<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="1060px"
    :visible="visible"
    :append-to-body="true"
    :close-on-click-modal="true"
    custom-class="ele-dialog-form"
    :title="`给工序【${this.data?.code}${this.data?.name}】配置工序`"
    @update:visible="updateVisible"
  >
    <div class="ele-body">
      <ele-pro-table
        ref="table"
        :needPage="false"
        :columns="columns"
        :datasource="datasource"
        row-key="code"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="showAddLog"
          >
            添加参数
          </el-button>
        </template>

        <!-- 状态列 -->

        <!-- 操作列 -->
        <template v-slot:action="{ row }">
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-edit"
            @click="openEdit(row)"
          >
            修改
          </el-link>
          <el-link
            :type="row.id ? 'primary' : 'info'"
            :underline="false"
            icon="el-icon-setting"
            @click="openSetting(row)"
          >
            配置工艺参数
          </el-link>
          <el-popconfirm
            class="ele-action"
            title="删除数据操作立即生效！！！确定要删除当前工序吗？"
            @confirm="remove(row)"
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false" icon="el-icon-delete">
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>
      </ele-pro-table>
    </div>

    <template v-slot:footer>
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save(false)">
        保存
      </el-button>
      <el-button type="primary" :loading="loading" @click="save(true)">
        保存并关闭
      </el-button>
    </template>
    <ele-modal
      width="1720px"
      :visible="addDialog"
      :append-to-body="true"
      :close-on-click-modal="true"
      @update:visible="closeAdd"
    >
      <Production :data="tableData" ref="ProductionCom" />
      <template v-slot:footer>
        <el-button @click="closeAdd">取消</el-button>
        <el-button type="primary" :loading="loading" @click="addParamrter">
          添加
        </el-button>
      </template>
    </ele-modal>
    <!-- 编辑弹窗 -->
    <user-edit
      :visible.sync="showEdit"
      :controlList="controlList"
      :data="current"
      @done="reload"
      ref="userEdit"
    />
    <!-- 配置工艺参数 -->
    <user-setting
      :visible.sync="showSetting"
      :data="current"
      ref="userSetting"
    />
  </ele-modal>
</template>

