<template>
  <div>
    <ele-modal
      :visible.sync="visible"
      v-if="visible"
      title="受托转生产订单"
      width="80vw"
      append-to-body
      :maxable="true"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="create-form"
      >
        <el-row :gutter="24">
          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="所属工厂:" prop="orderType">
              <el-input
                clearable
                :maxlength="20"
                v-model="form.applyFactoriesName"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="请托部门:" prop="orderType">
              <el-input
                clearable
                :maxlength="20"
                v-model="form.applyDeptName"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="请托人:" prop="orderType">
              <el-input
                clearable
                :maxlength="20"
                v-model="form.createUserName"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="受托工厂:" prop="orderType">
              <el-input
                clearable
                :maxlength="20"
                v-model="form.beEntrustedFactoriesName"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="受托部门:" prop="orderType">
              <el-input
                clearable
                :maxlength="20"
                v-model="form.beEntrustedDeptName"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="类型:">
              <DictSelection
                dictName="请托类型"
                v-model="form.type"
                disabled
              ></DictSelection>
            </el-form-item>
          </el-col>

          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="名称:">
              <el-input clearable v-model="form.productName" disabled />
            </el-form-item>
          </el-col>

          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="编码:">
              <el-input clearable v-model="form.productCode" disabled />
            </el-form-item>
          </el-col>

          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="牌号:">
              <el-input clearable v-model="form.brandNo" disabled />
            </el-form-item>
          </el-col>

          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="型号:">
              <el-input clearable v-model="form.model" disabled />
            </el-form-item>
          </el-col>

          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="规格:">
              <el-input clearable v-model="form.specification" disabled />
            </el-form-item>
          </el-col>

          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="批次号:">
              <el-input clearable v-model="form.batchNo" disabled />
            </el-form-item>
          </el-col>

          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="订单数量:">
              <el-input clearable v-model="form.contractNum" disabled>
                <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="planDeliveryTime">
              <el-date-picker
                :picker-options="pickerOptions"
                style="width: 100%"
                v-model="form.planDeliveryTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                disabled
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="计划开始时间:">
              <el-input clearable v-model="form.planStartTime" disabled>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="计划结束时间:">
              <el-input clearable v-model="form.planCompleteTime" disabled>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="工艺路线:" prop="produceRoutingName">
              <el-input
                v-model="form.produceRoutingName"
                placeholder="请选择工艺路线"
                @click.native="chooseRoute"
                readonly
              />
            </el-form-item>
          </el-col>

          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="紧急程度:">
              <el-select
                style="width: 100%"
                v-model="form.priority"
                placeholder="请选择"
                clearable
                disabled
              >
                <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: 12, md: 18 } : { span: 12 }">
            <el-form-item label="需求描述:">
              <el-input
                clearable
                v-model="form.describes"
                type="textarea"
                :rows="4"
                disabled
              />
            </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"> 确定 </el-button>
      </template>
      <!-- 选择工艺路线 -->
      <ProcessRoute ref="processRouteRef" @changeParent="changeParent" />
    </ele-modal>
  </div>
</template>

