<template>
  <div class="manage-publicCar main-wrap">
    <el-form class="search-bar">
      <div class="grid-content">
        <el-input v-model.trim="filters.name" :maxlength="20" placeholder="请输入申请人" clearable></el-input>
      </div>
      <div class="grid-content">
        <el-input v-model.trim="filters.department" :maxlength="20" placeholder="请输入用车部门" clearable></el-input>
      </div>
      <div class="grid-content">
        <el-select v-model="filters.dealResult" filterable clearable placeholder="处理状态">
          <el-option v-for="item in dealResultOptions" :key="item.id" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="grid-content">
        <el-date-picker v-model="filters.createDate" type="datetime" placeholder="请输入申请开始时间" clearable>
        </el-date-picker>
      </div>
      <div class="grid-content">
        <el-date-picker v-model="filters.endDate" type="datetime" placeholder="请输入用车结束时间" clearable>
        </el-date-picker>
      </div>
      <el-button type="primary" icon="el-icon-search" @click="searchList">搜索</el-button>
      <el-button type="primary" icon="el-icon-download" @click="exportList">导出</el-button>
    </el-form>

    <div class="tabel-wrap">
      <el-table border v-loading="loading" :data="list" style="width: 100%">
        <el-table-column type="index" label="序号" width="50">
        </el-table-column>
        <el-table-column prop="name" label="申请人" min-width="80">
        </el-table-column>
        <el-table-column prop="createDate" :formatter="(c,r,val) => $formatDate(new Date(val),'yyyy-MM-dd')" label="申请时间" min-width="80">
        </el-table-column>
        <el-table-column prop="department" label="用车部门" min-width="100">
        </el-table-column>
        <el-table-column prop="categoryName" :formatter="getCategoryValue" label="用车类型" min-width="100">
        </el-table-column>
        <el-table-column prop="userCount" label="用车人数" min-width="80">
        </el-table-column>
        <el-table-column prop="dealResult" :formatter="getResultValue" label="处理状态" min-width="80">
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="130" align="center">
          <template slot-scope="scope">
            <template v-if="scope.row.dealResult == 1">
              <el-button type="primary" size="mini" class="operationBtnWidth" @click="showEditDialog(1, scope)">处理</el-button>
            </template>
            <template v-else-if="scope.row.dealResult == 2">
              <el-button type="primary" size="mini" class="operationBtnWidth" @click="showEditDialog(0, scope)">详情</el-button>
              <el-button type="primary" size="mini" class="operationBtnWidth" @click="showPrintDialog(scope)">打印</el-button>
            </template>
            <template v-else>
              <el-button type="primary" size="mini" class="operationBtnWidth" @click="showEditDialog(0, scope)">详情</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination layout="prev, pager, next" :current-page="pagination.pageNum" :page-size="pagination.pageSize" :total="pagination.total" @current-change="changePage">
      </el-pagination>
    </div>

    <drag-dialog :title="editType ? '处理' : '详情'" :visible.sync="dialogEditVisible" :before-close="resetEditDialog" width="70%" top="5vh">
      <el-form class="editForm" :disabled="loading">
        <div class="line-wrap">
          <el-form-item class="col-line-3" label="用车部门" label-width="100px">
            <span>{{selected.department}}</span>
          </el-form-item>
          <el-form-item class="col-line-3" label="用车申请时间" label-width="100px">
            <span>{{selected.createDate}}</span>
          </el-form-item>
        </div>
        <div class="line-wrap">
          <el-form-item class="col-line-3" label="申请人" label-width="100px">
            <span>{{selected.name}}</span>
          </el-form-item>
          <el-form-item class="col-line-3" label="用车人数" label-width="100px">
            <span>{{selected.userCount}}</span>
          </el-form-item>
        </div>
        <el-form-item label="用车类型" label-width="100px">
          <span>{{selected.categoryName}}</span>
        </el-form-item>
        <el-form-item label="用车起止时间" label-width="100px">
          <span>{{selected.beginDate}} - {{selected.endDate}}</span>
        </el-form-item>
        <el-form-item label="用车详细路线" label-width="100px">
          <span>{{selected.lineDescription}}</span>
        </el-form-item>
        <div class="line-wrap">
          <el-form-item class="col-line-3" label="派车人" label-width="100px">
            <span>{{selected.dealName}}</span>
          </el-form-item>
          <el-form-item class="col-line-3-1" label="派车车牌" label-width="100px">
            <el-select class="w100" v-if="editType" v-model="selected.carPlateList" filterable clearable multiple placeholder="派车车牌">
              <el-option v-for="item in carPlateOptions" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
            <span v-else>{{selected.carPlate}}</span>
          </el-form-item>
        </div>
        <div class="line-wrap">
          <el-form-item class="col-line-3" label="出车公里数" label-width="100px">
            <el-input-number v-model.trim="selected.startKilometers" :controls="false" :precision="0" :min="0" :max="9999999" placeholder="" clearable></el-input-number>
          </el-form-item>
          <el-form-item class="col-line-3" label="收车公里数" label-width="100px">
            <el-input-number v-model.trim="selected.stopKilometers" :controls="false" :precision="0" :min="0" :max="9999999" placeholder="" clearable></el-input-number>
          </el-form-item>
          <el-form-item class="col-line-3" label="实际公里数" label-width="100px">
            <el-input-number v-model.trim="selected.trueKilometers" :controls="false" :precision="0" :min="0" :max="9999999" placeholder="" clearable></el-input-number>
          </el-form-item>
        </div>
        <el-form-item label="资金来源" label-width="100px">
          <el-input v-model.trim="selected.priceSource" placeholder="可不填" :maxlength="20" clearable></el-input>
        </el-form-item>
        <div class="line-wrap">
          <el-form-item class="col-line-3" label="用车单价" label-width="100px">
            <el-input-number v-model.trim="selected.price" :controls="false" :precision="2" :min="0" :max="9999999.99" placeholder="可不填" clearable></el-input-number>
          </el-form-item>
          <el-form-item class="col-line-3" label="用车金额" label-width="100px">
            <el-input-number v-model.trim="selected.totalPrice" :controls="false" :precision="2" :min="0" :max="9999999.99" placeholder="可不填" clearable></el-input-number>
          </el-form-item>
        </div>

        <!-- <template v-else>
          <el-form-item class="col-line-2" label="用车单价" label-width="100px">
            <span>{{selected.price}}</span>
          </el-form-item>
          <el-form-item class="col-line-2" label="用车金额" label-width="100px">
            <span>{{selected.totalPrice}}</span>
          </el-form-item>
        </template> -->
        <el-form-item v-if="editType" label-width="100px">
          <div class="item-value-start">
            <el-radio v-model="selected.dealResult" @change="toogleDealResult" :label="2">同意</el-radio>
            <el-radio v-model="selected.dealResult" @change="toogleDealResult" :label="3">不同意</el-radio>
            <el-input v-if="selected.dealResult === 3" v-model.trim="selected.dealOpinion" :maxlength="20" placeholder="可不填" clearable></el-input>
          </div>
        </el-form-item>
        <el-form-item v-else label="处理结果" label-width="100px">
          <span>{{selected.dealResult ===2?'同意':selected.dealOpinion}}</span>
        </el-form-item>
      </el-form>
      <div v-if="editType" slot="footer" class="dialog-footer">
        <el-button @click="resetEditDialog">取 消</el-button>
        <el-button type="primary" @click="dealApplyHandle">确 定</el-button>
      </div>
      <div v-else slot="footer" class="dialog-footer">
        <el-button @click="resetEditDialog">取 消</el-button>
        <el-button type="primary" @click="updateDealHandle">确 定</el-button>
      </div>
    </drag-dialog>
    <drag-dialog title="用车管理-打印" :visible.sync="dialogPrintVisible" :before-close="resetPrintDialog" width="70%" top="5vh">
      <iframe v-if="dialogPrintVisible" class="printIframe" ref="print" :src="`/print/publicCar?data=${JSON.stringify(selected)}`" frameborder="0" :data-item="selected"></iframe>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetPrintDialog">取 消</el-button>
        <el-button type="primary" @click="printHandle">打 印</el-button>
      </div>
    </drag-dialog>
  </div>
