<template>
  <ele-modal
    :visible.sync="visible"
    v-if="visible"
    :title="title"
    width="75vw"
    append-to-body
    @close="cancel"
    :maxable="true"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="create-form"
    >
      <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"
            ></DictSelection>
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="紧急程度:" prop="priority">
            <el-select
              style="width: 100%"
              v-model="form.priority"
              placeholder="请选择"
              clearable
            >
              <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: 12 } : { span: 6 }">
          <el-form-item label="名称:" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
        </el-col>

        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="请托数量:" prop="totalCount">
            <el-input v-model="form.totalCount">
              <template slot="append">{{ form.measuringUnit }}</template>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="请托工序:" prop="taskId">
            <el-select v-model="form.taskId" placeholder="请选择">
              <el-option
                v-for="item in newStepsList"
                :key="item.taskId"
                :label="item.taskTypeName"
                :value="item.taskId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { 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: 12 } : { 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 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 v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="受托工厂:" prop="beEntrustedFactoriesId">
            <el-select
              style="width: 100%"
              v-model="form.beEntrustedFactoriesId"
              placeholder="请选择"
              clearable
            >
              <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 v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="受托部门:" prop="beEntrustedDeptId">
            <deptSelect
              v-model="form.beEntrustedDeptId"
              @changeGroup="beEntrustedDeptIdChange"
            />
          </el-form-item>
        </el-col>

        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="完成日期:" prop="planDeliveryTime">
            <el-date-picker
              v-model="form.planDeliveryTime"
              type="datetime"
              placeholder="选择日期时间"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="是否尾工序:" prop="isLast">
            <el-radio-group v-model="form.isLast">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col v-bind="styleResponsive ? { lg: 24, md: 24 } : { span: 24 }">
          <el-form-item label="需求描述:">
            <el-input
              clearable
              v-model="form.describes"
              type="textarea"
              :rows="4"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template v-slot:footer>
      <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>
  </ele-modal>
</template>

<script>
  import deptSelect from '@/components/CommomSelect/dept-select.vue';
  import warehouseDefinition from '@/api/warehouseManagement/warehouseDefinition';
  import { getTaskInstanceById } from '@/api/produce/index';
  import { save, addSubmit, update } from '@/api/entrust/index';
  export default {
    components: { deptSelect },
    data() {
      return {
        title: '新增请托单',
        visible: false,
        form: {
          type: '',
          priority: '',
          name: '',
          pleaseEntrustDeptName: '',
          pleaseEntrustUserName: '',
          factoriesName: '',
          beEntrustedFactoriesId: '',
          beEntrustedDeptId: '',
          isLast: 0,
          describes: '',
          taskId: '',
          planDeliveryTime: '',
          beEntrustedDeptName: '',
          beEntrustedFactoriesName: '',
          pleaseEntrustDeptId: '',
          pleaseEntrustUserId: '',
          factoriesId: '',
          factoriesName: ''
        },
        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' }],
          planDeliveryTime: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          totalCount: [
            { required: true, message: '请输入', trigger: 'change' }
          ],
          taskId: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        factoryList: [],
        options: [
          {
            name: '一般',
            value: 1
          },
          {
            name: '紧急',
            value: 2
          }
        ],
        newStepsList: [],
        taskObj: null
      };
    },

    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      }
    },

    methods: {
      open(workOrderId, workData, taskObj) {
        this.taskObj = taskObj;
        const newList = workData.list.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: '',
            planDeliveryTime: copy.startTime,
            applyDeptId: this.form.pleaseEntrustDeptId,
            applyDeptName: this.form.pleaseEntrustDeptName,
            applyFactoriesId: this.form.factoriesId,
            applyFactoriesName: this.form.factoriesName
          });

          return copy;
        });

        const data = Object.assign(this.form, newList[0]);
        this.form = this.deepCopy(data);
        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;
        this.form.name = this.taskObj.name
          ? this.taskObj.name + '请托'
          : this.taskObj.taskTypeName + '请托';
        const taskId = this.taskObj.name
          ? this.taskObj.id
          : this.taskObj.taskId;
        console.log(taskId, 'taskId');
        this.getTaskInstanceByIdFn(workOrderId);
        this.getFactoryList();

        this.visible = true;
      },

      async getTaskInstanceByIdFn(workOrderId) {
        await getTaskInstanceById(workOrderId).then((res) => {
          let { data } = res;
          if (data.length) {
            data = data.filter((item) => item.taskId != -2);
            let arr = data.findIndex(
              (item) => item.sourceTaskId == this.taskObj.id
            );

            if (arr != -1) {
              data.splice(0, arr);
            }

            this.newStepsList = data;
          }
        });
      },

      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);
      },

      async getFactoryList() {
        const { list } = await warehouseDefinition.getFactoryarea({
          pageNum: 1,
          size: 999,
          type: 1
        });
        this.factoryList = list || [];

        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;
        }
      },

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

      cancel() {
        this.visible = false;
      },

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

          let URL;

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

          if (type === 1 && this.form.id) {
            // 编辑
            URL = update;
          } else if (type === 1) {
            // 新增
            URL = save;
            clearOrderIds();
          } else {
            // 其他类型提交
            URL = addSubmit;
            clearOrderIds();
          }

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

          console.log(this.form, 'this.form');

          const list = [];
          list.push(this.form);

          URL(list)
            .then((res) => {
              this.loading.close();
              this.$message.success('成功');
              this.cancel();
              this.$emit('refresh');
            })
            .catch((e) => {
              this.loading.close();
            });
        });
      }
    }
  };
</script>

<style></style>
