<template>
  <ele-modal
    width="80vw"
    :visible.sync="visible"
    :close-on-click-modal="false"
    custom-class="ele-dialog-form"
    :title="title"
  >
    <div class="form-wrapper">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="90px"
        class="formbox"
      >
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="名称:" prop="productName">
              <el-input
                @click.native="handleAdd"
                placeholder="请选择物料"
                v-model="form.productName"
                size="mini"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="编码:" prop="productCode">
              <el-input
                placeholder=""
                size="mini"
                disabled
                v-model="form.productCode"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="牌号:" prop="brandNum">
              <el-input
                placeholder=""
                size="mini"
                disabled
                v-model="form.brandNum"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="型号:" prop="modelType">
              <el-input
                placeholder=""
                size="mini"
                disabled
                v-model="form.modelType"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="规格:" prop="specification">
              <el-input
                placeholder=""
                size="mini"
                disabled
                v-model="form.specification"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <headerTitle title="计划信息"> </headerTitle>

        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="加工方式:" prop="produceType">
              <el-select
                v-model="form.produceType"
                style="width: 100%"
                @change="changeProduceType"
                size="mini"
              >
                <el-option
                  v-for="item of producedList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="BOM版本:" prop="bomCategoryId">
              <el-select
                v-model="form.bomCategoryId"
                style="width: 100%"
                @change="changeBomId"
                size="mini"
              >
                <el-option
                  v-for="item of bomVersionList"
                  :key="item.id"
                  :label="item.name + '(V' + item.versions + '.0)'"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="工艺路线:" prop="produceRoutingId">
              <el-select
                v-model="form.produceRoutingId"
                style="width: 100%"
                @change="changeRoute"
                size="mini"
              >
                <el-option
                  v-for="item of routingList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="生产数量:" prop="requiredFormingNum">
              <el-input
                v-model.number="form.requiredFormingNum"
                size="mini"
                oninput="value=value.replace(/[^\d]/g,'')"
                style="width: 100%"
                placeholder="输入数量"
              >
                <template slot="append">{{ form.measuringUnit }} </template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="批次号:" prop="batchNo">
              <el-input
                v-model="form.batchNo"
                size="mini"
                style="width: 100%"
                placeholder="输入批次号"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item
              label="要求完成日期:"
              label-width="110px"
              prop="reqMoldTime"
            >
              <el-date-picker
                style="width: 100%"
                size="mini"
                v-model="form.reqMoldTime"
                :pickerOptions="{
                  disabledDate: (time) =>
                    time.getTime() <
                    new Date(new Date().setHours(0, 0, 0, 0)).getTime()
                }"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item
              label="计划开始日期:"
              label-width="110px"
              prop="startTime"
            >
              <el-date-picker
                style="width: 100%"
                size="mini"
                v-model="form.startTime"
                :pickerOptions="{
                  disabledDate: (time) =>
                    time.getTime() <
                    new Date(new Date().setHours(0, 0, 0, 0)).getTime()
                }"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item
              label="计划结束日期:"
              label-width="110px"
              prop="endTime"
            >
              <el-date-picker
                style="width: 100%"
                size="mini"
                v-model="form.endTime"
                :pickerOptions="{
                  disabledDate: (time) =>
                    time.getTime() <
                    new Date(new Date().setHours(0, 0, 0, 0)).getTime()
                }"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 选择产品 -->
      <EquipmentDialog
        ref="equipmentRefs"
        @choose="confirmChoose"
        :selectList="[]"
      >
      </EquipmentDialog>
    </div>

    <template v-slot:footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="save" :loading="loading">
        确定
      </el-button>
    </template>
  </ele-modal>
</template>

