<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model="form"
      v-model:page="page"
      ref="crud"
      @row-save="rowSave"
      @row-update="rowUpdate"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      :beforeOpen="beforeOpen"
    >
      <template #leaderUser-form="{ type, disabled }">
        <el-select v-if="type == 'add' || type == 'edit'" placeholder="请选择 主管工艺员"
        filterable
        remote
        :remote-method="getLeaderUser"
        v-model="form.leaderUser">
          <el-option
            v-for="item in leaderUsers"
            :key="item.id"
            :label="item.realName"
            :value="item.id">
          </el-option>
        </el-select>
      </template>
      <!-- <template #userName="{ row }">{{ row.leaderUser.userName }}</template>
      <template #jcName="{ row }">{{ row.bsJfCenter.jcName }}</template> -->
      <template #menu-left>
        <el-button type="danger" icon="el-icon-delete" @click="handleDelete"
          >删除</el-button
        >
      </template>
      <template #menu="{ row }">
        <el-button type="text" @click="setTeam(row)">设置班组</el-button>
        <el-button type="text" @click="setCapability(row)">设置工艺能力</el-button>
      </template>
    </avue-crud>
    <el-dialog title="设置班组" append-to-body v-model="teamDialog" width="700">
      <el-transfer
        style="width: 100%"
        v-model="teamValue"
        :data="teamData"
        :titles="['未选择', '已选择']"
        :props="{
          key: 'id',
          label: 'tsName',
        }"
      ></el-transfer>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="teamDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitTeam">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="设置工艺能力" append-to-body v-model="capacityDialog" 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="capacityList"
          @selection-change="selectionChangeProject"
          @select="selectChange"
        >
          <el-table-column type="selection" width="55px"></el-table-column>
          <el-table-column align="center" label="工艺能力" prop="id">
            <template #default="scope">
              <el-select v-model="scope.row.id">
                <el-option v-for="item in abilityList" :key="item.id" :label="item.caName" :value="item.id"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" label="面积" prop="area">
            <template #default="scope">
              <el-input-number v-model="scope.row.area" :min="0" controls-position="right"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column align="center" label="数量" prop="quality">
            <template #default="scope">
              <el-input-number v-model="scope.row.quality" :min="0" controls-position="right"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column align="center" label="批次" prop="batch">
            <template #default="scope">
              <el-input v-model="scope.row.batch"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="饱和度(%)" prop="saturation">
            <template #default="scope">
              <el-input-number v-model="scope.row.saturation" :min="0" controls-position="right"></el-input-number>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
            <span class="dialog-footer">
                <el-button @click="capacityDialog = false">取 消</el-button>
                <el-button type="primary" @click="submitCapacity">确 定</el-button>
            </span>
        </template>
    </el-dialog>
  </basic-container>
