<template>
  <el-form ref="form1" :model="form" :rules="rules" label-width="120px">
    <el-row>
      <el-col :span="6">
        <el-form-item label="编码:">
          <el-input
            :maxlength="20"
            v-model="form.code"
            disabled
            placeholder="请输入"
          />
        </el-form-item>
      </el-col>

      <!-- <el-col :span="6">
        <el-form-item label="质检类型:" prop="qualityType">
          <DictSelection
            dictName="质检计划类型"
            v-model="form.qualityType"
            :disabled="btnType == 'detail'"
          ></DictSelection>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="质检方式:" prop="qualityMode">
          <DictSelection
            dictName="取样类型"
            v-model="form.qualityMode"
            clearable
            :disabled="btnType == 'detail'"
          ></DictSelection>
        </el-form-item>
      </el-col>-->
      <el-col :span="6">
        <el-form-item label="产品名称:" prop="productName">
          <el-input
            disabled
            v-model="form.productName"
            @click.native="addProduct"
            readonly
            placeholder="请选择"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="产品编码:" prop="productCode">
          <el-input v-model="form.productCode" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="批次号:" prop="batchNo">
          <el-input v-model="form.batchNo" disabled />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="6">
        <el-form-item label="规格:" prop="specification">
          <el-input v-model="form.specification" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="型号:" prop="modelType">
          <el-input v-model="form.modelType" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="牌号:" prop="brandNo">
          <el-input v-model="form.brandNo" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="总数量:" prop="total">
          <el-input
            type="number"
            v-model="form.total"
            @input="inputTotal"
            disabled
          />
        </el-form-item>
      </el-col>
    </el-row>
    <!-- <div style="text-align: right; margin-bottom: 22px">
      <div @click="toggleExpand">
        <div v-if="isExpanded"> <i class="el-icon-arrow-up"></i>收起 </div>
        <div v-if="!isExpanded">
          <i class="el-icon-arrow-down"></i>展开更多
        </div>
      </div>
    </div> -->
    <!-- v-if="isExpanded" -->
    <div>
      <el-row>
        <el-col :span="6">
          <el-form-item label="质检部门" prop="groupId">
            <deptSelect
              :disabled="btnType == 'detail'"
              v-model="form.groupId"
              @changeGroup="searchDeptNodeClick"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="质检人" prop="qualityId">
            <el-select
              :disabled="btnType == 'detail'"
              v-model="form.qualityId"
              @change="changeExecutor"
              size="small"
              style="width: 100%"
              filterable
            >
              <el-option
                v-for="item in executorList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="质检时间:" prop="qualityTime">
            <el-date-picker
              class="w100"
              v-model="form.qualityTime"
              type="date"
              value-format="yyyy-MM-dd"
              :disabled="btnType == 'detail'"
              placeholder="请选择"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="工时(h):" prop="hours">
            <el-input
              v-model="form.hours"
              :disabled="btnType == 'detail'"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="合格数:" prop="qualifiedNumber">
            <el-input
              type="number"
              :min="0"
              :disabled="btnType == 'detail'"
              @input="limitation('qualifiedNumber')"
              @blur="quantityCalculation"
              v-model="form.qualifiedNumber"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="不合格数:" prop="noQualifiedNumber">
            <el-input
              type="number"
              :min="0"
              :disabled="btnType == 'detail'"
              @input="limitation('noQualifiedNumber')"
              @blur="quantityCalculation"
              v-model="form.noQualifiedNumber"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合格率:" prop="qualificationRate">
            <el-input v-model="form.qualificationRate" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="不合格率:" prop="noQualificationRate">
            <el-input v-model="form.noQualificationRate" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="总重量:" prop="totalWeight">
            <el-input
              type="number"
              :disabled="btnType == 'detail'"
              v-model="form.totalWeight"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="计量类型" prop="inspectionStandards">
            <!-- 计量 计重 -->
            <el-select
              style="width: 100%"
              v-model="form.inspectionStandards"
              placeholder="请选择"
              :disabled="true"
            >
              <el-option
                v-for="item in inspectionStandardsList"
                :label="item.label"
                :value="item.value"
                :key="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="检验方式:" prop="qualityMode">
            <!-- <DictSelection dictName="取样类型" v-model="form.qualityMode" :disabled="qualityType == 1"></DictSelection> -->
            <el-select
              @change="changeQualityMode"
              style="width: 100%"
              v-model="form.qualityMode"
              placeholder="请选择"
              :disabled="
                parseInt(qualityType1) == 1 || parseInt(qualityType1) == 3
              "
            >
              <el-option
                v-for="item in qualityModeList"
                :label="item.label"
                :value="item.value"
                :key="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="6" v-if="btnType != 'detail'">
          <el-form-item label="取样数量:" prop="sampleNumber" :rules="{
            required: form.qualityMode == 2 ? true : false,
            message: '请输入取样数量',
            trigger: 'blur'
          }" v-if="form.qualityMode == 2">
            <div style="display: flex;align-items: center;justify-content: space-between;">
              <el-input type="number"
                :disabled="form.qualityMode == null || form.qualityMode == 1 || (form.qualityMode == 2 && form.sampleNumber) ? true : false"
                v-model="form.sampleNumber" @change="handleChangeNumber" style="width: calc(100% - 90px)" />
              <DictSelection dictName="计量单位" clearable v-model="form.sampleMeasureUnit" disabled size="mini"
                style="width: 90px;margin-left: 12px;">
              </DictSelection>
            </div>
          </el-form-item>
        </el-col>-->
        <!-- <el-col :span="6" v-if="btnType != 'detail'">
          <el-form-item label="取样数量:" prop="sampleNumber" :rules="{
            required: form.qualityMode == 2 ? true : false,
            message: '请输入取样数量',
            trigger: 'blur'
          }" v-if="form.qualityMode == 2">
            <div style="display: flex;align-items: center;justify-content: space-between;">
              <el-input type="number"
                :disabled="form.qualityMode == null || form.qualityMode == 1 || (form.qualityMode == 2 && form.sampleNumber) ? true : false"
                v-model="form.sampleNumber" @change="handleChangeNumber" style="width: calc(100% - 90px)" />
              <DictSelection dictName="计量单位" clearable v-model="form.sampleMeasureUnit" disabled size="mini"
                style="width: 90px;margin-left: 12px;">
              </DictSelection>
            </div>
          </el-form-item>
        </el-col>-->
        <!-- <el-col :span="6">
          <el-form-item label="合格证号:" prop="certificateNumber">
            <el-input
              v-model="form.certificateNumber"
              :disabled="btnType == 'detail'"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col> -->

        <el-col :span="6">
          <!-- <el-form-item label="质检结果:" prop="qualityResults" v-if="form.qualityMode == 2"> -->
          <el-form-item label="质检结果:" prop="qualityResults">
            <el-select
              v-model="form.qualityResults"
              placeholder="请选择"
              style="width: 100%"
              :disabled="btnType == 'detail'"
            >
              <el-option label="合格" :value="1" />
              <el-option label="不合格" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6" v-if="parseInt(qualityType1) == 2">
          <el-form-item label="工艺路线:">
            <el-input
              @click.native="openVersion"
              clearable
              v-model="form.produceRoutingName"
              :disabled="btnType == 'detail'"
              placeholder="请选择"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="parseInt(qualityType1) == 2">
          <el-form-item label="工序:">
            <el-select
              style="width: 100%"
              v-model="form.produceTaskId"
              placeholder="请选择"
              clearable
              @change="produceTaskChange"
              :disabled="btnType == 'detail'"
            >
              <el-option
                v-for="item in produceTaskList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="6">
          <el-form-item label="质检类型:">
            <el-input
              v-model="form.certificateNumber"
              disabled
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col> -->

        <el-col :span="6">
          <el-form-item label="备注:" prop="remark">
            <el-input
              type="textarea"
              v-model="form.remark"
              placeholder="请输入"
              :disabled="btnType == 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="附件:" prop="accessory">
            <fileUpload
              v-model="form.accessory"
              :type="btnType == 'detail' ? 'view' : ''"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </div>
    <ProductionVersion ref="versionRefs" @changeProduct="changeProduct" />
    <EquipmentDialog ref="equipmentRefs" @choose="choose" />
  </el-form>
