<template>
  <ele-modal
    width="65vw"
    :visible.sync="visible"
    v-if="visible"
    :close-on-click-modal="false"
    row-key="code"
    custom-class="ele-dialog-form"
    title="生产前准备"
    :before-close="onClose"
    append-to-body
    :maxable="true"
  >
    <ele-pro-table
      ref="table"
      :columns="columns"
      :datasource="
        type == 'plan'
          ? preReleaseList.filter((item) => item.preType != 6)
          : preReleaseList
      "
      :needPage="false"
      :selection.sync="selection"
      row-key="id"
      @columns-change="handleColumnChange"
      :cacheKey="cacheKeyUrl"
      :page-size="20"
    >
      <template v-slot:toolbar>
        <el-button
          v-if="type != 'order' && type != 'plan'"
          type="primary"
          size="mini"
          @click="batchKittingComplete"
          >批量齐套检查</el-button
        >
      </template>

      <template v-slot:preType="{ row }">
        <span>{{ getTypeLabel(row.preType) }}</span>
      </template>

      <template v-slot:statusStr="{ row }">
        <span v-if="row.statusStr == '缺料'" style="color: red">{{
          row.statusStr
        }}</span>
        <span v-else style="color: green">{{ row.statusStr }}</span>
      </template>

      <template v-slot:action="{ row }">
        <el-link
          type="primary"
          :underline="false"
          @click="kittingComplete(row)"
        >
          <!-- v-if="type == 'plan' || row.preType == '6'" -->
          齐套检查
        </el-link>

        <!-- <el-link
          type="primary"
          :underline="false"
          @click="taskAssignment"
          v-if="row.statusStr == '缺料' && type == 'plan' && row.preType == '5'"
        >
          任务派单
        </el-link> -->
      </template>
    </ele-pro-table>

    <el-dialog
      title="任务派单"
      v-if="dialogVisible"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      append-to-body
    >
      <el-form ref="form" :model="form" label-width="100px" :rules="rules">
        <el-form-item label="分管部门：">
          <ele-tree-select
            clearable
            :data="groupList"
            filterable
            v-model="form.executeGroupId"
            valueKey="id"
            labelKey="name"
            placeholder="请选择"
            @change="change_principalDep"
            default-expand-all
          />
        </el-form-item>

        <el-form-item label="技术员：" prop="executorId">
          <el-select
            v-model="form.executorId"
            placeholder="请选择"
            style="width: 100%"
            @change="leaderListChange"
            filterable
          >
            <el-option
              v-for="item in leaderList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="工序">
          <el-input disabled placeholder="请输入内容" v-model="form.taskName">
          </el-input>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入内容"
            v-model="form.remark"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="batchConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <ele-modal
      width="65vw"
      :visible.sync="routeVisible"
      v-if="routeVisible"
      append-to-body
      :maxable="true"
      :title="fileTitle"
    >
      <ele-pro-table
        ref="ncFileTable"
        :columns="jobColumns2"
        :datasource="bomDataList"
        :need-page="false"
        :immediate="true"
        @refresh="refresh"
      >
        <template v-slot:code="{ row }">
          <el-link type="primary" :underline="false" @click="goDetail(row)">
            {{ row.code }}
          </el-link>
        </template>
        <template v-slot:action="{ row, $index }">
          <!-- <el-link
            type="primary"
            @click="fileDetails(row, fileTitle == 'NC代码' ? 'nc' : '')"
            >详情</el-link
          > -->

          <!-- <el-link
          type="primary"
          :underline="false"
          @click="taskAssignment"
          v-if="row.statusStr == '缺料' && type == 'plan' && row.preType == '5'"
        >
          任务派单
        </el-link> -->

          <el-link
            type="primary"
            @click="taskAssignment(row)"
            :underline="false"
            v-if="row.preType == 5 && row.ncCodeList.length == 0"
            >任务派单</el-link
          >
        </template>

        <template v-slot:versions="{ row, $index }">
          <span v-if="row.versions">V{{ row.versions }}.0</span>
        </template>
        <template v-slot:statusStr="{ row }">
          <span
            v-if="row.preType == 4 && row.fileParam.length == 0"
            style="color: red"
          >
            缺料
          </span>
          <span
            v-else-if="row.preType == 5 && row.ncCodeList.length == 0"
            style="color: red"
          >
            缺料
          </span>
          <span v-else style="color: green">齐套</span>
        </template>
      </ele-pro-table>
      <template v-slot:footer v-if="fileTitle == 'NC代码'">
        <el-button size="small" @click="routeVisible = false">返回</el-button>
        <el-button type="primary" size="small" @click="save('齐套')"
          >齐套</el-button
        >
        <el-button type="primary" size="small" @click="save('缺料')"
          >不齐套</el-button
        >
      </template>
    </ele-modal>

    <ele-modal
      width="65vw"
      :visible.sync="fileVisible"
      v-if="fileVisible"
      append-to-body
      :maxable="true"
      :title="fileTitle"
    >
      <ele-pro-table
        ref="ncFileTable"
        :columns="jobColumns1"
        :datasource="fileList"
        :need-page="false"
        :immediate="true"
      >
        <template v-slot:code="{ row }">
          <el-link type="primary" :underline="false" @click="fileDetails(row)">
            {{ row.code }}
          </el-link>
        </template>
      </ele-pro-table>
    </ele-modal>

    <kitting-complete ref="kittingCompleteRef"></kitting-complete>
    <auxiliary-material
      ref="auxiliaryMaterialRef"
      @success="updateStatus"
    ></auxiliary-material>
  </ele-modal>