</template>
<script>
import {getList,getNotSelectTeam,getSelectTeam,getAbility,addWorkCenter,updateWorkCenter,saveTeam,
getSelectCraft,saveCraft,deleteWorkCenter,getAllUser} from "@/api/basicData/workCenter"
export default {
  data() {
    return {
      loading: false,
      data: [],
      form: {},
      query:{},
      capacityList: [],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      leaderUsers:[],
      abilityList:[],
      teamValue: [],
      capacityDialog: false,
      teamData: [],
      teamDialog: false,
      selectionList: [],
      option: {
        columnSort: true,
        tip: false,
        height: "auto",
        align: "center",
        // rowKey: "wcCode",
        calcHeight: 32,
        simplePage: false,
        searchShow: true,
        searchMenuSpan: 6,
        searchIcon: true,
        searchIndex: 3,
        tree: false,
        border: true,
        index: false,
        selection: true,
        viewBtn: false,
        delBtn: false,
        editBtn: true,
        editBtnText: "修改",
        editBtnIcon: " ",
        delBtnIcon: " ",
        addBtn: true,
        labelWidth: 120,
        searchLabelWidth: 100,
        menu: true,
        menuWidth: 240,
        dialogWidth: 800,
        dialogClickModal: false,
        searchEnter: true,
        excelBtn: true,
        gridBtn: false,
        searchShowBtn: false,
        showOverflowTooltip: true,
        searchLabelPosition: "left",
        searchLabelPosition: "left",
        searchGutter: 24,
        searchSpan: 6,
        menuAlign: "center",
        gridBtn: false,
        searchMenuPosition: "right",
        addBtnIcon: " ",
        viewBtnIcon: " ",
        delBtnIcon: " ",
        editBtnIcon: " ",
        column: [
          {
            label: "编码",
            prop: "wcCode",
            span: 24,
            overflow: true,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入编码",
                trigger: "blur",
              },
            ],
          },
          {
            label: "名称",
            prop: "wcName",
            span: 24,
            overflow: true,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入名称",
                trigger: "blur",
              },
            ],
          },
          {
            label: "工序",
            prop: "processes",
            span: 24,
            hide: true,
            addDisplay: false,
            editDisplay: false,
            overflow: true,
            search: false,
            rules: [
              {
                required: true,
                message: "请输入工序",
                trigger: "blur",
              },
            ],
          },
          {
            label: "工艺能力",
            prop: "craftAbility",
            span: 24,
            overflow: true,
            search: false,
            addDisplay: false,
            editDisplay: false,
            rules: [
              {
                required: true,
                message: "请输入工艺能力",
                trigger: "blur",
              },
            ],
          },
          {
            label: "业务标识",
            prop: "sign",
            span: 24,
            overflow: true,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入业务标识",
                trigger: "blur",
              },
            ],
          },
          {
            label: "主管工艺员",
            prop: "leaderUserName",
            type: "select",
            span: 24,
            overflow: true,
            search: true,
            addDisplay:false,
            editDisplay:false,
            rules: [
              {
                required: true,
                message: "请输入主管工艺员",
                trigger: "blur",
              },
            ],
            filterable:true,
            remote:true,
            dicUrl:"/api/blade-system/user/page?current=1&size=9999&realName={{key}}",
            props: {
              label: "realName",
              value: "id",
              res:"data.records"
            },
          },
          {
            label: "主管工艺员",
            prop: "leaderUser",
            type: "select",
            span: 24,
            overflow: true,
            search: true,
            hide:true,
            rules: [
              {
                required: true,
                message: "请输入主管工艺员",
                trigger: "blur",
              },
            ],
            filterable:true,
            remote:true,
            dicUrl:"/api/blade-system/user/page?current=1&size=300&realName={{key}}",
            props: {
              label: "realName",
              value: "id",
              res:"data.records"
            },
          },
          {
            label: "班组",
            prop: "team",
            span: 24,
            addDisplay: false,
            editDisplay: false,
            overflow: true,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入班组",
                trigger: "blur",
              },
            ],
          },
          {
            label: "交付中心",
            prop: "jcId",
            type: "select",
            span: 24,
            overflow: true,
            search: false,
            dicUrl:'/api/blade-system/dict/dictionary?code=workCenterJfCenter', //字典中取值
            props:{
              label:'dictValue',
              value:'dictKey',
            },
            rules: [
              {
                required: true,
                message: "请输入交付中心",
                trigger: "blur",
              },
            ],
          },
          {
            label: "描述",
            prop: "describe",
            type: "textarea",
            span: 24,
            hide: true,
            overflow: true,
            search: false,
            // rules: [
            //     {
            //         required: true,
            //         message: '请输入交付中心',
            //         trigger: 'blur',
            //     },
            // ],
          },
          {
            label: "",
            prop: "checkout",
            type: "checkbox",
            dicData: [{ label: "检验标记", value: 1 }],
            span: 8,
            hide: true,
            overflow: true,
            search: false,
            // rules: [
            //     {
            //         required: true,
            //         message: '请输入交付中心',
            //         trigger: 'blur',
            //     },
            // ],
          },
          {
            label: "",
            prop: "whetherPlate",
            type: "checkbox",
            dicData: [{ label: "镀后标记", value: 1 }],
            span: 8,
            hide: true,
            overflow: true,
            search: false,
            // rules: [
            //     {
            //         required: true,
            //         message: '请输入交付中心',
            //         trigger: 'blur',
            //     },
            // ],
          },
          {
            label: "",
            prop: "bigBatch",
            type: "checkbox",
            dicData: [{ label: "是否大批量", value: 1 }],
            span: 8,
            hide: true,
            overflow: true,
            search: false,
            // rules: [
            //     {
            //         required: true,
            //         message: '请输入交付中心',
            //         trigger: 'blur',
            //     },
            // ],
          },
        ],
      },
      checkId:''
    };
  },
  mounted() {
    this.getAbilityData()
  },
  methods: {
    getLeaderUser(query){
      console.log('query------------',query)
      console.log('leaderUsers------------',this.leaderUsers.length)
      if(query == ''){
        console.log('111111111111111111111')
        if(this.leaderUsers.length == 0){
          getAllUser({
            current:1,size:300
          }).then(res =>{
            this.leaderUsers = res.data.data.records
          })
        }
        
      }else{
        getAllUser({
          current:1,size:300,
          realName:query
        }).then(res =>{
          this.leaderUsers = res.data.data.records
        })
      }
    },
    searchChange(params, done){
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad()
      done()
    },
    searchReset(){
      this.query = {}
      this.onLoad()
    },
    currentChange(currentPage){
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize){
      this.page.pageSize = pageSize;
    },
    beforeOpen(done, type){
      if(type == 'edit'){
        console.log('form',this.form)
        this.form.jcId = this.form.jcId + ''
        this.form.leaderUser = this.form.leaderUser + ''
        this.form.checkout = this.form.checkout == 1 ? [1] : []
        this.form.bigBatch = this.form.bigBatch == 1 ? [1] : []
        this.form.whetherPlate = this.form.whetherPlate == 1 ? [1] : []
        // this.getLeaderUser(this.form.leaderUserName)
        getAllUser({current:1,size:300}).then(res => {
          this.leaderUsers = res.data.data.records
          let tmp = this.leaderUsers.find(item => item.id == this.form.leaderUser)
          if(!tmp){
            getAllUser({
              realName:this.form.leaderUserName
            }).then(res =>{
              this.leaderUsers = [...this.leaderUsers, ...res.data.data.records]
              done()
            })
          }else{
            done()
          }
        })
      }else{
        done()
      }
    },
    rowSave(row, done, loading){
      let params = {
        ...row,
        checkout:row.checkout.length != 0 ? 1 : 0,
        bigBatch:row.bigBatch.length != 0 ? 1 : 0,
        whetherPlate:row.whetherPlate.length != 0 ? 1 : 0,
      }

      addWorkCenter(params).then(res =>{
        if(res.data.code === 200){
          this.$message.success('新增成功');
          this.onLoad()
          done()
        }
      })
    },
    rowUpdate(row, index, done, loading){
      let params = {
        ...row,
        checkout:row.checkout.length != 0 ? 1 : 0,
        bigBatch:row.bigBatch.length != 0 ? 1 : 0,
        whetherPlate:row.whetherPlate.length != 0 ? 1 : 0,
      }
      updateWorkCenter(params).then(res =>{
        if(res.data.code === 200){
          this.$message.success('修改成功');
          this.onLoad()
          done()
        }
      })
    },
    // 设置班组
    async setTeam(row) {
      this.checkId = row.id
      // this.teamValue = row.teamValue && row.teamValue != "" ? row.teamValue.split(",") : [];
      // console.log("teamValue=================", this.teamValue);
      const selectTeam = await getSelectTeam({id: row.id,});
      const noSelectTeam = await getNotSelectTeam({id: row.id,});
      console.log('selectTeam-----------',selectTeam)
      console.log('noSelectTeam-----------',noSelectTeam)
      this.teamData = [...noSelectTeam.data.data,...selectTeam.data.data]
      this.teamValue = selectTeam.data.data.map(item => item.id)
      console.log('teamValue-----------',this.teamValue)
      this.teamDialog = true;
    },
    submitTeam(){
      console.log('this.teamValue-----------',this.teamValue)
      let params = {
        id:this.checkId,
        teamIds:this.teamValue
      }

      saveTeam(params).then(res =>{
        if(res.data.code === 200){
          this.$message.success('班组设置成功');
          this.teamDialog = false
          this.onLoad()
        }
      })
    },
    submitCapacity(){
      if(this.capacityList.length == 0){
        this.$message.error('请至少填写一条数据')
        return
      }
      // console.log('this.capacityList-----------',this.capacityList)
      // 校验通过：准备提交数据（过滤无用字段）
        const submitData = this.capacityList.map(row => {
          const { _select, ...validData } = row; // 剔除选择状态字段
          return validData;
        });
      let params = {
        id:this.checkId,
        crafs:submitData
      }
      console.log('params-----------',params)
      saveCraft(params).then(res =>{
        if(res.data.code === 200){
          this.$message.success('工艺能力设置成功');
          this.capacityDialog = false
          this.onLoad()
        }
      })
    },
    getAbilityData(){
      getAbility().then(res =>{
        this.abilityList = res.data.data
      })
    },
    // 设置工艺能力
    setCapability(row){
      this.checkId = row.id
      getSelectCraft({id:row.id}).then(res =>{
        this.capacityList = res.data.data
        this.capacityDialog = true
      })
    },
    // 工艺能力插入一行
    insertEvent() {
      const record = { _select: false };
      this.capacityList.push(record);
    },
    selectChange(list, row) {
      row._select = !row._select;
    },
    remove() {
      let arr = this.capacityList.filter((item) => item._select);
      if (arr.length != 0) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          if (this.rowId) {
            let deleteData = this.capacityList.filter((item) => item._select);
            this.deleteTidArr = deleteData.filter((item) => item.tidId);
          }
          let deleteArr = this.capacityList.filter((item) => !item._select);
          this.capacityList = deleteArr;
        });
      } else {
        this.$message.error("请至少选择一条数据进行操作！");
      }
    },
    handleSave() {
      //   if(this.capacityList.length == 0){
      //     this.$message.error('请至少填写一条数据')
      //   }else{
      //     // let tmp = this.capacityList.find(item => !item.oneData || !item.twoData)
      //     // if(tmp){
      //     //     this.$message.error('数据请填写完整!')
      //     // }
      //   }
      this.capacityDialog = false;
    },
    selectionChange(val) {
      this.selectionList = val;
    },
    handleDelete() {
      if (this.selectionList.length == 0) {
        this.$message.error("请至少选择一条数据");
      } else {
        this.$confirm("确定删除选中数据?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          deleteWorkCenter({
            ids: this.selectionList.map(item => item.id).join(","),
          }).then(res =>{
            if(res.data.code === 200){
              this.$message.success('删除成功');
              this.onLoad()
            }
          })
        });
      }
    },
    onLoad() {
      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.data = [
      //   {
      //     area: 0.0,
      //     batchNo: null,
      //     bigBatch: false,
      //     bsJfCenter: {
      //       createMan: null,
      //       createTime: null,
      //       deleted: false,
      //       jcCode: "SJZX",
      //       jcId: 2,
      //       jcName: "烧结中心",
      //       keyValue: 2,
      //       updateTime: null,
      //     },
      //     checkout: false,
      //     craftAbility: null,
      //     createMan: {
      //       userId: 1,
      //       userName: "admin",
      //     },
      //     deleted: false,
      //     describe: null,
      //     endPoint: null,
      //     keyValue: 222,
      //     leaderUser: {
      //       userId: 280,
      //       userName: "01152",
      //     },
      //     limitType: 0,
      //     processes: " ",
      //     quantity: 0,
      //     roundCycle: null,
      //     saturation: 0.0,
      //     sign: "test",
      //     startPoint: null,
      //     teamValue: "",
      //     team: " ",
      //     wcCode: "11",
      //     wcId: 222,
      //     wcName: "测试中心",
      //     whetherPlate: false,
      //   },
      //   {
      //     area: 0.0,
      //     batchNo: null,
      //     bigBatch: false,
      //     bsJfCenter: {
      //       createMan: null,
      //       createTime: null,
      //       deleted: false,
      //       jcCode: "WXZX",
      //       jcId: 3,
      //       jcName: "外协中心",
      //       keyValue: 3,
      //       updateTime: null,
      //     },
      //     checkout: false,
      //     craftAbility: "玻璃烧结电镀、玻璃烧结、烧结后检验",
      //     createMan: {
      //       userId: 541,
      //       userName: "崔殿龙",
      //     },
      //     deleted: false,
      //     describe: null,
      //     endPoint: null,
      //     keyValue: 202,
      //     leaderUser: {
      //       userId: 541,
      //       userName: "崔殿龙",
      //     },
      //     limitType: 0,
      //     processes: " ",
      //     quantity: 0,
      //     roundCycle: null,
      //     saturation: 0.0,
      //     sign: "1",
      //     startPoint: null,
      //     team: "玻璃烧结班组",
      //     teamValue: "182",
      //     wcCode: "010",
      //     wcId: 202,
      //     wcName: "玻璃烧结作业中心",
      //     whetherPlate: false,
      //   },
      //   {
      //     area: 0.0,
      //     batchNo: null,
      //     bigBatch: false,
      //     bsJfCenter: {
      //       createMan: null,
      //       createTime: null,
      //       deleted: false,
      //       jcCode: "SJZX",
      //       jcId: 2,
      //       jcName: "烧结中心",
      //       keyValue: 2,
      //       updateTime: null,
      //     },
      //     checkout: false,
      //     craftAbility: "滚镀金或振镀金、超声波清洗",
      //     createMan: {
      //       userId: 90,
      //       userName: "03891",
      //     },
      //     deleted: false,
      //     describe: null,
      //     endPoint: null,
      //     keyValue: 162,
      //     leaderUser: {
      //       userId: 541,
      //       userName: "崔殿龙",
      //     },
      //     limitType: 0,
      //     processes: " ",
      //     quantity: 0,
      //     roundCycle: null,
      //     saturation: 0.0,
      //     sign: "4",
      //     startPoint: null,
      //     team: "镀金二班白龙喜、镀金二班杜宁",
      //     teamValue: "124,125",
      //     wcCode: "009",
      //     wcId: 162,
      //     wcName: "镀金小批量作业中心",
      //     whetherPlate: false,
      //   },
      //   {
      //     area: 0.0,
      //     batchNo: null,
      //     bigBatch: true,
      //     bsJfCenter: {
      //       createMan: {
      //         userId: 1,
      //         userName: "admin",
      //       },
      //       createTime: "2024-12-09 00:00:00",
      //       deleted: false,
      //       jcCode: "RBZX",
      //       jcId: 1,
      //       jcName: "热表中心",
      //       keyValue: 1,
      //       updateTime: "2024-12-09 00:00:00",
      //     },
      //     checkout: false,
      //     craftAbility: "滚镀金或振镀金",
      //     createMan: {
      //       userId: 90,
      //       userName: "03891",
      //     },
      //     deleted: false,
      //     describe: null,
      //     endPoint: null,
      //     keyValue: 122,
      //     leaderUser: {
      //       userId: 541,
      //       userName: "崔殿龙",
      //     },
      //     limitType: 0,
      //     processes: " ",
      //     quantity: 0,
      //     roundCycle: null,
      //     saturation: 0.0,
      //     sign: "4",
      //     startPoint: null,
      //     team: "镀金一班郭千千、镀金一班张二帅",
      //     teamValue: "102,103",
      //     wcCode: "008",
      //     wcId: 122,
      //     wcName: "镀金大批量作业中心",
      //     whetherPlate: false,
      //   },
      // ];
      // this.page.total = this.data.length;
    },
  },
};
</script>