<script>
  import EquipmentDialog from '@/views/saleOrder/components/EquipmentDialog';
  import { getCode } from '@/api/codeManagement';
  import {
    bomRoutingList,
    bomListByPlan,
    saveSaleToPlan,
    temporarilyUpdate
  } from '@/api/saleOrder';

  export default {
    components: {
      EquipmentDialog
    },
    props: {
      factoryType: {
        type: Number,
        default: 1
      },
      factoryObj: {
        type: Object,
        default: () => {}
      }
    },
    watch: {
      factoryType: {
        immediate: true,
        deep: true,
        handler(val) {
          this.type = val;
          this.title = val == 1 ? '新增临时计划' : '编辑临时计划';
          this.form = this.factoryObj;
        }
      }
    },
    data() {
      return {
        visible: true,
        title: '',
        type: 1,

        loading: false,
        form: {
          timeDimensionPlanType: 3,
          categoryId: '',
          productName: '',
          planType: 1,

          produceType: 2,
          bomCategoryId: '',
          produceRoutingId: '',
          requiredFormingNum: ''
        },

        bomVersionList: [],
        routingList: [],
        rules: {
          productName: [
            { required: true, message: '请选择名称', trigger: 'change' }
          ],
          bomCategoryId: [
            { required: true, message: '请选择BOM版本', trigger: 'blur' }
          ],

          produceRoutingId: [
            { required: true, message: '请选择工艺路线', trigger: 'blur' }
          ],

          reqMoldTime: [
            { required: true, message: '请选择要求完成日期', trigger: 'blur' }
          ],

          requiredFormingNum: [
            { required: true, message: '请输入生产数量', trigger: 'blur' }
          ]
        },

        producedList: [
          { code: 2, name: '加工' },
          { code: 3, name: '装配' }
        ]
      };
    },

    computed: {
      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      }
    },
    methods: {
      handleAdd() {
        this.$refs.equipmentRefs.open();
      },

      confirmChoose(list) {
        this.$set(this.form, 'categoryId', list[0].id);
        this.$set(this.form, 'productName', list[0].name);
        this.$set(this.form, 'productCode', list[0].code);
        this.$set(this.form, 'specification', list[0].specification);
        this.$set(this.form, 'brandNum', list[0].brandNum);
        this.$set(this.form, 'modelType', list[0].modelType);
        this.$set(this.form, 'measuringUnit', list[0].measuringUnit);

        this.bomListVersion();
      },

      handleDeleteItem(index) {
        this.form.salesOrders.splice(index, 1);
      },

      async getPlanCode() {
        this.loading = true;
        try {
          const code = await getCode('product_code');
          this.$set(this.form, 'code', code);
        } catch (err) {}
      },

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

          if (this.type == 1) {
            await this.getPlanCode();

            this.loading = true;
            saveSaleToPlan(this.form)
              .then((res) => {
                this.$message.success('新增成功！');
                this.$emit('close', true);
              })
              .finally(() => {
                this.loading = false;
              });
          } else {
            
            this.loading = true;
            temporarilyUpdate(this.form)
              .then((res) => {
                this.$message.success('修改成功！');
                this.$emit('close', true);
              })
              .finally(() => {
                this.loading = false;
              });
          }
        });
      },

      bomListVersion() {
        let param = {
          bomType: this.form.produceType,
          categoryId: this.form.categoryId
        };
        bomListByPlan(param).then((res) => {
          this.bomVersionList = res || [];
        });
      },

      getPlanRouting() {
        bomRoutingList(this.form.bomCategoryId).then((res) => {
          this.routingList = res || [];
        });
      },

      changeProduceType() {
        this.form.bomCategoryId = '';
        this.form['bomCategoryName'] = '';
        this.form['bomCategoryVersions'] = '';

        this.bomVersionList = [];

        this.routingList = [];
        this.form.produceRoutingId = '';
        this.form.produceRoutingName = '';
        this.form.produceVersionName = '';
        this.bomListVersion();
      },

      changeBomId() {
        this.routingList = [];
        this.form.produceRoutingId = '';
        this.form.produceRoutingName = '';
        this.form.produceVersionName = '';

        this.bomVersionList.forEach((f) => {
          if (f.id == this.form.bomCategoryId) {
            this.$set(this.form, 'bomCategoryName', f.name);
            this.$set(this.form, 'bomCategoryVersions', f.versions);
          }
        });

        this.getPlanRouting();
      },

      changeRoute() {
        this.routingList.forEach((f) => {
          if (f.id == this.form.produceRoutingId) {
            this.$set(this.form, 'produceRoutingName', f.name);
            this.$set(this.form, 'produceVersionName', f.version);
          }
        });
      },

      cancel() {
        this.$emit('close');
      }
    }
  };
</script>

<style lang="scss" scoped>
  .el-form-item {
    margin-bottom: 14px !important;
  }
</style>
