<template>
  <el-dialog
    title="实验报工"
    :visible.sync="visible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    width="80%"
    :maxable="true"

  >
    <header-title title="基础信息"> </header-title>
    <el-form
      label-width="115px"
      :model="form"
      :rules="[{}]"
      ref="formRef"
      :disabled="type == 'detail'"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="质检项：" prop="inspectionName">
            {{ tableData[0]?.inspectionName }}</el-form-item
          >
        </el-col>
        <el-col :span="8">
          <el-form-item label="编码：" prop="inspectionCode">
            {{ tableData[0]?.inspectionCode }}
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="批次号：" prop="batchNo">
            {{ tableData[0]?.batchNo }}
          </el-form-item>
        </el-col></el-row
      >
      <header-title title="  样品信息"> </header-title>
      <ele-pro-table
        :needPage="false"
        :columns="workColumns"
        :datasource="tableData"
      >
        <template v-slot:toolbar v-if="type != 'detail'">
          当前质检剩余样品数：{{ getSampleQuantityCount1 }}
        </template>
        <template v-slot:sampleQuantity="{ row, $index }">
          <el-input
            v-model="row.sampleQuantity"
            placeholder="请输入"
            :disabled="type == 'detail'"
            type="number"
            @input="inputValue('sampleQuantity', row, $index)"
          >
          </el-input>
        </template>

        <template v-slot:qualifiedQuantity="{ row, $index }">
          <el-input
            v-model="row.qualifiedQuantity"
            placeholder="请输入"
            :disabled="type == 'detail'"
            type="number"
            @input="inputValue('qualifiedQuantity', row, $index)"
          >
          </el-input>
        </template>
        <template v-slot:noQualifiedQuantity="{ row, $index }">
          <el-input
            v-model="row.noQualifiedQuantity"
            placeholder="请输入"
            :disabled="type == 'detail'"
            type="number"
            @input="inputValue('noQualifiedQuantity', row, $index)"
          >
          </el-input>
        </template>
        <template v-slot:lossNumber="{ row, $index }">
          <el-input
            v-model="row.lossNumber"
            placeholder="请输入"
            :disabled="type == 'detail'"
            type="number"
            @input="inputValue('lossNumber', row, $index)"
            @click.native="curretNum = row.lossNumber"
          >
          </el-input>
        </template>
        <template v-slot:lossNumberUnqualified="{ row, $index }">
          <el-input
            v-model="row.lossNumberUnqualified"
            placeholder="请输入"
            :disabled="type == 'detail'"
            type="number"
            @input="inputValue('lossNumberUnqualified', row, $index)"
            @click.native="curretNum = row.lossNumberUnqualified"
          >
          </el-input>
        </template>
        <template v-slot:retainedSampleQuantity="{ row, $index }">
          <el-input
            v-model="row.retainedSampleQuantity"
            placeholder="请输入"
            :disabled="type == 'detail'"
            type="number"
            @input="inputValue('retainedSampleQuantity', row, $index)"
            @click.native="curretNum = row.retainedSampleQuantity"
          >
          </el-input>
        </template>
        <template v-slot:retainedSampleUnqualified="{ row, $index }">
          <el-input
            v-model="row.retainedSampleUnqualified"
            placeholder="请输入"
            :disabled="type == 'detail'"
            type="number"
            @input="inputValue('retainedSampleUnqualified', row, $index)"
            @click.native="curretNum = row.retainedSampleUnqualified"
          >
          </el-input>
        </template>
      </ele-pro-table>
      <header-title title="实验数据" style="margin-top: 15px"> </header-title>
      <el-row>
        <el-col :span="8">
          <el-form-item label="实验编号：" prop="code">
            <el-input v-model="form.code" placeholder="请输入" :disabled="true">
            </el-input>
          </el-form-item> </el-col
      ></el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="实验时间：" prop="experimentalTime">
            <el-date-picker
              v-model="form.experimentalTime"
              type="datetime"
              placeholder="选择日期时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="执行标准：" prop="qualityStandardName">
            <el-input
              :value="getDictValue('质检标准类型', form.qualityStandardName)"
              placeholder="请输入"
              :disabled="true"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <header-title title="实验室/实验设备"> </header-title>
      <el-row>
        <el-col :span="8">
          <el-form-item label="实验室：" prop="workshopId">
            <el-select
              v-model="form.workshopId"
              style="width: 100%"
              placeholder="请选择"
            >
              <el-option
                v-for="item in laboratoryList"
                :key="item.workshopId"
                :label="item.workshopName"
                :value="item.workshopId"
                @click.native="form.workshopName = item.workshopName"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-for="(item, index) in form.experimentEquipmentList">
        <el-col :span="24">
          <el-row>
            <el-col :span="8">
              <el-form-item
                :label="'实验设备' + (index + 1) + '：'"
                prop="equipmentName"
              >
                <el-input
                  placeholder="请选择"
                  v-model="item.equipmentName"
                  @click.native="equipmentOpen(index)"
                  readonly
                  style="width: calc(100% - 30px)"
                >
                </el-input>
                <i
                  class="el-icon-delete"
                  style="
                    color: #f56c6c;
                    font-size: 16px;
                    margin-left: 10px;
                    cursor: pointer;
                  "
                  @click="delLaboratoryItemList(index)"
                ></i>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="24">
          <el-row>
            <el-col :span="8">
              <el-form-item label="开始时间：" prop="startTime">
                <el-date-picker
                  v-model="item.startTime"
                  type="datetime"
                  placeholder="选择日期时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 100%"
                >
                </el-date-picker
              ></el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="结束时间：" prop="endTime">
                <el-date-picker
                  v-model="item.endTime"
                  type="datetime"
                  placeholder="选择日期时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 100%"
                >
                </el-date-picker
              ></el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="24">
          <el-row>
            <el-col :span="16">
              <el-form-item label="运行参数：" prop="operatingParameters">
                <el-input
                  v-model="item.operatingParameters"
                  placeholder="请输入"
                >
                </el-input
              ></el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label=" " prop="industryType">
            <el-button type="primary" @click="addExperimentEquipmentList">
              新增实验设备
            </el-button>
          </el-form-item>
        </el-col></el-row
      >
      <header-title title="实验过程"> </header-title>
      <el-button type="primary" size="small" @click="releaseRulesRefOpen(1)"
        >选择实验过程</el-button
      >
      <el-row>
        <el-col :span="24">
          <experimentationProcess
            ref="experimentationProcess1"
            :edit="false"
          ></experimentationProcess> </el-col
      ></el-row>
      <header-title title="工艺要求"> </header-title>
      <el-input
        type="textarea"
        autosize
        placeholder="请输入内容"
        :disabled="true"
        v-model="form.processRequirementsJson"
      >
      </el-input>

      <header-title title="实验工具" style="margin-top: 15px"> </header-title>
      <el-button type="primary" size="small" @click="handleAdd('toolJson')"
        >选择实验工具</el-button
      >
      <ele-pro-table
        :needPage="false"
        :columns="unitColumns"
        :datasource="form.toolJson"
        style="margin-top: 15px"
      >
        <template v-slot:action="{ row, $index }">
          <el-popconfirm
            class="ele-action"
            title="确定要删除此条数据吗？"
            @confirm="remove($index, 'toolJson')"
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false" icon="el-icon-delete">
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>
      </ele-pro-table>

      <header-title title="实验耗材" style="margin-top: 15px"> </header-title>
      <el-button
        type="primary"
        size="small"
        @click="handleAdd('consumablesJson')"
        >选择实验耗材</el-button
      >
      <ele-pro-table
        :needPage="false"
        :columns="unitColumns1"
        style="margin-top: 15px"
        :datasource="form.consumablesJson"
      >
        <template v-slot:remark="{ row, $index }">
          <el-input type="textarea" v-model="row.remark"></el-input>
        </template>
        <template v-slot:batchNo="{ row, $index }">
          <el-input v-model="row.batchNo"></el-input>
        </template>

        <template v-slot:action="{ row, $index }">
          <el-popconfirm
            class="ele-action"
            title="确定要删除此条数据吗？"
            @confirm="remove($index, 'consumablesJson')"
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false" icon="el-icon-delete">
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>
      </ele-pro-table>
      <header-title title="实验记录" style="margin-top: 15px"> </header-title>
      <el-button type="primary" size="small" @click="releaseRulesRefOpen(2)"
        >选择实验记录</el-button
      >
      <el-row>
        <el-col :span="24">
          <experimentationProcess
            ref="experimentationProcess2"
            :edit="false"
          ></experimentationProcess> </el-col
      ></el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="实验结果：" prop="resultsDescription">
            <el-input
              type="resultsDescription"
              :rows="4"
              placeholder="请输入内容"
              v-model="form.resultsDescription"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="实验结论：" prop="results">
            <el-select v-model="form.results" placeholder="请选择">
              <el-option :label="'合格'" :value="1"> </el-option>
              <el-option :label="'不合格'" :value="2"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="实验图片：" prop="imgUrl">
            <imgList v-model="form.imgUrl"></imgList>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="附件图片：" prop="attachmentUrl">
            <imgList v-model="form.attachmentUrl"></imgList>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template v-slot:footer>
      <el-button size="small" @click="handleClose">关闭</el-button>
      <el-button
        type="primary"
        size="small"
        @click="save"
        v-if="type != 'detail'"
        >保存</el-button
      >
      <!-- <el-button type="primary" size="small" @click="submit">提交</el-button> -->
    </template>
    <releaseRules
      ref="releaseRulesRef"
      @success="releaseRulesSuccess"
    ></releaseRules>
    <ProductModal
      ref="productRefs"
      @chooseModal="chooseModal"
      @chooseCurrent="chooseCurrent"
    />
  </el-dialog>
