<template>
  <el-dialog
    :visible.sync="visible"
    title="转派工单"
    width="60%"
    :modal="false"
    :fullscreen="fullscreen"
    class="fullscreen"
  >
    <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="0" />
        <el-tab-pane label="班组" name="1" />
      </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" v-if="tabValue == '1'">
              <el-form-item label="班组">
                <el-select
                  v-model="teamId"
                  size="small"
                  @change="teamChange"
                  style="width: 100%"
                >
                  <el-option
                    :value="i.id"
                    :label="i.name"
                    v-for="i in teamAllList"
                    :key="i.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <template v-if="tabValue == '0'">
              <el-col :span="12">
                <el-form-item label="部门">
                  <deptSelect v-model="groupId" @changeGroup="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>
            </template>
          </el-row>
        </el-form>
      </div>

      <div v-if="tabValue == '0'" class="data-tab">
        <ele-pro-table
          ref="tableRef2"
          row-key="id"
          :columns="columns"
          :datasource="datasource"
          cache-key="redeployOther"
          :header-cell-class-name="headerCellClassName"
          :selection.sync="selection"
        >
        </ele-pro-table>
      </div>
    </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>
  </el-dialog>
</template>

<script>
  import modalTitle from '@/components/modalTitle.vue';
  import deptSelect from '@/components/CommomSelect/dept-select.vue';
  import { getUserPage } from '@/api/system/organization';
  import { recordrulesplanReManualDispatchOrder } from '@/api/recordRules/index';
  import { getteampage } from '@/api/workforceManagement/team';

  export default {
    components: { deptSelect, modalTitle },
    props: {},
    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: '',
        selection: [],
        teamAllList: [],
        teamId: '',
        executeUser: []
      };
    },
    created() {
      this.getList();
      this.getAllTeamList();
    },

    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();
      },
      open(row, val = 'transfer') {
        this.entranceValue = val;

        // 转派
        if (val == 'transfer') {
          if (row.planExecuteType == '1') {
            // 班组
            this.tabValue = '1';
          } else {
            this.tabValue = '0';
          }
        }
        this.row = row;
        this.name = '';
        this.groupId = '';
        this.executorDeptName = '';
        this.visible = true;

        this.$nextTick(() => {
          this.$refs.tableRef2?.clearSelection();
        });
      },
      //重置
      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();
      },
      headerCellClassName({ columnIndex }) {
        // 如果是第一列（通常是全选框），则返回自定义的class名
        if (columnIndex === 0) {
          return 'hide-selection-checkbox';
        }
        return '';
      },
      async submit() {
        if (this.tabValue == '0' && this.selection.length == 0) {
          return this.$message.warning('请选择转派人员');
        }

        if (this.tabValue == '1' && !this.teamId) {
          return this.$message.warning('请选择班组');
        }

        let executeUser = null;

        if (this.tabValue == '0') {
          executeUser = this.selection.map((i) => {
            return {
              groupId: i.groupId,
              groupName: i.groupName,
              userId: i.id,
              userName: i.name
            };
          });
        } else {
          executeUser = this.executeUser;
        }

        this.btnLoading = true;

        let params = {
          executeUser,
          id: this.row.planId,
          // 0个人 1班组
          type: this.tabValue
        };
        recordrulesplanReManualDispatchOrder(params)
          .then(() => {
            this.$message.success(`该工单成功转派`);
            this.visible = false;
            this.$emit('refresh');
            this.btnLoading = false;
          })
          .catch(() => {
            this.btnLoading = false;
          });
      },
      confirm() {
        this.visible = false;
        this.$emit('confirm', this.selectedRow);
      },
      cancel() {
        this.tabValue = '0';
        this.selectedRow = {};
        this.selectedRowData = [];
        this.selection = [];
        this.executeUser = [];
        this.visible = false;
      },
      async getAllTeamList() {
        const { list } = await getteampage({
          pageNum: 1,
          size: -1
        });
        console.log('teamAllList 班组', list);
        this.teamAllList = list;
      },
      teamChange() {
        console.log('this.teamId', this.teamId);
        // 当前班组
        const currentTeam = this.teamAllList.find(
          (item) => item.id === this.teamId
        );
        if (currentTeam) {
          // 同步执行人
          this.executeUser = [
            {
              teamId: currentTeam.id,
              teamName: currentTeam.name
            }
          ];
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  .sparepart-apply {
    .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>