</template>

<script>
  import {
    completenessCheck,
    taskReleaseWork,
    updatePreRelease,
    updatePreReleaseOrder,
    listBomTaskFile,
    newFilePageAPI,
    listBomRoutingFile
  } from '@/api/productionPlan';
  import { listOrganizations, getUserPage } from '@/api/system/organization';
  import kittingComplete from './kittingComplete.vue';
  import auxiliaryMaterial from './auxiliaryMaterial.vue';
  import { setFileUrl } from '@/components/addDoc/util.js';

  export default {
    components: { kittingComplete, auxiliaryMaterial },
    props: {
      type: {
        type: String,
        default: ''
      }
    },
    data() {
      // 1主材料 2辅材料 3工装 4工艺文件 5NC代码 6人员
      return {
        visible: false,
        cacheKeyUrl: 'checkProductionPreparationsKey',
        selection: [],
        planId: '',
        preReleaseList: [],
        fileTitle: '',
        fileVisible: false,
        typeList: [
          {
            value: 1,
            label: '主材料齐套'
          },
          {
            value: 2,
            label: '辅材料齐套'
          },
          {
            value: 3,
            label: '工装齐套'
          },
          {
            value: 4,
            label: '工艺文件齐套'
          },
          {
            value: 5,
            label: 'NC代码齐套'
          },
          {
            value: 6,
            label: '人员齐套'
          }
        ],
        // 表格选中数据
        jobColumns1: [
          {
            label: '编码',
            prop: 'code',
            slot: 'code',
            width: 180,
            align: 'center',
            showOverflowTooltip: true
          },

          {
            prop: 'version',
            label: '文件名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 200
          },
          {
            prop: 'name',
            label: '版本',
            align: 'center',
            slot: 'name',
            showOverflowTooltip: true,
            minWidth: 200
          },

          {
            prop: 'createTime',
            label: '创建时间',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 110
          }
        ],
        // 表格选中数据
        jobColumns2: [
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            label: '编码',
            prop: 'code',
            slot: 'code',
            width: 180,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'name',
            label: '工序名称',
            align: 'center',
            slot: 'name',
            showOverflowTooltip: true,
            minWidth: 200
          },
          {
            prop: 'versions',
            slot: 'versions',
            label: '版本',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100
          },
          {
            prop: 'workCenterName',
            label: '工作中心',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100
          },

          {
            prop: 'statusStr',
            slot: 'statusStr',
            align: 'center',
            label: '状态'
          },

          {
            columnKey: 'action',
            label: '操作',
            width: 100,
            align: 'center',
            resizable: false,
            slot: 'action',
            showOverflowTooltip: true
          }
        ],
        groupList: [],
        leaderList: [],
        form: {
          executeGroupName: '',
          executeGroupId: '',
          executorName: '',
          executorId: '',
          remark: '',
          taskId: '',
          taskName: '',
          sourceTaskId: ''
        },
        dialogVisible: false,
        rules: {
          executorId: [
            { required: true, message: '请选择技术人员', trigger: 'blur' }
          ]
        },
        itemData: {},
        bomDataList: [],
        productionData: {},
        routeVisible: false,
        fileList: []
      };
    },

    created() {
      this.getGs();
    },

    computed: {
      columns() {
        return [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center',
            fixed: 'left',
            reserveSelection: true
          },
          {
            width: 55,
            type: 'index',
            columnKey: 'index',
            align: 'center',
            label: '序号',
            fixed: 'left'
          },
          {
            prop: 'preType',
            slot: 'preType',
            align: 'center',
            label: '名称'
          },
          {
            prop: 'statusStr',
            slot: 'statusStr',
            align: 'center',
            label: '状态'
          },
          // {
          //   prop: 'approveDate',
          //   align: 'center',
          //   label: '校验时间'
          // },
          // {
          //   prop: 'approveName',
          //   align: 'center',
          //   label: '校验人',
          //   showOverflowTooltip: true
          // },
          {
            columnKey: 'action',
            label: '操作',
            align: 'center',
            resizable: false,
            slot: 'action',
            fixed: 'right',
            showOverflowTooltip: true
          }
        ];
      }
    },

    methods: {
      async completenessCheck(planId, apsWorkOrderId) {
        const params = {
          planId
        };
        if (apsWorkOrderId) {
          params.apsWorkOrderId = apsWorkOrderId;
        }
        this.preReleaseList = await completenessCheck(params);
      },

      // reload(where) {
      //   this.$nextTick(() => {
      //     if (this.$refs.table && this.$refs.table.reload)
      //       this.$refs.table.reload({ page: 1, where: where });
      //   });
      // },

      async getGs() {
        await listOrganizations().then((list) => {
          this.groupList = this.$util.toTreeData({
            data: list,
            idField: 'id',
            parentIdField: 'parentId'
          });
        });
      },
      fileDetails(row) {
        // if (row.preType == '5') {
        //   newFilePageAPI({
        //     ids: "'" + row.fileId + "'"
        //   }).then((res) => {
        //     if (res.length) {
        //       window.open(setFileUrl(res[0]));
        //     }
        //   });
        // } else {
        window.open(setFileUrl(row));
        // }
      },
      getTypeLabel(value) {
        const item = this.typeList.find((it) => it.value === value);
        return item ? item.label : '';
      },

      open(item) {
        this.visible = true;
        this.itemData = item;
        this.preReleaseList = [];
        // if (item.preRelease.length) {
        //   this.preReleaseList = item.preRelease;
        // } else {
          if (item.id && this.type == 'plan') {
            this.completenessCheck(item.id);
          } else if (this.type == 'order') {
            this.completenessCheck(item.productionPlanId, item.id);
          // }
        }
      },

      handleColumnChange() {},

      onClose() {
        this.visible = false;
        this.$emit('update');
      },

      handleClose() {
        this.dialogVisible = false;
      },
      save(statusStr) {
        let data = this.preReleaseList.find((item) => item.preType == 5);
        console.log(data);
        data.statusStr = statusStr;
        this.updatePreRelease(data);
        this.routeVisible = false;
      },
      updatePreRelease(item) {
        if (this.type == 'plan') {
          updatePreRelease(item);
        } else if (this.type == 'order') {
          item.apsWorkOrderId = this.itemData.id;
          updatePreReleaseOrder(item);
        }
        this.$emit('update');
      },
      async kittingComplete(item) {
        if (item.preType == '6') {
          this.$confirm('是否确认齐套?', '提示', {
            confirmButtonText: '齐套',
            cancelButtonText: '不齐套',
            type: 'warning',
            distinguishCancelAndClose: true
          })
            .then(() => {
              item.statusStr = '齐套';
              this.updatePreRelease(item);
            })
            .catch((action) => {
              if (action == 'cancel') {
                item.statusStr = '缺料';
                this.updatePreRelease(item);
              }
            });
        } else if (item.preType == '5') {
          const res = await listBomTaskFile(
            this.itemData.bomCategoryId,
            this.itemData.produceRoutingId
          );
          let fileParam = [];
          let ncCodeList = [];
          res.forEach((row) => {
            fileParam.push(row.fileParam.map((item) => item.id));
            ncCodeList.push(row.ncCodeList);
            row.preType = item.preType;
          });
          this.bomDataList = res;

          this.fileTitle = 'NC代码';

          this.routeVisible = true;
        } else if (item.preType == '4') {
          const res = await listBomRoutingFile(
            this.itemData.bomCategoryId,
            this.itemData.produceRoutingId
          );

          if (res.fileParam.length != 0) {
            let fileParam = res.fileParam.map((item) => item.id).join(',');
            this.fileList = await newFilePageAPI({
              ids: "'" + fileParam + "'"
            });
          } else {
            this.fileList = [];
          }

          this.fileTitle = '工艺文件';

          this.fileVisible = true;
        } else if (item.preType == '1') {
          this.itemData.productionPlanId =
            this.itemData.productionPlanId || this.itemData.id;
          const list = [this.itemData];
          this.$refs.kittingCompleteRef.open(list);
        } else if (item.preType == '2') {
          const data = this.preReleaseList.find((it) => it.preType == 2);
          this.$refs.auxiliaryMaterialRef.open(this.itemData, data);
        }
      },

      async refresh() {
        const res = await listBomTaskFile(
          this.itemData.bomCategoryId,
          this.itemData.produceRoutingId
        );
        let fileParam = [];
        let ncCodeList = [];
        res.forEach((row) => {
          fileParam.push(row.fileParam.map((item) => item.id));
          ncCodeList.push(row.ncCodeList);
          row.preType = this.productionData.preType;
        });
        this.bomDataList = res;
        if (this.productionData.preType == '4') {
          this.fileTitle = '工艺文件';
        } else {
          this.fileTitle = 'NC代码';
        }
      },

      async goDetail(item) {
        if (item.preType == '4') {
          if (item.fileParam.length != 0) {
            let fileParam = item.fileParam.map((item) => item.id).join(',');
            this.fileList = await newFilePageAPI({
              ids: "'" + fileParam + "'"
            });
          } else {
            this.fileList = [];
          }

          this.fileTitle = '工艺文件';
        } else {
          if (item.ncCodeList.length != 0) {
            let ncCodeList = item.ncCodeList
              .map((item) => item.fileId)
              .join(',');
            this.fileList = await newFilePageAPI({
              ids: "'" + ncCodeList + "'"
            });
          } else {
            this.fileList = [];
          }
          this.fileTitle = 'NC代码';
        }

        this.fileVisible = true;
      },

      taskAssignment(row) {
        this.form.taskId = row.id;
        this.form.taskName = row.name;
        this.form.sourceTaskId = row.sourceTaskId;
        this.dialogVisible = true;
      },

      change_principalDep(id) {
        const node = this.findNodeById(this.groupList, id);
        this.form.executeGroupName = node ? node.name : '';
        this.form.executorId = '';
        this.form.executorName = '';

        this.getUserPage();
      },

      leaderListChange(id) {
        const item = this.leaderList.find((it) => it.id === id);
        this.form.executorName = item.name;
      },

      findNodeById(list, id) {
        for (const item of list) {
          if (item.id === id) return item;
          if (item.children) {
            const found = this.findNodeById(item.children, id);
            if (found) return found;
          }
        }
        return null;
      },

      async getUserPage() {
        if (!this.form.executeGroupId) return (this.leaderList = []);
        let par = {
          groupId: this.form.executeGroupId,
          size: 999
        };
        await getUserPage(par).then((res) => {
          this.leaderList = res.list;
        });
      },

      updateStatus() {
        const index = this.preReleaseList.findIndex((it) => it.preType == 2);

        this.$set(this.preReleaseList[index], 'statusStr', '齐套');
      },

      async batchConfirm() {
        const valid = await this.$refs.form.validate().catch(() => false);
        if (!valid) return;

        const loading = this.$loading({
          lock: true,
          text: '派单中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        await taskReleaseWork({
          ...this.form,
          productionPlanId: this.itemData.productionPlanId || this.itemData.id,
          eventType: 1
        })
          .then(() => {
            loading.close();
            this.$message.success('派单成功');
            this.form = {
              executeGroupName: '',
              executeGroupId: '',
              executorName: '',
              executorId: '',
              remake: ''
            };
            this.dialogVisible = false;
            // this.reload();
          })
          .catch(() => {
            loading.close();
          });
      },
      batchKittingComplete() {}
    }
  };
</script>

<style></style>