</template>

<script>
  import dictMixins from '@/mixins/dictMixins';
  import experimentationProcess from '@/components/templateDiv/experimentationProcess.vue';
  import releaseRules from '@/components/releaseRules/index.vue';
  import { getFactoryarea } from '@/api/aps/index.js';
  import { save, getById, update } from '@/api/experimentReport/index.js';
  import ProductModal from '@/views/inspectionProject/components/ProductModal.vue';
  import imgList from '@/components/upload/imgList.vue';
  import detailMixins from '../mixins/detailMixins';

  export default {
    components: { experimentationProcess, releaseRules, ProductModal, imgList },
    props: {},
    mixins: [dictMixins, detailMixins],

    data() {
      return {
        visible: false,
        tableData: [],
        unitListKey: '',
        curretNum: 0,
        type: '',
        getSampleQuantityCount: 0,
        form: {
          code: '',
          correlationId: '',
          consumablesJson: [],
          toolJson: [],
          attachmentUrl: [],
          experimentalTime: '',
          imgUrl: [],
          procedureJson: null,
          qualityStandardName: '',
          qualityStandardId: '',
          processRequirementsJson: '',
          recordJson: null,
          qualityWorkOrderId: '',
          results: 1,
          resultsDescription: '',
          experimentEquipmentList: []
        },
        laboratoryList: [],
        unitColumns: [
          {
            minWidth: 200,
            prop: 'name',
            align: 'center',
            label: '工具名称',
            showOverflowTooltip: true
          },
          {
            minWidth: 200,
            prop: 'modelType',
            align: 'center',
            label: '型号',
            showOverflowTooltip: true
          },
          {
            minWidth: 200,
            prop: 'code',
            align: 'center',
            label: '编号',
            showOverflowTooltip: true
          },
          {
            columnKey: 'action',
            label: '操作',
            align: 'center',
            width: 100,
            resizable: false,
            slot: 'action',
            fixed: 'right'
          }
        ],
        unitColumns1: [
          {
            minWidth: 200,
            prop: 'name',
            align: 'center',
            label: '耗材名称',
            showOverflowTooltip: true
          },
          {
            minWidth: 200,
            prop: 'code',
            align: 'center',
            label: '编号',
            showOverflowTooltip: true
          },
          {
            minWidth: 200,
            prop: 'batchNo',
            slot: 'batchNo',
            align: 'center',
            label: '批次号',
            showOverflowTooltip: true
          },
          {
            minWidth: 200,
            prop: 'specification',
            align: 'center',
            label: '浓度',
            showOverflowTooltip: true
          },
          {
            minWidth: 200,
            prop: 'gys',
            align: 'center',
            label: '来源',
            showOverflowTooltip: true
          },
          {
            minWidth: 300,
            prop: 'remark',
            slot: 'remark',
            align: 'center',
            label: '过程',
            showOverflowTooltip: true
          },
          {
            columnKey: 'action',
            label: '操作',
            align: 'center',
            width: 100,
            resizable: false,
            slot: 'action',
            fixed: 'right'
          }
        ],
        workColumns: [
          {
            minWidth: 120,
            prop: 'sampleQuantity',
            slot: 'sampleQuantity',
            align: 'center',
            label: '样品数',
            showOverflowTooltip: true
          },
          {
            minWidth: 120,
            prop: 'qualifiedQuantity',
            align: 'center',
            slot: 'qualifiedQuantity',
            label: '合格数',
            showOverflowTooltip: true
          },
          {
            minWidth: 130,
            prop: 'noQualifiedQuantity',
            slot: 'noQualifiedQuantity',
            align: 'center',
            label: '不合格数',
            showOverflowTooltip: true
          },
          {
            minWidth: 140,
            prop: 'lossNumber',
            slot: 'lossNumber',
            align: 'center',
            label: '损耗数（合格品）',
            showOverflowTooltip: true
          },
          {
            minWidth: 150,
            prop: 'lossNumberUnqualified',
            slot: 'lossNumberUnqualified',
            align: 'center',
            label: '损耗数（不合格品）',
            showOverflowTooltip: true
          },
          {
            minWidth: 140,
            prop: 'retainedSampleQuantity',
            slot: 'retainedSampleQuantity',
            align: 'center',
            label: '留样数（合格品）',
            showOverflowTooltip: true
          },
          {
            minWidth: 150,
            prop: 'retainedSampleUnqualified',
            slot: 'retainedSampleUnqualified',
            align: 'center',
            label: '留样数（不合格品）',
            showOverflowTooltip: true
          }
        ]
      };
    },
    computed: {
      getSampleQuantityCount1() {
        return this.getSampleQuantityCount - this.numTotal;
      },
      numTotal() {
        return (
          (Number(this.tableData[0].lossNumber) || 0) +
          (Number(this.tableData[0].lossNumberUnqualified) || 0) +
          (Number(this.tableData[0].retainedSampleQuantity) || 0) +
          (Number(this.tableData[0].retainedSampleUnqualified) || 0)
        );
      }
    },
    watch: {},
    methods: {
      async open(row, type) {
        this.tableData = [row];
        this.type = type;
        this.getSampleQuantityCount = row.getSampleQuantityCount;
        if (row.experimentId) {
          this.$set(this, 'form', await getById(row.experimentId));
          this.$nextTick(() => {
            if (this.form.procedureJson) {
              this.$refs.experimentationProcess1.init(
                this.form.procedureJson.tempJson
              );
            }
            if (this.form.recordJson) {
              this.$refs.experimentationProcess2.init(
                this.form.recordJson.tempJson
              );
            }
          });
        } else {
          this.form.correlationId = row.id;
          this.form.qualityStandardName = row.qualityStandardName;
          this.form.qualityStandardId = row.qualityStandardId;
          this.form.qualityWorkOrderId = row.qualityWorkOrderId;
          this.form.processRequirementsJson = row.defaultValue;
          this.$nextTick(async () => {
            if (row.procedureJson.tempJson) {
              this.$refs.experimentationProcess1.init(
                row.procedureJson.tempJson
              );
            }
            if (row.recordJson.tempJson) {
              this.$refs.experimentationProcess2.init(row.recordJson.tempJson);
            }
          });
        }

        this.getFactoryarea();
        this.visible = true;
      },
      equipmentOpen(index) {
        this.$refs.productRefs.open([], index);
      },
      chooseCurrent(data) {
        this.$set(
          this.form.experimentEquipmentList[data[0].currentIndex],
          'equipmentId',
          data[0].id
        );
        this.$set(
          this.form.experimentEquipmentList[data[0].currentIndex],
          'equipmentName',
          data[0].name
        );
      },
      handleAdd(key) {
        this.unitListKey = key;
        this.$refs.productRefs.open(this.form[key]);
      },
      remove(index, key) {
        this.form[key].splice(index, 1);
      },
      chooseModal(data) {
        this.form[this.unitListKey] = [...this.form[this.unitListKey], ...data];
      },
      delLaboratoryItemList(index) {
        this.form.experimentEquipmentList.splice(index, 1);
      },
      addExperimentEquipmentList() {
        this.form.experimentEquipmentList.push({});
      },
      async getFactoryarea() {
        const data = await getFactoryarea({
          pageNum: 1,
          size: 1000,
          type: 3
        });
        this.laboratoryList = data.list;
      },
      releaseRulesRefOpen(type) {
        this.releaseRulesType = type;
        this.$refs.releaseRulesRef.open(type);
      },
      releaseRulesSuccess(data) {
        if (this.releaseRulesType == 1) {
          this.$refs.experimentationProcess1.init(data.tempJson.tempJson);
        }

        if (this.releaseRulesType == 2) {
          this.$refs.experimentationProcess2.init(data.tempJson.tempJson);
        }
      },
      inputValue(type, item, index) {
        //样品数
        if (type == 'sampleQuantity') {
          this.isSampleQuantity(item, index);
        }
        //样品合格数、不合格数
        if (type == 'qualifiedQuantity' || type == 'noQualifiedQuantity') {
          this.isQualifiedQuantity(item, index, type);
        }
        //损耗数
        if (type == 'lossNumber' || type == 'lossNumberUnqualified') {
          this.setNumber(item, index, type, '损耗', 'lossNumber');
          if (this.numTotal > this.getSampleQuantityCount) {
            this.$message.error('不能大于当前质检剩余样品数');
            this.$set(this.tableData[index], type, 0);
          }
        }
        //留样数
        if (
          type == 'retainedSampleQuantity' ||
          type == 'retainedSampleUnqualified'
        ) {
          this.setNumber(item, index, type, '留样', 'retainedSampleQuantity');
          if (this.numTotal > this.getSampleQuantityCount) {
            this.$message.error('不能大于当前质检剩余样品数');
            this.$set(this.tableData[index], type, 0);
          }
        }
      },
      save() {
        this.$refs.formRef.validate((valid) => {
          if (!valid) return false;
          let data = JSON.parse(JSON.stringify(this.form));
          let procedureJson = this.$refs.experimentationProcess1.getValue();
          let recordJson = this.$refs.experimentationProcess2.getValue();
          if (procedureJson) {
            data.procedureJson = {
              tempJson: JSON.stringify(procedureJson)
            };
          }
          if (recordJson) {
            data.recordJson = {
              tempJson: JSON.stringify(recordJson)
            };
          }
          let api = data.id ? update : save;
          api(data)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.handleClose();
              this.$emit('done', this.tableData[0]);
            })
            .catch((e) => {
              this.loading = false;
            });
        });
      },
      handleClose() {
        this.visible = false;
      }
    }
  };
</script>

<style lang="scss" scoped></style>
