<template>
  <ele-modal
    :visible.sync="visible"
    v-if="visible"
    :title="title"
    width="75vw"
    append-to-body
    @close="cancel"
    :maxable="true"
  >
    <!-- <div class="switch" v-if="type == 'detail'">
      <div class="switch_left">
        <ul>
          <li
            v-for="item in tabOptions"
            :key="item.key"
            :class="{ active: activeComp == item.key }"
            @click="activeComp = item.key"
          >
            {{ item.name }}
          </li>
        </ul>
      </div>
    </div> -->
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="create-form"
    >
      <headerTitle title="基本信息" style="margin-top: 15px"></headerTitle>

      <el-row :gutter="15">
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="类型:" prop="type">
            <DictSelection
              dictName="请托类型"
              v-model="form.type"
              :disabled="type == 'detail'"
            ></DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="紧急程度:" prop="priority">
            <el-select
              style="width: 100%"
              v-model="form.priority"
              placeholder="请选择"
              clearable
              :disabled="type == 'detail'"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col v-bind="styleResponsive ? { lg: 6, md: 24 } : { span: 6 }">
          <el-form-item label="名称:" prop="name">
            <el-input v-model="form.name" :disabled="type == 'detail'" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="请托部门:" prop="pleaseEntrustDeptName">
            <el-input v-model="form.pleaseEntrustDeptName" clearable disabled>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="请托人:" prop="pleaseEntrustUserId">
            <el-input v-model="form.pleaseEntrustUserName" clearable disabled />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 6, md: 8 } : { span: 6 }">
          <el-form-item label="所属工厂:" prop="factoriesName">
            <el-input v-model="form.factoriesName" style="width: 100%" disabled>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="受托工厂:" prop="beEntrustedFactoriesId">
            <el-select
              style="width: 100%"
              v-model="form.beEntrustedFactoriesId"
              placeholder="请选择"
              clearable
              :disabled="type == 'detail'"
            >
              <el-option
                v-for="item in factoryList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                @click.native="factoryListChange(item)"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="受托部门:" prop="beEntrustedDeptId">
            <deptSelect
              :disabled="type == 'detail'"
              v-model="form.beEntrustedDeptId"
              @changeGroup="beEntrustedDeptIdChange"
            />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="是否尾工序:" prop="isLast">
            <el-radio-group v-model="form.isLast" :disabled="type == 'detail'">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <!-- <el-col :span="6">
          <el-form-item label="完成时间:" prop="finishTime">
            <el-date-picker
              style="width: 100%"
              v-model="form.finishTime"
              type="date"
              value-format="yyyy-MM-dd"
              :disabled="type == 'detail'"
            ></el-date-picker>
          </el-form-item>
        </el-col>

        <el-col v-bind="styleResponsive ? { lg: 24, md: 24 } : { span: 24 }">
          <el-form-item label="需求描述:">
            <el-input
              v-model="form.describes"
              type="textarea"
              :rows="2"
              :disabled="type == 'detail'"
            />
          </el-form-item>
        </el-col> -->
      </el-row>
      <headerTitle title="产品信息" style="margin-top: 15px"></headerTitle>

      <el-button
        size="small"
        type="primary"
        icon="el-icon-plus"
        class="ele-btn-icon"
        @click="addOder"
        v-if="type != 'detail' && type != 'edit'"
        style="margin-bottom: 10px"
      >
        新建
      </el-button>

      <el-button
        size="small"
        type="danger"
        icon="el-icon-delete"
        class="ele-btn-icon"
        @click="removeOder"
        v-if="type != 'detail' && type != 'edit'"
        plain
        style="margin-bottom: 10px"
      >
        删除
      </el-button>

      <ele-pro-table
        ref="entrustCreateTable"
        :columns="columns"
        :datasource="orderList"
        :selection.sync="selection"
        :current.sync="current"
        highlight-current-row
        row-key="id"
        height="40vh"
      >
        <template v-slot:totalCountHead="{ column }">
          <div>
            <span class="is-required">{{ column.label }}</span>
          </div>
        </template>

        <template v-slot:taskIdHead="{ column }">
          <div>
            <span class="is-required">{{ column.label }}</span>
          </div>
        </template>

        <template v-slot:planDeliveryTimeHead="{ column }">
          <div>
            <span class="is-required">{{ column.label }}</span>
          </div>
        </template>

        <template v-slot:totalCount="{ row }">
          <el-input v-model="row.totalCount" :disabled="type == 'detail'">
            <template slot="append">{{ row.measuringUnit }}</template>
          </el-input>
        </template>

        <template v-slot:describes="{ row }">
          <el-input v-model="row.describes" :disabled="type == 'detail'">
          </el-input>
        </template>

        <template v-slot:taskId="{ row, $index }">
          <el-select
            clearable
            filterable
            style="width: 100%"
            v-model="row.taskId"
            placeholder="请选择"
            @change="taskListChange(row, $index)"
            :disabled="type == 'detail'"
          >
            <el-option
              v-for="item in row.taskList"
              :label="item.name"
              :value="item.id"
              :key="item.id"
            >
            </el-option>
          </el-select>
        </template>

        <template v-slot:planDeliveryTime="{ row }">
          <el-date-picker
            v-model="row.planDeliveryTime"
            type="datetime"
            placeholder="选择日期时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :disabled="type == 'detail'"
          >
          </el-date-picker>
        </template>
      </ele-pro-table>
    </el-form>

    <template v-slot:footer v-if="type != 'detail'">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="save(1)"> 保存 </el-button>
      <el-button type="primary" @click="save(2)"> 提交 </el-button>
    </template>
    <!-- <detail
      v-if="activeComp === 'bpm' && form.processInstanceId"
      :id="form.processInstanceId"
    ></detail> -->

    <produceOrder ref="produceOrderRef" @choose="choose" />
  </ele-modal>