</template>
<script>
  import deptSelect from '@/components/CommomSelect/dept-select.vue';
  import fileUpload from '@/components/addDoc/index.vue';

  import ProductionVersion from './ProductionVersion.vue';
  import EquipmentDialog from './EquipmentDialog.vue';
  //接口
  import { getUserPage } from '@/api/system/organization';

  import { getProduceTaskList } from '@/api/aps';
  import { getByCode } from '@/api/system/dictionary-data';

  export default {
    components: {
      EquipmentDialog,
      ProductionVersion,
      deptSelect,
      fileUpload
    },
    props: {
      form: {
        type: Object,
        default: () => {}
      },
      btnType: {
        type: String,
        default: ''
      },
      qualityType1: {
        type: Number,
        default: ''
      },
      sampleList: {
        type: Array,
        default: () => []
      }
    },
    watch: {
      // 'form.qualityMode': {
      //   handler(newVal) {
      //     if (newVal) {
      //       this.$emit('changeModel', newVal);
      //     } else {
      //       console.log('清空样品清单');
      //       // this.$emit('table2');
      //     }
      //   },
      //   immediate: false
      // },
      // 'form.inspectionStandards': {
      //   handler(newVal) {
      //     if (newVal && this.qualityType1 == 2) {
      //       this.$emit('changeInspectionStandardsModel', newVal);
      //     } else {
      //       console.log('清空样品清单');
      //       // this.$emit('table2');
      //     }
      //   },
      //   immediate: false
      // },
      // 新增 *** 监听合格率更改 质检结果
      // 'form.qualificationRate': {
      //   handler(newVal) {
      // if (newVal == '100.00%' || newVal == '100%' || newVal == '100.0%') {
      //   this.$set(this.form, 'qualityResults', 1);
      // } else {
      //   this.$set(this.form, 'qualityResults', 2);
      //   // this.$emit('table2');
      // }
      //   },
      //   immediate: false,
      //   deep: true
      // }
    },
    data() {
      return {
        executorList: [],
        sourceList: [],
        rules: {
          productName: [
            { required: true, message: '请选择产品', trigger: 'change' }
          ],
          qualifiedNumber: [
            { required: true, message: '请输入合格数', trigger: 'blur' }
          ],
          noQualifiedNumber: [
            { required: true, message: '请输入不合格数', trigger: 'blur' }
          ],
          qualityTime: [
            { required: true, message: '请选择质检时间', trigger: 'blur' }
          ],
          groupId: [
            { required: true, message: '请选择质检部门', trigger: 'change' }
          ],
          qualityId: [
            { required: true, message: '请选择质检人', trigger: 'change' }
          ],
          qualityResults: [
            { required: true, message: '请选择质检结果', trigger: 'change' }
          ],
          inspectionStandards: [
            { required: true, message: '请选择检验标准', trigger: 'change' }
          ]
        },
        produceTaskList: [],
        inspectionStandardsList: [],
        qualityModeList: [],
        isExpanded: false
      };
    },
    created() {
      this.getDictListIqoCode('measurement_type');
      this.getQualityModeList('quality_method_code');
    },
    methods: {
      // *** 只能输入大于0的数字
      limitation(val) {
        this.form[val] =
          this.form[val].replace(/[^\d]/g, '').replace(/^0+/, '') || '0';
      },
      // *** 计算合格数 不合格数
      quantityCalculation() {
        let qualifiedNumber = this.form.qualifiedNumber - 0;
        let noQualifiedNumber = this.form.noQualifiedNumber - 0;
        let total = qualifiedNumber + noQualifiedNumber;
        let passRate = ((qualifiedNumber / this.form.total) * 100).toFixed(2);
        let failureRate = ((noQualifiedNumber / this.form.total) * 100).toFixed(
          2
        );

        console.log(passRate, failureRate, '合格率');
        console.log(total, '总数');
        this.form.qualificationRate = passRate + '%';
        this.form.noQualificationRate = failureRate + '%';
        if (total != this.form.total) {
          this.$message.warning('合格数加上不合格数需要等于总数量');
          return false;
        }
        return true;
      },

      toggleExpand() {
        this.isExpanded = !this.isExpanded;
      },
      toggleExpand2() {
        this.isExpanded = true;
        this.$nextTick(() => {
          this.$refs.form1.validateField('qualityResults');
        });
      },
      async getDictListIqoCode(code) {
        let { data: res } = await getByCode(code);
        this.inspectionStandardsList = res.map((item) => {
          let values = Object.keys(item);
          return {
            value: Number(values[0]),
            label: item[values[0]]
          };
        });

        console.log(this.inspectionStandardsList, '2222222222222222');
      },
      async getQualityModeList(code) {
        let { data: res } = await getByCode(code);
        this.qualityModeList = res.map((item) => {
          let values = Object.keys(item);
          return {
            value: Number(values[0]),
            label: item[values[0]]
          };
        });
      },
      // 打开工艺路线弹窗
      openVersion() {
        this.$refs.versionRefs.open();
      },
      //工艺路线回调
      changeProduct(data) {
        this.form.produceRoutingId = data.id;
        this.form.produceRoutingName = data.name;
        this.form.produceTaskId = '';
        this.form.produceTaskName = '';
        this.getTaskList();
      },
      // 获取工序数据
      async getTaskList() {
        if (!this.form.produceRoutingId) {
          return;
        }
        const res = await getProduceTaskList({
          isDetail: true,
          pageNum: 1,
          routingId: this.form.produceRoutingId,
          size: -1
        });
        this.produceTaskList = res?.list;
      },
      // 选择工序
      produceTaskChange() {
        if (!this.form.produceTaskId) {
          return;
        }
        this.form.produceTaskName = this.produceTaskList.find(
          (item) => item.id == this.form.produceTaskId
        ).name;
      },
      // 产品名称
      addProduct() {
        this.$refs.equipmentRefs.open();
      },
      choose(data) {
        this.form.productCode = data[0].code;
        this.form.productName = data[0].name;
        this.form.specification = data[0].specification;
        this.form.modelType = data[0].modelType;
        this.form.brandNo = data[0].brandNum;
      },

      //选择部门(搜索)
      searchDeptNodeClick(info, row) {
        if (info) {
          const params = { groupId: info };
          this.getUserList(params);
          this.form.groupName = row.name;
        } else {
          this.form.executeGroupId = null;
        }
      },
      // 获取人员
      async getUserList(params) {
        try {
          let data = { pageNum: 1, size: -1 };
          // 如果传了参数就是获取巡点检人员数据
          if (params) {
            data = Object.assign(data, params);
          }
          const res = await getUserPage(data);
          this.executorList = res.list;
        } catch (error) {}
      },
      // 人员选择
      changeExecutor(val) {
        if (val) {
          this.form.executeId = val;
          this.form.executeName = this.executorList.filter(
            (item) => item.id === val
          )[0].name;
        }
      },
      inputTotal(val) {
        if (val) {
          this.form.total = val;
          this.form.qualifiedNumber = val;
        }
      },
      handleChangeNumber(val) {
        this.form.sampleNumber = val;
        console.log(val);
        this.$emit('changeNumber', val);
      },

      //更新合格率
      updateQualificationRate(
        qualifiedNumber,
        noQualifiedNumber,
        qualificationRate,
        noQualificationRate
      ) {
        this.form.qualifiedNumber = qualifiedNumber;
        this.form.noQualifiedNumber = noQualifiedNumber;
        this.form.qualificationRate = qualificationRate + '%';
        this.form.noQualificationRate = noQualificationRate + '%';
      },
      //解决换检验方式的时候
      changeQualityMode(val) {
        console.log(val, 'isInfoChangeModel');
        if (val) {
          this.$emit('changeModel', val);
        } else {
          console.log('清空table2数据');
          this.$emit('table2');
        }
      }
    }
  };
</script>
<style lang="scss" scoped></style>
