<template>
  <el-dialog
    :visible.sync="visible"
    title="转派工单"
    width="60%"
    :modal="false"
    :fullscreen="fullscreen"
    class="fullscreen"
    @close="cancel"
  >
    <template slot="title">
      <modalTitle
        title="转派工单"
        @setFullscreen="fullscreen = !fullscreen"
      ></modalTitle>
    </template>
    <div class="sparepart-apply">
      <el-tabs
        v-model="tabValue"
        class="demo-monitor-tabs"
        @tab-click="handleClickTab"
      >
        <el-tab-pane label="执行人" name="1" />
        <!-- 非完成报工不显示辅助人 -->
        <el-tab-pane
          v-if="entranceValue == 'transfer'"
          label="辅助人"
          name="2"
        />
      </el-tabs>
      <div class="select-box">
        <el-form label-width="80px">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="工单单号">
                <el-input v-model="row.code" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门">
                <deptSelect v-model="groupId" @changeGroup="deptClick" />
                <!-- <selectTree
                        ref="treeDept"
                        class="form-input"
                        :options="treeList"
                        size="small"
                        :props="{
                          value: 'code',
                          label: 'name',
                          children: 'children',
                        }"
                        @getValue="deptClick"
                      /> -->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="" label-width="10px">
                <el-input v-model="name" placeholder="搜索姓名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" style="text-align: right">
              <el-form-item label="" label-width="10px">
                <el-button @click="search" type="primary" icon="el-icon-search"
                  >搜索</el-button
                >
                <el-button @click="reset" icon="el-icon-refresh-left"
                  >重置</el-button
                >
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="data-tab">
        <ele-pro-table
      :page-size="defPageSize"
          ref="tableRef2"
          :pageSizes="tablePageSizes"
          row-key="id"
          :columns="columns"
          :datasource="datasource"
          @select-all="handleSelectAll"
          @selection-change="handleSelectionChange"
          cache-key="redeployOther"
          :header-cell-class-name="headerCellClassName"
        >
        </ele-pro-table>
      </div>
      <div slot="footer" class="footer">
        <el-button @click="cancel">返回</el-button>
        <el-button
          v-if="entranceValue == 'transfer'"
          :loading="btnLoading"
          type="primary"
          @click="submit"
          >提交</el-button
        >
        <el-button
          v-if="entranceValue == 'noFinishSubmit'"
          :loading="btnLoading"
          type="primary"
          @click="confirm"
          >确认</el-button
        >
      </div>
    </div>
  </el-dialog>
</template>