</template>

<script>
  import {
    save,
    addSubmit,
    pleaseEntrustDetail,
    update
  } from '@/api/entrust/index';
  import produceOrder from './produceOrder';
  import detail from '@/views/bpm/processInstance/detail.vue';
  import deptSelect from '@/components/CommomSelect/dept-select.vue';
  import { getProduceTaskList } from '@/api/aps';
  import warehouseDefinition from '@/api/warehouseManagement/warehouseDefinition';

  const defaultForm = function () {
    return {
      createTime: '', //创建时间
      code: '', //编码
      name: '', //名称
      workOrderCode: '', //工单编码
      pleaseEntrustUserId: '', //请托人id
      pleaseEntrustUserName: '', //请托人名称
      pleaseEntrustDeptId: '', //请托人部门id
      pleaseEntrustDeptName: '', //请托人部门名称
      beEntrustedDeptId: '', //受托人部门id
      beEntrustedDeptName: '', //受托人部门名称
      produceRoutingId: null,
      produceRoutingName: '',
      procedureList: [],
      pleaseEntrustObjList: [], //具体请托对象
      type: '', //类型
      status: '',
      describes: '', //描述
      finishTime: '', //完成时间
      processInstanceId: '', //流程实例id
      factoriesName: '',
      factoriesId: '',
      priority: '',
      beEntrustedFactoriesId: '', //受托工厂id
      beEntrustedFactoriesName: '', //受托工厂名称
      id: '',
      isLast: 0
    };
  };
  export default {
    components: { produceOrder, detail, deptSelect },
    data() {
      return {
        visible: false,
        loading: null,
        activeComp: 'main',
        planType: [
          { label: '所有计划类型', value: null },
          { label: '内销计划', value: '1' },
          { label: '外销计划', value: '2' },
          { label: '预制计划', value: '3' }
        ],
        options: [
          {
            name: '一般',
            value: 1
          },
          {
            name: '紧急',
            value: 2
          }
        ],
        tabOptions: [
          { key: 'main', name: '异常详情' },
          { key: 'bpm', name: '流程详情' }
        ],
        form: { ...defaultForm() },
        // 表单验证规则
        rules: {
          type: [{ required: true, message: '请选择', trigger: 'change' }],
          name: [{ required: true, message: '请输入', trigger: 'change' }],

          workOrderCode: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          beEntrustedDeptId: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          finishTime: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          beEntrustedFactoriesId: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          isLast: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        type: '',
        title: '创建',
        produceTaskList: [],
        factoryList: [],
        orderList: [],
        selection: [],
        current: null,
        columns: [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center',
            reserveSelection: true
          },
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'categoryName',
            label: '产品名称',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          // {
          //   prop: 'apsWorkOrderCode',
          //   label: '生产订单号',
          //   slot: 'apsWorkOrderCode',
          //   align: 'center',
          //   minWidth: 110,
          //   showOverflowTooltip: true
          // },
          {
            prop: 'productionPlanCode',
            label: '计划编号',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'brandNum',
            label: '牌号',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'batchNo',
            label: '批次号',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'describes',
            slot: 'describes',
            label: '需求描述',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'totalCount',
            slot: 'totalCount',
            label: '请托数量',
            align: 'center',
            minWidth: 140,
            showOverflowTooltip: true,
            headerSlot: 'totalCountHead'
          },
          {
            prop: 'planType',
            label: '计划类型',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true,
            formatter: (row) => {
              const obj = this.planType.find((i) => i.value == row.planType);
              return obj && obj.label;
            }
          },
          {
            prop: 'workOrderCode',
            label: '生产工单号',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'specification',
            label: '规格',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          // {
          //   prop: 'name',
          //   label: '名称',
          //   width: 130,
          //   showOverflowTooltip: true,
          //   align: 'center'
          // },
          {
            prop: 'modelType',
            label: '型号',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'produceRoutingName',
            label: '工艺路线',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'bomType',
            label: 'BOM分类',
            align: 'center',
            showOverflowTooltip: true,
            formatter: (row) => {
              if (row.bomType == 1) {
                return '产品(PBOM)';
              }
              if (row.bomType == 2) {
                return '加工(MBOM)';
              }
              if (row.bomType == 3) {
                return '装配(ABOM)';
              }
              return '';
            }
          },
          {
            prop: 'bomCategoryVersions',
            label: 'BOM版本',
            align: 'center',
            width: 130,
            showOverflowTooltip: true,
            formatter: (row) => {
              if (row.bomCategoryName) {
                return `${row.bomCategoryName} (V${row.bomCategoryVersions}.0)`;
              }
              return '';
            }
          },
          {
            prop: 'taskId',
            slot: 'taskId',
            label: '工序',
            align: 'center',
            minWidth: 150,
            showOverflowTooltip: true,
            headerSlot: 'taskIdHead'
          },
          {
            prop: 'categoryCode',
            label: '编码',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'planDeliveryTime',
            slot: 'planDeliveryTime',
            label: '完成日期',
            align: 'center',
            minWidth: 260,
            headerSlot: 'planDeliveryTimeHead'
          },
          {
            prop: 'planStartTime',
            label: '计划开始时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 130,
            sortable: true
          },
          {
            prop: 'planCompleteTime',
            label: '计划结束时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 130,
            sortable: true
          },
          {
            prop: 'startTime',
            label: '工单开始时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 130,
            sortable: true
          },
          {
            prop: 'completeTime',
            label: '工单结束时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 130,
            sortable: true
          }
          // {
          //   prop: 'priority',
          //   label: '优先级',
          //   align: 'center',
          //   minWidth: 120
          // }
        ]
      };
    },

    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      }
    },
    created() {
      this.getFactoryList();
    },
    methods: {
      open(type, row) {
        this.visible = true;
        this.orderList = [];
        if (type == 'add') {
          this.form.pleaseEntrustDeptName =
            this.$store.state.user.info.groupName;
          this.form.pleaseEntrustDeptId = this.$store.state.user.info.groupId;
          this.form.pleaseEntrustUserName = this.$store.state.user.info.name;
          this.form.pleaseEntrustUserId = this.$store.state.user.info.userId;

          const data = this.factoryList.filter(
            (it) => it.factoryId == this.$store.state.user.info.factoryId
          );

          if (data.length != 0) {
            this.form.factoriesId = data[0].factoryId;
            this.form.factoriesName = data[0].factoryName;
          }
        } else if (type == 'edit' || type == 'detail') {
          this.getDetail(row.id);
        }

        this.type = type;

        this.title = type == 'add' ? '新增' : type == 'edit' ? '修改' : '详情';
      },

      addOder() {
        this.$refs.produceOrderRef.open(this.orderList);
      },

      async getDetail(id) {
        try {
          const res = await pleaseEntrustDetail(id);
          const data = res?.data || {};

          // 从 data 中结构需要的字段
          const {
            applyDeptName,
            applyDeptId,
            createUserName,
            createUserId,
            applyFactoriesId,
            applyFactoriesName,
            beEntrustedDeptId,
            beEntrustedDeptName,
            beEntrustedFactoriesName,
            beEntrustedFactoriesId,
            name,
            type,
            priority,
            id: dataId
          } = data;

          // 一次性合并到 form
          Object.assign(this.form, {
            pleaseEntrustDeptName: applyDeptName,
            pleaseEntrustDeptId: applyDeptId,
            pleaseEntrustUserName: createUserName,
            pleaseEntrustUserId: createUserId,
            factoriesId: applyFactoriesId,
            factoriesName: applyFactoriesName,
            beEntrustedDeptId,
            beEntrustedDeptName,
            beEntrustedFactoriesName,
            beEntrustedFactoriesId,
            name,
            type,
            priority,
            id: dataId
          });

          // 深拷贝时添加 taskList
          const newData = {
            ...this.deepCopy(data),
            taskList: []
          };

          this.orderList.push(newData);

          await this.getOrderTaskList();
        } catch (error) {
          console.error('加载委托详情失败：', error);
        }
      },

      removeOder() {
        this.$confirm('此操作将删除这些工单, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            for (let item of this.selection) {
              const index = this.orderList.findIndex((it) => it.id == item.id);
              this.orderList.splice(index, 1);
            }
          })
          .catch(() => {});
      },

      beEntrustedDeptIdChange(val, row) {
        this.form.beEntrustedDeptName = row.name;
      },
      factoryListChange(row) {
        this.form.beEntrustedFactoriesName = row.name;
      },

      async getFactoryList() {
        const { list } = await warehouseDefinition.getFactoryarea({
          pageNum: 1,
          size: 999,
          type: 1
        });
        this.factoryList = list || [];
      },
      cancel() {
        this.form = { ...defaultForm() };
        this.produceTaskList = [];
        this.visible = false;
      },
      choose(list) {
        if (!list || list.length === 0) {
          this.orderList = [];
          return;
        }

        const getKey = (item) => item.id;
        const newKeys = new Set(list.map(getKey));
        const oldKeys = new Set(this.orderList.map(getKey));

        const keptOldList = this.orderList.filter((oldItem) =>
          newKeys.has(getKey(oldItem))
        );

        const addedItems = list.filter((item) => !oldKeys.has(getKey(item)));

        const newList = addedItems.map((item) => {
          const copy = this.deepCopy(item);

          Object.assign(copy, {
            describes: '',
            totalCount: copy.formingNum,
            taskList: [],
            taskId: '',
            taskName: '',
            beEntrustedFactoriesId: '',
            beEntrustedFactoriesName: '',
            status: '',
            beEntrustedDeptName: '',
            beEntrustedDeptId: '',
            measuringUnit: copy.unit,
            categoryName: copy.productName,
            categoryCode: copy.productCode,
            workOrderId: copy.id,
            workOrderCode: copy.code,
            brandNum: copy.brandNo,
            modelType: copy.model,
            name: '',
            type: '',
            workOrderCode: copy.code,
            planDeliveryTime: copy.startTime,
            applyDeptId: this.form.pleaseEntrustDeptId,
            applyDeptName: this.form.pleaseEntrustDeptName,
            applyFactoriesId: this.form.factoriesId,
            applyFactoriesName: this.form.factoriesName
          });

          return copy;
        });

        this.orderList = [...keptOldList, ...newList];

        this.getOrderTaskList();
      },

      async getOrderTaskList() {
        for (const item of this.orderList) {
          const res = await getProduceTaskList({
            isDetail: true,
            pageNum: 1,
            routingId: item.produceRoutingId,
            size: -1
          });

          item.taskList = res.list;
        }
      },

      deepCopy(obj, hash = new WeakMap()) {
        if (obj === null) return null;
        if (obj instanceof Date) return new Date(obj);
        if (obj instanceof RegExp) return new RegExp(obj);
        if (typeof obj !== 'object' && typeof obj !== 'function') return obj;
        if (hash.has(obj)) return hash.get(obj);

        const result = Array.isArray(obj) ? [] : {};
        hash.set(obj, result);

        return Object.keys(obj).reduce((acc, key) => {
          acc[key] = this.deepCopy(obj[key], hash);
          return acc;
        }, result);
      },

      taskListChange(item, index) {
        const data = item.taskList.filter((it) => it.id == item.taskId);

        this.orderList[index].taskName = data[0].name;
      },

      save(type) {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return false;
          }

          if (this.orderList.length == 0) {
            return this.$message.warning('请添加产品信息');
          }

          for (let item of this.orderList) {
            if (!item.totalCount) {
              return this.$message.warning('请托数量不能为空');
            }

            if (!item.taskId) {
              return this.$message.warning('工序不能为空');
            }

            if (!item.planDeliveryTime) {
              return this.$message.warning('完成日期不能为空');
            }
          }

          this.orderList.forEach((item) => {
            item.beEntrustedFactoriesId = this.form.beEntrustedFactoriesId;
            item.beEntrustedFactoriesName = this.form.beEntrustedFactoriesName;
            item.beEntrustedDeptName = this.form.beEntrustedDeptName;
            item.beEntrustedDeptId = this.form.beEntrustedDeptId;
            item.isLast = this.form.isLast;
            item.name = this.form.name;
            item.type = this.form.type;
            item.status = type == 1 ? 0 : 1;
            item.approvalStatus = type == 1 ? 0 : 1;
          });
          let URL;

          const clearOrderIds = () => {
            this.orderList.forEach((it) => (it.id = ''));
          };

          if (type === 1) {
            URL = this.type === 'edit' ? update : save;
          } else {
            URL = addSubmit;
          }

          if (this.type === 'add' && (type !== 1 || type === 1)) {
            clearOrderIds();
          }

          this.loading = this.$loading({
            lock: true,
            text: '加载中',
            background: 'rgba(0, 0, 0, 0.7)'
          });

          URL(this.orderList)
            .then((res) => {
              this.loading.close();
              this.$message.success('成功');
              this.cancel();
              this.$emit('refresh');
            })
            .catch((e) => {
              this.loading.close();
            });
        });
      }
    }
  };
</script>
<style lang="scss" scoped>
  .basic-details-title {
    margin: 10px 0;
  }

  .add-product {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    font-size: 30px;
    color: #1890ff;
    margin: 10px 0;
    cursor: pointer;
  }

  .create-form .el-form-item {
    margin-bottom: 15px !important;
  }
</style>