<script>
  import route from '@/api/technology/route';
  import Production from './production';
  import UserEdit from './production/components/user-edit.vue';
  import UserSetting from './production/components/user-setting.vue';
  import control from '@/api/technology/control';
  export default {
    components: { Production, UserEdit, UserSetting },
    props: {
      // 弹窗是否打开
      visible: Boolean,
      // 修改回显的数据
      data: Object
    },
    data() {
      return {
        timeType: [
          { value: 1, label: '是' },
          { value: 0, label: '否' }
        ],
        // 表格列配置
        columns: [
          {
            prop: 'code',
            label: '工序编码',
            // sortable: 'custom',
            showOverflowTooltip: true,
            align: 'center',

            minWidth: 110
          },
          {
            prop: 'name',
            label: '工序名称',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 110
          },
          {
            align: 'center',
            prop: 'controlName',
            label: '工序控制码',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'workCenterName',
            label: '所属工作中心',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },

          {
            columnKey: 'action',
            label: '操作',
            width: 260,
            align: 'center',
            resizable: false,
            slot: 'action',
            showOverflowTooltip: true
          }
        ],

        loading: false,
        addDialog: false,
        showSetting: false,
        showEdit: false,
        current: {},
        removeList: [],
        tableData: [],
        controlList:[]
      };
    },

    methods: {
      addParamrter() {
        // console.log(this.$refs.ProductionCom?.selection);
        let arr = this.$refs.ProductionCom.selection;

        let arrM = arr.map((item, index) => {
          return { ...item.detail };
        });
        arrM.forEach((element) => {
          if (element.id) {
            this.$set(element, 'sourceTaskId', element.id);
            delete element.id;
          }
        });

        this.$refs.table.setData([...arrM, ...this.$refs.table.getData()]);
        this.closeAdd();
      },
      showAddLog() {
        this.tableData = this.$refs.table.getData();
        this.addDialog = true;
        // this.$nextTick(() => {
        //   this.$refs.ProductionCom.reload();
        // });
      },
      /* 打开编辑弹窗 */
      openEdit(row) {
        this.getControlList()
        this.current = row;
        this.showEdit = true;
        this.$refs.userEdit.$refs.form &&
          this.$refs.userEdit.$refs.form.clearValidate();
      },
      
      getControlList(){
         const params = {
           pageNum: 1, size: -1
         }
         control.list().then(res=>{
            this.controlList = res.list
         })
      },
      /*配置工艺参数 */
      openSetting(row) {
        if (!row.id) {
          this.$message.warning('新增的数据需要保存之后才能配置工艺参数');
          return;
        }
        this.current = row;
        this.showSetting = true;
      },

      /*关闭选择参数*/
      closeAdd() {
        this.$refs.ProductionCom.$refs.table.setSelectedRows([]);
        this.addDialog = false;
      },
      /* 刷新表格 */
      reload() {
        this.$refs.table.reload();
      },
      remove(row) {
        if (row.id) {
          route.taskinstanceDelete([row.id]).then(() => {
            this.$message.success('删除成功');
            this.reload();
          });
        } else {
          const data = this.$refs.table.getData() ?? [];
          console.log(data);
          this.$refs.table.setData(data.filter((d) => d.code !== row.code));
        }
      },
      /* 表格数据源 */
      async datasource({ page, limit, where }) {
        if (this.data?.id) {
          console.log(22222);
          const res = await route.taskinstanceList({
            routingId: this.data.id,
            isDetail: true,
            pageNum: 1,
            size: -1
          });
          let arr = res.list.map((it) => it.detail);
          return {
            list: arr,
            count: res.count
          };
        }
      },
      /* 保存编辑 */
      save(isClose) {
        let arr = this.$refs.table.getData();
        if (arr.length == 0) {
          this.$message.warning('至少配置一条工序才能保存');
          return;
        }
        let arr1 = arr.map((it, i) => {
          if (it.orderNum) {
            delete it.orderNum;
          }
          return {
            ...it,
            orderNum: i + 1
          };
        });

        route
          .taskinstanceSave({
            routingId: this.data.id,
            taskInstanceList: arr1
          })
          .then((res) => {
            if (res) {
              this.$message.success('保存成功！');
              if (isClose) {
                this.updateVisible(false);
              } else {
                this.reload();
              }
            }
          });
        // arr.forEach((it) => {
        //   if (!it.taskId) {
        //     this.$set(it, 'taskId', this.data.id);
        //   }
        // });
        // producetask
        //   .paramSave({
        //     removeList: this.removeList,
        //     saveList: arr
        //   })
        //   .then(() => {
        //     this.$message.success('保存成功！');
        //     this.updateVisible(false);
        //   });

        // this.$refs.form.validate((valid) => {
        //   if (!valid) {
        //     return false;
        //   }
        //   if (!this.isUpdate) {
        //     delete this.form.id;
        //   }

        //   this.form.workBeat.beatTimes = this.totalTime;

        //   this.loading = true;
        //   producetask
        //     .save(this.form)
        //     .then((msg) => {
        //       this.form = {};
        //       this.loading = false;
        //       this.$message.success(msg);
        //       this.updateVisible(false);
        //       this.$emit('done');
        //     })
        //     .catch((e) => {
        //       this.loading = false;
        //       // this.$message.error(e.message);
        //     });
        // });
      },
      /* 更新visible */
      updateVisible(value) {
        this.removeList = [];
        this.$refs.table.setData([]);
        this.$emit('update:visible', value);
      }
    },

    watch: {
      visible(visible) {
        if (visible) {
          this.$nextTick(() => {
            this.reload();
          });
        }
      }
    }
  };
</script>