<script>
  import modalTitle from '@/components/modalTitle.vue';
  import deptSelect from '@/components/CommomSelect/dept-select.vue';
  import {
    workOrderRotate,
    addAssists
  } from '@/api/maintenance/patrol_maintenance';
  import { getUserPage } from '@/api/system/organization';
  export default {
    components: { deptSelect, modalTitle },
    props: {
      // sourceType: {
      //   type: Number, //1,保养工单;2,维修工单
      //   required: true
      // }
    },
    data() {
      return {
        fullscreen: false,
        btnLoading: false,
        visible: false,
        treeList: [],
        pages: {
          pageNum: 1,
          size: 15
        },
        total: 0,
        selectedRow: {},
        selectedRowData: [],
        groupId: '',
        executorDeptName: '',
        name: '',
        row: {},
        columns: [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center'
            // selectable: (row, index) => {
            //  return row.id !== this.row.executeUserId;
            // }
          },
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'jobNumber',
            label: '工号',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'name',
            label: '姓名',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'phone',
            label: '电话',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'groupName',
            label: '部门',
            align: 'center',
            showOverflowTooltip: true
          }
        ],
        tabValue: '',
        selectedRowDataId: '',
        tableData: [],
        // arry: [],
        entranceValue: ''
      };
    },
    created() {
      this.getList();
    },

    methods: {
      async getList() {
        const data = await getUserPage({
          pageNum: 1,
          size: -1,
          groupId: '',
          name: '',
          groupId: this.groupId
        });
        this.tableData = data.list;
      },
      handleClickTab(tab, event) {
        // this.selectedRow = {};
        // this.selectedRowData = [];
        this.tabValue = tab.name;
        this.$refs.tableRef2.clearSelection();
        console.log(this.selectedRowData, '[this.selectedRow]');

        console.log(tab.name);
        if (tab.name == 1) {
          this.$refs.tableRef2.setSelectedRows([this.selectedRow]);
        } else {
          this.$refs.tableRef2.setSelectedRows(this.selectedRowData);
        }
      },
      open(row, val) {
        this.entranceValue = val;
        this.tabValue = '1';
        // //非完成报工
        // if (val == 'noFinishSubmit') {
        //   this.tabValue = '1';
        // }
        // // 转派
        // if (val == 'transfer') {
        //   if (row.assistsName == '') {
        //     this.tabValue = '2';
        //   } else {
        //     this.tabValue = '1';
        //   }
        // }
        this.row = row;
        this.name = '';
        this.groupId = '';
        this.executorDeptName = '';
        this.visible = true;
        this.$refs.tableRef2.clearSelection();
      },
      // handleDone() {
      //   console.log('handDone');
      //   this.$nextTick(() => {
      //     this.arry.forEach((item) => {
      //       this.tableData.find((item2) => {
      //         if (item == item2.id) {
      //           console.log(item2, 'item2');
      //           this.$refs.tableRef2.toggleRowSelection(item2, true);
      //         }
      //       });
      //     });
      //   });
      // },
      //重置
      reset() {
        this.name = '';
        this.search();
      },
      // 搜索
      search() {
        this.$refs.tableRef2.reload();
      },

      deptClick(data) {
        if (data) {
          this.$refs.tableRef2.reload();
        }
      },

      // 获取审核人列表、巡点检人员
      async datasource({ page, limit, where, order }) {
        this.selectedRow = {};
        // 如果传了参数就是获取巡点检人员数据
        return getUserPage({
          pageNum: page,
          size: limit,
          ...where,
          groupId: this.groupId,
          name: this.name
        });
      },
      handleSelectAll(selection) {
        this.$refs.tableRef2.clearSelection();
      },
      handleSelectionChange(row) {
        if (!row || !row.length) {
          return;
        }

        if (this.tabValue == '1') {
          this.selectedRow = row[row.length - 1];
          if (row.length > 1) {
            this.$refs.tableRef2.clearSelection();
            this.$refs.tableRef2.toggleRowSelection(row.pop());
          }
        } else {
          this.selectedRowData = row;
          let arr = row.map((item) => {
            return item.id;
          });
          this.selectedRowDataId = arr.toString();
        }
      },
      headerCellClassName({ columnIndex }) {
        // 如果是第一列（通常是全选框），则返回自定义的class名
        if (columnIndex === 0) {
          return 'hide-selection-checkbox';
        }
        return '';
      },
      async submit() {
        let paramsArr = [];
        // if (this.selectedRow.id) {
        //   this.btnLoading = true;
        //   let params = {};
        //   await workOrderRotate(params).then(() => {
        //     this.$message.success(`该工单成功转派给${this.selectedRow.name}`);
        //     this.visible = false;
        //     this.$emit('refresh');
        //     this.btnLoading = false;
        //   });
        // }
        console.log(this.selectedRow, 'this.selectedRow');
        console.log(this.selectedRow, 'this.selectedRow');
        if (this.selectedRow.id) {
          paramsArr.push(
            workOrderRotate({
              acceptUserId: this.selectedRow.id,
              workOrderId: this.row.id
            })
          );
        }
        if (this.selectedRowDataId) {
          paramsArr.push(
            addAssists({
              acceptUserId: this.selectedRowDataId,
              workOrderId: this.row.id
            })
          );
        }
        if (paramsArr.length) {
          this.btnLoading = true;
          Promise.all(paramsArr)
            .then(() => {
              this.$message.success('工单转派成功');
              this.$emit('refresh');

              this.cancel();
            })
            .catch((error) => {
              this.$message.error('工单转派失败：' + error.message);
            })
            .finally(() => {
              this.btnLoading = false;
            });
        } else {
          this.$message.warning('请选择执行人或辅助人');
        }
        // if (this.tabValue == '1') {
        // } else {
        //   this.btnLoading = true;
        //   let params = {
        //     acceptUserId: this.selectedRowDataId,
        //     workOrderId: this.row.id
        //   };
        //   addAssists(params).then(() => {
        //     this.visible = false;
        //     this.$emit('refresh');
        //     this.btnLoading = false;
        //   });
        // }
      },
      confirm() {
        this.cancel();
        this.$emit('confirm', this.selectedRow);
      },
      cancel() {
        this.tabValue = '1';
        this.selectedRow = {};
        this.selectedRowData = [];
        this.selectedRowDataId = '';

        this.visible = false;
      }
    }
  };
</script>

<style lang="scss" scoped>
  .sparepart-apply {
    min-height: 40vh;
    .select-box {
      padding: 10px 0;
    }

    .material-item + .material-item {
      margin-top: 10px;
    }
  }

  .flex-between {
    display: flex;
    justify-content: space-between;
    padding-right: 20%;
  }

  .list-box {
    max-height: 60vh;
    overflow-y: auto;
    overflow-x: hidden;
  }

  .footer {
    padding: 10px;
    text-align: right;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  ::v-deep .hide-selection-checkbox .cell .el-checkbox {
    visibility: hidden !important;
  }
</style>
