<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model:page="page"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      :before-open="beforeOpen"
      @on-load="onLoad"
    >
      <template #menu-left>
        <el-button type="danger" icon="el-icon-delete" @click="handleDelete"
          >删 除
        </el-button>
        <el-button type="success" icon="el-icon-upload" @click="handleImport"
          >导入
        </el-button>
      </template>
      <template #menu="scope">
        <el-button type="text" @click="setCrew(scope.row)">设置班组人员</el-button>
        <el-button type="text" @click="changeTime(scope.row, 0)">日分派时间</el-button>
        <el-button type="text" @click="changeTime(scope.row, 1)"
          >特殊日分派时间</el-button
        >
        <el-button type="text" @click="changeTime(scope.row, 2)">轮换时间</el-button>
      </template>
      <template #teamLeader="{ row }">
        {{ row.teamLeaderRealName }}
      </template>
      <template #planner="{ row }">
        {{ row.plannerRealName }}
      </template>
      <template #dispatcher="{ row }">
        {{ row.dispatcherRealName }}
      </template>
      <!-- <template #csId="{ row }">
        {{ row.bsClassesSet.csName }}
      </template> -->
      <!-- <template #csId-form="{ type }">
        <span v-show="type == 'edit' || type == 'add'">
          <el-select v-model="form.bsClassesSet.csId" placeholder="请选择班次">
            <el-option
              v-for="item in csData"
              :key="item.csId"
              :value="item.csId"
              :label="item.csName"
            ></el-option>
          </el-select>
        </span>
      </template> -->
      <template #teamLeader-form="{ type }">
        <span v-show="type == 'edit' || type == 'add'">
          <el-select v-model="form.teamLeader" placeholder="请选择班组长"
          filterable remote :remote-method="getTeamUser">
            <el-option
              v-for="item in userData"
              :key="item.id"
              :value="item.id"
              :label="item.realName"
            ></el-option>
          </el-select>
        </span>
      </template>
      <template #planner-form="{ type }">
        <span v-show="type == 'edit' || type == 'add'">
          <el-select v-model="form.planner" placeholder="请选择计划员"
          filterable remote :remote-method="getPlanner">
            <el-option
              v-for="item in plannerData"
              :key="item.id"
              :value="item.id"
              :label="item.realName"
            ></el-option>
          </el-select>
        </span>
      </template>
      <template #dispatcher-form="{ type }">
        <span v-show="type == 'edit' || type == 'add'">
          <el-select v-model="form.dispatcher" placeholder="请选择调度员"
          filterable remote :remote-method="getDispatcher">
            <el-option
              v-for="item in dispatcherData"
              :key="item.id"
              :value="item.id"
              :label="item.realName"
            ></el-option>
          </el-select>
        </span>
      </template>
    </avue-crud>
    <el-dialog class="setCrewBox" title="设置人员" append-to-body v-model="crewDialog" width="60%">
      <tree-transfer
        class="trans_ware"
        style="margin-top: 10px;"
        ref="transferRef"
        :titleList="['未选择', '已选择']"
        v-model:fromData="noChooseUser"
        v-model:toData="chooseUser"
        :defaultProps="{
          id: 'id', // 节点id
          parentId: 'parentId', // 父节点id
          label: 'label',
          children: 'children',
          disabled: 'disabled',
        }"
        rootPid="0"
      />
      <template #footer>
          <span class="dialog-footer">
              <el-button @click="crewDialog = false">取 消</el-button>
              <el-button type="primary" @click="submitPeople">确 定</el-button>
          </span>
      </template>
    </el-dialog>
    <el-dialog title="时间" append-to-body v-model="timeDialog" width="60%">
      <div>
        <el-button type="primary" icon="el-icon-plus" @click="insertEvent()"
          >插入一行</el-button
        >
        <el-button plain type="danger" @click="remove">删除选择行</el-button>
        <!-- <el-button type="primary" @click="handleSave">保存</el-button> -->
      </div>
      <div style="margin-top: 20px">
        <el-table
          :data="timeList"
          @select="selectChange"
        >
          <el-table-column type="selection" width="55px"></el-table-column>
          <el-table-column align="center" label="开始时间">
            <template #default="scope">
              <el-time-select
                v-model="scope.row.startTime"
                start="00:00"
                step="00:15"
                end="24:00"
                placeholder="选择时间"
              >
              </el-time-select>
            </template>
          </el-table-column>
          <el-table-column align="center" label="结束时间">
            <template #default="scope">
              <el-time-select
                v-model="scope.row.endTime"
                start="00:00"
                step="00:15"
                end="24:00"
                placeholder="选择时间"
              >
              </el-time-select>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
          <span class="dialog-footer">
              <el-button @click="timeDialog = false">取 消</el-button>
              <el-button type="primary" @click="submitTime">确 定</el-button>
          </span>
      </template>
    </el-dialog>

    <!-- 导入 -->
    <basic-import v-if="isShowImport" title="导入" :isShow="isShowImport"
      templateUrl="/blade-desk/BA/TeamSet/downloadExcelTemplate"
      templateName="班组模板.xls"
      importUrl="/blade-desk/BA/TeamSet/importExcel"
     @closeDialog="closeDialog"></basic-import>

  </basic-container>