</template>

<script>
import listMixin from '@/mixin/listPage.js';
import { mapGetters, mapActions } from 'vuex';
import store from './store.js';
import { dealApply, exportApplyList } from '@/api/management/publicCar.js';
// import printJS from 'print-js';

export default {
  beforeRouteEnter(to, from, next) {
    store.install();
    next();
  },
  mixins: [listMixin],
  data() {
    return {
      filters: {
        name: '',
        department: '',
        dealResult: '',
        createDate: '',
        endDate: '',
      },
      selected: {},
      dialogPrintVisible: false,
      //1处理中 2已同意 3未同意
      dealResultOptions: [
        {
          label: '处理中',
          value: 1,
        },
        {
          label: '已同意',
          value: 2,
        },
        {
          label: '未同意',
          value: 3,
        },
      ],
    };
  },
  computed: {
    ...mapGetters(['carPlateOptions', 'userInfo']),
    ...mapGetters('management/publicCar', ['list', 'pagination']),
  },
  methods: {
    ...mapActions(['fetchCarPlateOptions']),
    ...mapActions('management/publicCar', ['fetchList']),
    getResultValue(c, r, val) {
      let item = this.dealResultOptions.find(item => item.value == val);
      return item ? item.label : val;
    },
    initSelected() {
      this.selected = {
        userId: '',
        name: '',
        department: '',
        duty: '',
        title: '',
        sex: '',
        birthday: '',
        jobNumber: '',
        cellphone: '',
        carPlateList: [],
      };
    },
    getCategoryValue(c, r, val) {
      let list = JSON.parse(val);
      let item = list.find(item => item.checked);
      return item ? item.name : '';
    },
    exportList() {
      const filters = this.getFilters();
      exportApplyList(filters);
    },
    showEditDialog(type, data) {
      this.editType = type;
      if (this.carPlateOptions.length == 0) {
        this.fetchCarPlateOptions();
      }
      let categoryName = JSON.parse(data.row.categoryName).map(
        item => (item.checked ? `☑ ${item.name}` : `▢ ${item.name}`)
      );
      this.selected = {
        id: data.row.id,
        department: data.row.department,
        createDate: data.row.createDate,
        name: data.row.name,
        userCount: data.row.userCount,
        categoryName: categoryName.join('； '),
        // beginDate: this.$formatDate(
        //   new Date(data.row.beginDate),
        //   'yyyy-MM-dd hh:mm:ss'
        // ),
        // endDate: this.$formatDate(
        //   new Date(data.row.endDate),
        //   'yyyy-MM-dd hh:mm:ss'
        // ),
        beginDate: data.row.beginDate,
        endDate: data.row.endDate,
        lineDescription: data.row.lineDescription,
        dealName: data.row.dealName || this.userInfo.name,
        carPlate: data.row.carPlate,
        carPlateList: data.row.carPlate ? data.row.carPlate.split(',') : [],
        startKilometers: data.row.startKilometers,
        stopKilometers: data.row.stopKilometers,
        trueKilometers: data.row.trueKilometers,
        priceSource: data.row.priceSource,
        price: data.row.price,
        totalPrice: data.row.totalPrice,
        dealResult: data.row.dealResult,
        dealOpinion: data.row.dealOpinion,
      };
      this.dialogEditVisible = true;
    },
    resetEditDialog(done) {
      this.initSelected();
      done && typeof done == 'function'
        ? done()
        : (this.dialogEditVisible = false);
    },
    toogleDealResult(val) {
      if (val === 2) {
        this.selected.dealOpinion = '';
      }
    },
    validateSelect() {
      if (this.selected.dealResult == 2 && !this.selected.carPlateList.length) {
        this.$message.error('请选择派车车牌！');
        return;
      }
      if (this.selected.dealResult == 1) {
        this.$message.error('请选择处理意见！');
        return;
      }
      return true;
    },
    dealApplyHandle() {
      if (!this.validateSelect()) {
        return;
      }
      this.$confirm(`确认要处理吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          let dealOpinion = '';
          if (this.selected.dealResult == 3) {
            dealOpinion = this.selected.dealOpinion
              ? `不同意 - ${this.selected.dealOpinion}`
              : `不同意 - 无车可派送`;
          }
          let carPlate = this.selected.carPlateList.map(
            id => this.carPlateOptions.find(i => i.id === id).name
          );
          const entity = {
            userId: this.userInfo.id,
            id: this.selected.id,
            carPlate: carPlate.join(','),
            startKilometers: this.selected.startKilometers,
            stopKilometers: this.selected.stopKilometers,
            trueKilometers: this.selected.trueKilometers,
            priceSource: this.selected.priceSource,
            price: this.selected.price,
            totalPrice: this.selected.totalPrice,
            dealName: this.selected.dealName,
            dealResult: this.selected.dealResult,
            dealOpinion: dealOpinion,
          };
          dealApply(entity)
            .then(res => {
              console.log(res);
              this.fetchList();
              this.$message.success(res.msg);
              this.resetEditDialog();
            })
            .catch(err => {
              console.log(err);
              this.$message.error(err.msg || '处理失败！');
            });
        })
        .catch(action => {
          console.log(action);
        });
    },
    updateDealHandle() {
      const entity = {
        id: this.selected.id,
        startKilometers: this.selected.startKilometers,
        stopKilometers: this.selected.stopKilometers,
        trueKilometers: this.selected.trueKilometers,
        priceSource: this.selected.priceSource,
        price: this.selected.price,
        totalPrice: this.selected.totalPrice,
      };
      dealApply(entity)
        .then(res => {
          console.log(res);
          this.fetchList();
          this.$message.success(res.msg);
          this.resetEditDialog();
        })
        .catch(err => {
          console.log(err);
          this.$message.error(err.msg || '处理失败！');
        });
    },
    showPrintDialog(data) {
      let categoryName = JSON.parse(data.row.categoryName).map(
        (item, index) =>
          item.checked
            ? `☑ ${index + 1}、${item.name}`
            : `▢ ${index + 1}、${item.name}`
      );
      this.selected = {
        id: data.row.id,
        department: data.row.department,
        createDate: data.row.createDate,
        name: data.row.name,
        userCount: data.row.userCount,
        categoryName: categoryName.join('； '),
        // beginDate: this.$formatDate(
        //   new Date(data.row.beginDate),
        //   'yyyy-MM-dd hh:mm:ss'
        // ),
        // endDate: this.$formatDate(
        //   new Date(data.row.endDate),
        //   'yyyy-MM-dd hh:mm:ss'
        // ),

        beginDate: data.row.beginDate,
        endDate: data.row.endDate,
        lineDescription: data.row.lineDescription,
        dealName: data.row.dealName,
        carPlate: data.row.carPlate,
        startKilometers: data.row.startKilometers,
        stopKilometers: data.row.stopKilometers,
        trueKilometers: data.row.trueKilometers,
        priceSource: data.row.priceSource,
        price: data.row.price,
        totalPrice: data.row.totalPrice,
        dealResult: data.row.dealResult,
        dealOpinion: data.row.dealOpinion,
      };
      this.dialogPrintVisible = true;
    },
    resetPrintDialog(done) {
      this.selected = {};
      done && typeof done == 'function'
        ? done()
        : (this.dialogPrintVisible = false);
    },
    printHandle() {
      this.$refs.print.contentWindow.vmPrint();
    },
  },
};
</script>

<style lang="scss">
.manage-publicCar {
  .el-input-number .el-input__inner {
    text-align: left;
  }
  .item-value {
    display: flex;
    justify-content: space-between;
  }
  .item-value-start {
    display: flex;
    .el-radio {
      line-height: 40px;
    }
    .el-input {
      margin-left: 30px;
    }
  }
  .w100 {
    width: 100%;
  }
  .printIframe {
    width: 100%;
    height: 500px;
  }
}
</style>