<script>
  import ProcessRoute from '@/components/selectionDialog/processRoute.vue';
  import { getFactoryList, createProductionOrder } from '@/api/beEntrusted';
  import { getByCode } from '@/api/system/dictionary-data';
  import { routeList } from '@/api/aps';
  import dayjs from 'dayjs';

  export default {
    name: 'CreateOrder',
    components: {
      ProcessRoute
    },
    props: {
      isAdd: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        visible: false,
        loading: null,
        disabledList: [], //已保存数据不做删除
        form: {
          bomCategoryId: '',
          factoriesId: '',
          applyFactoriesName: '', //所属工厂
          applyDeptName: '', //请托部门
          createUserName: '', //请托人
          beEntrustedFactoriesName: '', //受托工厂
          beEntrustedDeptName: '', //受托部门
          planDeliveryTime: dayjs(
            new Date().getTime() + 3600 * 1000 * 24 * 10
          ).format('YYYY-MM-DD'),
          productName: '',
          productCode: '',
          model: '',
          contractNum: '',
          describes: '',
          measuringUnit: '',
          brandNo: '',
          produceRoutingId: '',
          produceRoutingName: '',
          sourceId: '',
          sourceCode: '',
          priority: '',
          formingWeight: '',
          newWeightUnit: ''
        },
        // 表单验证规则
        rules: {
          produceRoutingName: [
            { required: true, message: '请选择工艺路线', trigger: 'blur' }
          ]
        },

        options: [
          {
            name: '一般',
            value: 1
          },
          {
            name: '紧急',
            value: 2
          }
        ],

        routingList: [],
        factoryList: [],

        title: '受托转生产订单',
        pickerOptions: {
          disabledDate: (time) => {
            // 禁用日期
            let nowData = new Date();
            nowData = new Date(nowData.setDate(nowData.getDate() - 1));
            return time < nowData;
          }
        },
        // 订单类型
        orderTypeList: [
          {
            id: 0,
            label: '库存性订单'
          },
          {
            id: 1,
            label: '生产性订单'
          },
          {
            id: 2,
            label: '无客户生产性订单'
          },
          {
            id: 4,
            label: '不定向订单'
          }
        ],
        selectIndex: 0, // 选择工艺路线的当前数据下标
        processingRequired: 0, // 生产类型跟BOM 版本是否必填 1:是 0:否
        sourceSalesOrderId: '', // 源销售订单ID
        modelList: [], // 机型数据
        colorList: [], // 颜色数据
        routeAllList: []
      };
    },
    watch: {
      // disabledList() {
      //   console.log(this.disabledList, 'disabledList');
      // }
    },
    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      },
      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      },
      // 是否必填字段
      isRequired() {
        // if (this.form.planType == 5) {
        //   return false;
        // }
        return this.processingRequired == 1;
      },
      // 工艺路线 输入框展示跟选择框判断
      isRouteSelect() {
        return (row) => {
          if (this.isRequired) {
            return true;
          }
          if (!row.selectionRowShow) {
            return true;
          }

          return false;
        };
      },

      // 选择按钮的显示
      isSelectShow() {
        // if (this.form.planType == 5) {
        //   return true;
        // }
        return this.processingRequired == 0;
      }
    },
    created() {},
    mounted() {
      this.getFactoryList();
      this.getCodeData();
    },
    methods: {
      // 获取
      async getCodeData() {
        let arr1 = await this.getLevelCode('product_model_key');
        let arr2 = await this.getLevelCode('product_color_key');
        this.modelList = arr1;
        this.colorList = arr2;
      },
      async getLevelCode(code) {
        try {
          const res = await getByCode(code);
          if (res.code == 0) {
            let list = Object.values(res.data).map((el) => {
              let k = Object.keys(el)[0];
              let v = Object.values(el)[0];
              return {
                label: v,
                value: k
              };
            });
            return list;
          }
        } catch (err) {
          this.$message.error(err.message);
        }
      },

      async getFactoryList() {
        this.factoryList = await getFactoryList();
      },
      open(row) {
        this.visible = true;

        row[0].bomCategoryId = '';
        row[0].bomCategoryName = '';
        row[0].bomCategoryVersions = '';
        row[0].bomType = '';
        row[0].produceRoutingId = '';
        row[0].produceRoutingName = '';

        this.form = this.deepCopy(row[0]);
        this.form.productCode = this.form.categoryCode;
        this.form.productName = this.form.categoryName;
        this.form.model = this.form.modelType;
        this.form.brandNo = this.form.brandNum;
        this.form.contractNum = this.form.totalCount;
        this.form.measuringUnit = this.form.measuringUnit;
        this.form.sourceCode = this.form.code;
        this.form.sourceId = this.form.id;
        this.form.formingWeight = this.form.totalWeight;
        this.form.newWeightUnit = this.form.weightUnit;

        this.getRoteList(this.form.beEntrustedFactoriesId);
      },

      async getRoteList(factoriesId) {
        await routeList({ factoriesId, pageNum: 1, size: -1 }).then((res) => {
          this.routeAllList = 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);
      },

      cancel() {
        this.form = {
          bomCategoryId: '',
          factoriesId: '',
          applyFactoriesName: '', //所属工厂
          applyDeptName: '', //请托部门
          createUserName: '', //请托人
          beEntrustedFactoriesName: '', //受托工厂
          beEntrustedDeptName: '', //受托部门
          planDeliveryTime: dayjs(
            new Date().getTime() + 3600 * 1000 * 24 * 10
          ).format('YYYY-MM-DD'),
          productName: '',
          productCode: '',
          model: '',
          contractNum: '',
          describes: '',
          measuringUnit: '',
          brandNo: '',
          produceRoutingId: '',
          produceRoutingName: '',
          sourceId: '',
          sourceCode: '',
          priority: ''
        };
        this.$refs.form.clearValidate();
        this.visible = false;
      },

      /* 保存编辑 */
      save() {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return false;
          }

          if (!this.form.produceRoutingName) {
            return this.$message.warning('请选择工艺路线');
          }

          // this.form.produceRoutingName = this.routeAllList.find(
          //   (item) => item.id === this.form.produceRoutingId
          // )?.name;

          this.form.planDeliveryTime = this.form.planDeliveryTime.split(' ')[0];

          let params = {
            ...this.form,
            sourceType: 3
          };

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

          createProductionOrder(params)
            .then((res) => {
              this.loading.close();
              this.$message.success('成功');
              this.cancel();
              this.$emit('refresh');
            })
            .catch((e) => {
              this.loading.close();
            });
        });
      },

      chooseRoute() {
        this.$refs.processRouteRef.open(this.form);
      },

      // 打开工艺路线
      openDialog(index) {
        this.selectIndex = index;
        this.$refs.processRouteRef.open();
      },

      // 选择工艺路线
      changeParent(item) {
        this.form.produceRoutingName = item.name;
        this.form.produceRoutingId = item.id;
        // console.log('item', item);
        // let data = this.form.productInfoList[this.selectIndex];
        // this.$set(data, 'bomVersionList', []);
        // this.$set(data, 'bomCategoryId', '');
        // this.$set(data, 'model', '');
        // this.$set(data, 'routingList', []);
        // this.$set(data, 'productType', '');
        // this.$set(data, 'produceRoutingName', item.name);
        // this.$set(data, 'produceRoutingId', item.id);
        // this.$set(data, 'selectionRowShow', true);
        // this.selectionRowShow = true;
      }
    }
  };
</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;
  }

  .header_required {
    .is-required:before {
      content: '*';
      color: #f56c6c;
      margin-right: 4px;
    }
  }
</style>