</template>

<script>
import {getList,addTeam,updateTeam,getAllUser,deleteTeam,getNotSelectUser,getSelectUser,getDeptUser,saveUser,getDispatchTime,saveDispatchTime} from "@/api/basicData/teamManagement.js"
import basicImport from '@/components/basic-import/main.vue'
import treeTransfer from 'tree-transfer-vue3' // 引入
export default {
  components: {
    basicImport,
    treeTransfer
  },
  data() {
    return {
      isShowImport:false,
      data: [],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      peopleValue:[],
      peopleData:[],
      timeList: [],
      deleteTidArr: [], //删除数据
      form: {},
      crewDialog: false,
      timeDialog: false,
      noChooseUser:[],  //未选人员
      chooseUser:[],    //已选人员
      csData: [
        {
          csId: 18,
          csName: "白班",
          keyValue: 18,
        },
        {
          csId: 19,
          csName: "晚班",
          keyValue: 19,
        },
      ],
      crewData: [], //班组人员数据
      userData: [],
      plannerData:[],
      dispatcherData:[],
      query: {},
      loading: true,
      excelBox: false,
      option: {
        tip: false,
        height: "auto",
        calcHeight: 32,
        simplePage: false,
        searchShow: true,
        searchMenuSpan: 6,
        searchIcon: true,
        searchIndex: 3,
        tree: false,
        border: true,
        index: true,
        selection: true,
        viewBtn: false,
        delBtn: false,
        editBtnText: "修改",
        viewBtnText: "详情",
        labelWidth: 120,
        menuWidth: 440,
        dialogWidth: 600,
        dialogClickModal: false,
        searchEnter: true,
        filterBtn: true,
        searchShowBtn: false,
        excelBtn: true,
        showOverflowTooltip: true,
        searchLabelPosition: "left",
        searchGutter: 24,
        searchSpan: 6,
        menuAlign: "center",
        gridBtn: false,
        searchMenuPosition: "right",
        addBtnIcon: " ",
        viewBtnIcon: " ",
        delBtnIcon: " ",
        editBtnIcon: " ",
        align: "center",
        column: [
          {
            label: "编码",
            prop: "tsCode",
            search: true,
            sortable: true,
            filter: true,
            span: 24,
            width: 150,
            rules: [
              {
                required: true,
                message: "请输入编码",
                trigger: "blur",
              },
            ],
          },
          {
            label: "名称",
            prop: "tsName",
            sortable: true,
            filter: true,
            span: 24,
            width: 150,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入名称",
                trigger: "blur",
              },
            ],
          },
          {
            label: "班组长",
            prop: "teamLeader",
            search: false,
            type: "select",
            sortable: true,
            filter: true,
            span: 24,
            width: 150,
            rules: [
              {
                required: true,
                message: "请选择班组长",
                trigger: "blur",
              },
            ],
            dicUrl:"/api/blade-system/user/page?current=1&size=9999",
            props: {
              label: "realName",
              value: "id",
              res:"data.records"
            },
          },
          {
            label: "计划员",
            prop: "planner",
            search: false,
            sortable: true,
            filter: true,
            type: "select",
            span: 24,
            width: 150,
            rules: [
              {
                required: true,
                message: "请选择计划员",
                trigger: "blur",
              },
            ],
            dicUrl:"/api/blade-system/user/page?current=1&size=9999",
            props: {
              label: "realName",
              value: "id",
              res:"data.records"
            },
          },
          {
            label: "调度员",
            prop: "dispatcher",
            search: true,
            sortable: true,
            filter: true,
            remote: true,
            type: "select",
            span: 24,
            width: 150,
            rules: [
              {
                required: true,
                message: "请选择调度员",
                trigger: "blur",
              },
            ],
            dicUrl:"/api/blade-system/user/page?current=1&size=9999&realName={{key}}",
            props: {
              label: "realName",
              value: "id",
              res:"data.records"
            },
          },
          {
            label: "班组人员",
            prop: "teamMember",
            search: false,
            sortable: true,
            filter: true,
            editDisplay: false,
            addDisplay: false,
            span: 24,
            width: 150,
            rules: [
              {
                required: true,
                message: "请选择班组人员",
                trigger: "blur",
              },
            ],
          },
          {
            label: "班次",
            prop: "csId",
            search: false,
            type: "select",
            sortable: true,
            filter: true,
            span: 24,
            width: 150,
            props: {
              label: "name",
              value: "id",
            },
            dicUrl:"/api/blade-desk/BA/Shifts/listForSelect"
          },
          {
            label: "类型分类",
            prop: "tsType",
            search: false,
            type: "select",
            sortable: true,
            filter: true,
            span: 24,
            width: 150,
            dicData: [
              { value: 1,label: "针孔",},
              { value: 2,label: "壳体",},
              { value: 3,label: "烧结",},
              { value: 4,label: "园区",},
              // { value: 5,label: "外协",},
            ],
          },
          {
            label: "日分派时间",
            prop: "dayPutDueTime",
            search: false,
            sortable: true,
            editDisplay: false,
            filter: true,
            addDisplay: false,
            span: 24,
            width: 150,
            rules: [
              {
                required: true,
                message: "请输入日分派时间",
                trigger: "blur",
              },
            ],
          },
          {
            label: "特殊日分派时间",
            prop: "specDayPutDueTime",
            search: false,
            sortable: true,
            editDisplay: false,
            filter: true,
            addDisplay: false,
            span: 24,
            width: 150,
            rules: [
              {
                required: true,
                message: "请输入特殊日分派时间",
                trigger: "blur",
              },
            ],
          },
          {
            label: "轮换时间",
            prop: "exChangeTime",
            search: false,
            sortable: true,
            editDisplay: false,
            filter: true,
            addDisplay: false,
            span: 24,
            width: 150,
            rules: [
              {
                required: true,
                message: "请输入轮换时间",
                trigger: "blur",
              },
            ],
          },
          {
            label: "特殊",
            prop: "special",
            search: false,
            type: "select",
            sortable: true,
            filter: true,
            span: 24,
            width: 150,
            dicData: [
              {
                value: '1',
                label: "是",
              },
              {
                value: '0',
                label: "否",
              },
            ],
          },
        ],
      },
      selectionList: [],
      checkId:'',
      checkTimeType:0
    };
  },
  mounted() {},
  methods: {
    // 点击导入按钮
    handleImport() {
      this.isShowImport = true
    },
    handleDelete(){
      if(this.selectionList.length == 0){
        this.$message.error('请至少选择一条数据')
        return
      }
      deleteTeam({
        ids: this.selectionList.map(item => item.id).join(',')
      }).then(res =>{
        if(res.data.code == 200){
          this.$message.success('删除成功')
          this.onLoad()
        }
      })
    },
    // 多选
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    getTeamUser(query){
      if(query == ''){
        getAllUser({
          current:1,
          size:9999
        }).then(res =>{
          this.userData = res.data.data.records
        })
      }else{
        getAllUser({
          current:1,
          size:9999,
          realName:query
        }).then(res =>{
          this.userData = res.data.data.records
        })
      }
    },
    getPlanner(query){
      if(query == ''){
        getAllUser({
          current:1,
          size:9999
        }).then(res =>{
          this.plannerData = res.data.data.records
        })
      }else{
        getAllUser({
          current:1,
          size:9999,
          realName:query
        }).then(res =>{
          this.plannerData = res.data.data.records
        })
      }
    },
    getDispatcher(query){
      if(query == ''){
        getAllUser({
          current:1,
          size:9999
        }).then(res =>{
          this.dispatcherData = res.data.data.records
        })
      }else{
        getAllUser({
          current:1,
          size:9999,
          realName:query
        }).then(res =>{
          this.dispatcherData = res.data.data.records
        })
      }
    },
    rowUpdate(row, index, done, loading) {
      updateTeam(row).then(res =>{
        if(res.data.code == 200){
          this.$message.success('修改成功')
          this.onLoad()
          done()
        }
      })
    },
    rowSave(row, done, loading) {
      console.log('row-----------',row)
      addTeam(row).then(res =>{
        if(res.data.code == 200){
          this.$message.success('添加成功')
          this.onLoad()
          done()
        }
      })
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    rowDel(row, index, done) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {});
    },
    // 设置时间
    changeTime(row, val) {
      this.checkId = row.id;
      this.checkTimeType = val;
      getDispatchTime({
        id:row.id,
        special:val
      }).then(res =>{
        console.log('res-----------',res)
        res.data.data.map(item =>{
          item._select = false
        })
        this.timeList = res.data.data;
        this.timeDialog = true;
      })
      // this.timeList = [];
      // // if(val == 1){
      // this.timeList = [
      //   { startTime: "00:00", endTime: "00:15", _select: false },
      //   { startTime: "00:15", endTime: "00:20", _select: false },
      //   { startTime: "00:45", endTime: "01:00", _select: false },
      // ];
      // this.timeDialog = true;
      // // }
    },
    submitTime(){
      if(this.timeList.length == 0){
        this.$message.error("请添加一条数据！");
        return;
      }
      const  timeData  = []
      this.timeList.map(item =>{
        timeData.push({
          startTime:item.startTime,
          endTime:item.endTime,
          special:this.checkTimeType
        })
      })
      let params = {
        id:this.checkId,
        special:this.checkTimeType,
        teamTimes:timeData
      }
      saveDispatchTime(params).then(res =>{
        if(res.data.code === 200){ 
          this.$message.success('设置成功');
          this.timeDialog = false
          this.onLoad()
        }
      })
    },
    selectChange(list, row){
      row._select = !row._select;
    },
    // 插入一行
    insertEvent() {
      const record = { _select: false };
      this.timeList.push(record);
    },
    //删除所选行
    remove() {
      let arr = this.timeList.filter((item) => item._select);
      if (arr.length != 0) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          if (this.rowId) {
            let deleteData = this.timeList.filter((item) => item._select);
            this.deleteTidArr = deleteData.filter((item) => item.tidId);
          }
          let deleteArr = this.timeList.filter((item) => !item._select);
          this.timeList = deleteArr;
        });
      } else {
        this.$message.error("请至少选择一条数据进行操作！");
      }
    },
    // 点击保存按钮
    handleSave() {
      if (this.timeList.length == 0) {
        this.$message.error("请至少填写一条数据");
      } else {
        let tmp = this.timeList.find((item) => item.startTime && item.endTime);
        if (!tmp) {
          this.$message.error("数据请填写完整!");
        }
      }
    },
    processTree(nodes, isRootLevel = true) {
      return nodes.map(item => {
        // 第一层：parentId = 0；其他层：parentId = item.pid
        const parentId = isRootLevel ? 0 : item.pid;

        const newItem = {
          ...item,
          parentId // 添加 parentId 字段
          // 注意：保留原有的 pid 字段，除非你不需要
        };

        // 递归处理 children，下一层不再是根层
        if (Array.isArray(item.children)) {
          newItem.children = this.processTree(item.children, false);
        }

        return newItem;
      });
    },
    // 设置班组人员
    async setCrew(row) {
      this.checkId = row.id;
      const users = await getDeptUser({teamSetId: row.id});
      this.chooseUser = this.processTree(users.data.data.teamSelects)
      this.noChooseUser = this.processTree(users.data.data.teamUnSelects)
      this.crewDialog = true;

      // const notUser = await getNotSelectUser({id: row.id});
      // const user = await getSelectUser({id: row.id});
      // console.log('notUser============', notUser);
      // console.log('user============', user);
      // this.peopleData = [...notUser.data.data,...user.data.data]
      // this.peopleValue = user.data.data.map(item => item.id)
      // this.crewDialog = true;
    },

    getLeafIds(nodes) {
      const leafIds = [];

      function traverse(items) {
        if (!Array.isArray(items)) return;

        items.forEach(item => {
          // 判断是否为叶子节点
          const hasChildren = Array.isArray(item.children) && item.children.length > 0;
          
          if (!hasChildren) {
            // 是叶子节点，收集 id
            leafIds.push(item.id);
          } else {
            // 有子节点，继续递归
            traverse(item.children);
          }
        });
      }

      traverse(nodes);
      return leafIds;
    },

    submitPeople(){
      let userArr = this.getLeafIds(this.chooseUser).map(item => item.replace('user-',""))
      let params = {
        id:this.checkId,
        userIds:userArr
      } 

      saveUser(params).then(res =>{
        if(res.data.code === 200){
          this.$message.success('人员设置成功')
          this.crewDialog = false
          this.onLoad()
        }
      })
    },
    // 打开前回调
    async beforeOpen(done, type, loading) {
      if(type == 'edit'){
        this.form.csId = this.form.csId + ''
        this.form.teamLeader = this.form.teamLeader + ''
        this.form.planner = this.form.planner + ''
        this.form.dispatcher = this.form.dispatcher + ''
        const res = await getAllUser({current:1,size:9999 })
        
        this.dispatcherData = res.data.data.records
        this.userData = res.data.data.records
        this.plannerData = res.data.data.records

        const dispatcherRes = await getAllUser({realName:this.form.dispatcherRealName})
        // 合并数据并根据 id 去重
        const mergedData = [...this.dispatcherData, ...dispatcherRes.data.data.records];
        const uniqueData = Array.from(
          new Map(mergedData.map(item => [item.id, item])).values()
        );
        this.dispatcherData = uniqueData

        const plannerRes = await getAllUser({realName:this.form.plannerRealName})
        // 合并数据并根据 id 去重
        const mergedPlannerData = [...this.plannerData, ...plannerRes.data.data.records];
        const uniquePlannerData = Array.from(
          new Map(mergedPlannerData.map(item => [item.id, item])).values()
        );
        this.plannerData = uniquePlannerData

        const teamRes = await getAllUser({realName:this.form.teamLeaderRealName})
        // 合并数据并根据 id 去重
        const mergedTeamData = [...this.userData, ...teamRes.data.data.records];
        const uniqueTeeanData = Array.from(
          new Map(mergedTeamData.map(item => [item.id, item])).values()
        );
        this.userData = uniqueTeeanData
        done()
      }else {
        done()
      }
      
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad() {
      this.loading = true;
      getList({
        current:this.page.currentPage,
        size:this.page.pageSize,
        ...this.query
      }).then(res =>{
        this.data = res.data.data.records
        this.page.total = res.data.data.total
        this.loading = false
      })
    },
  },
};
</script>

<style></style>

<style lang="scss">
.setCrewBox{
  .tree-transfer-vue3{
    height: 450px !important;

    .el-tree{
      height: 335px !important;
    }
  }
}
</style>
