<template>
  <div style="height: 700px; overflow-y: scroll">
    <el-form ref="form" :model="form" :disabled="disabled" :rules="rules" label-width="80px">
      <el-divider content-position="left">生猪健康检查信息</el-divider>
      <!-- <el-form-item label="入场批次ID" prop="entranceBatchId">
        <el-input
          v-model="queryParams.entranceBatchId"
          placeholder="请输入入场批次ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-row>
        <el-col :span="6">
          <el-form-item label="精神" prop="spirit">
            <el-select v-model="form.spirit">
              <el-option
                v-for="dict in dict.type.app_inspection_res"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="外貌" prop="appearance">
            <el-select v-model="form.appearance">
              <el-option
                v-for="dict in dict.type.app_inspection_res"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="呼吸" prop="breathe">
            <el-select v-model="form.breathe">
              <el-option
                v-for="dict in dict.type.app_inspection_res"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="排泄物" prop="metabolite">
            <el-select v-model="form.metabolite">
              <el-option
                v-for="dict in dict.type.app_inspection_res"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="检验人" prop="staffId">
            <el-select v-model="form.staffId">
              <el-option v-for="item in staffList" :key="item.id" :value="item.id" :label="item.realname"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="其他" prop="otherRemark">
            <el-input
              v-model="form.otherRemark"
              :autosize="{ minRows: 2, maxRows: 6 }"
              :placeholder="disabled ? '' : '请输入其他'"
              maxlength="50" show-word-limit
              type="textarea" autosize
            />
          </el-form-item>
        </el-col>
      </el-row>
<!--      <el-divider content-position="left">生猪检验检疫信息</el-divider>-->
<!--      <el-row class="mb20">-->
<!--        <el-col :span="5">-->
<!--          <div>-->
<!--            &lt;!&ndash; <span style="color: #f00">* </span> &ndash;&gt;-->
<!--            检验检疫项目</div>-->
<!--        </el-col>-->
<!--        <el-col :span="5">-->
<!--          <div>-->
<!--            &lt;!&ndash; <span style="color: #f00">* </span> &ndash;&gt;-->
<!--            检验检疫结果</div>-->
<!--        </el-col>-->
<!--        <el-col :span="5">-->
<!--          <div>查验人</div>-->
<!--        </el-col>-->
<!--        <el-col :span="5">-->
<!--          <div>处理情况</div>-->
<!--        </el-col>-->
<!--      </el-row>-->
<!--      &lt;!&ndash; <div class="mt10 mb10">-->
<!--        <el-button-->
<!--            type="primary"-->
<!--            v-if="form.inspectionDetailArr.length==0"-->
<!--            @click="addItem"-->
<!--            >录入检疫信息</el-button>-->
<!--        </div> &ndash;&gt;-->
<!--      <el-row v-for="(itemRow, i) in form.inspectionDetailArr" :key="i">-->
<!--        <el-col :span="5">-->
<!--          <el-form-item-->
<!--            label=""-->
<!--            label-width="0"-->
<!--            :prop="'inspectionDetailArr.' + i + '.itemName'"-->
<!--          >-->
<!--            <el-select-->
<!--              v-model="itemRow.itemName"-->
<!--              filterable-->
<!--              clearable-->
<!--              placeholder="请选择检验检疫项目"-->
<!--              @change="selectItem"-->
<!--              style="width: 180px"-->
<!--            >-->
<!--              <el-option-->
<!--                v-for="(item,i) in inspectionItemOptions"-->
<!--                :key="i"-->
<!--                :label="item.itemName"-->
<!--                :value="item.itemName"-->
<!--              ></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--        <el-col :span="5">-->
<!--          <el-form-item-->
<!--            label=""-->
<!--            label-width="0"-->
<!--            :prop="'inspectionDetailArr.' + i + '.result'"-->
<!--            :rules="rules1"-->
<!--          >-->
<!--            <el-select-->
<!--              v-model="itemRow.result"-->
<!--              filterable-->
<!--              placeholder="请选择检验检疫结果"-->
<!--              style="width: 180px"-->
<!--            >-->
<!--              <el-option-->
<!--                v-for="(item,i) in getAtResultList(itemRow.itemName)"-->
<!--                :key="i"-->
<!--                :label="item.name"-->
<!--                :value="item.name"-->
<!--              ></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--        <el-col :span="5">-->
<!--          <el-form-item-->
<!--            label=""-->
<!--            label-width="0"-->
<!--            :prop="'inspectionDetailArr.' + i + '.checkName'"-->
<!--            :rules="{-->
<!--              min: 0,-->
<!--              max:10,-->
<!--              message: '查验人超出限制（10位）',-->
<!--              trigger: 'blur',-->
<!--            }"-->
<!--          >-->
<!--            <el-input-->
<!--              v-model="itemRow.checkName"-->
<!--              placeholder="请输入查验人"-->
<!--              style="width: 180px"-->
<!--            />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--        <el-col :span="5">-->
<!--          <el-form-item-->
<!--            label=""-->
<!--            label-width="0"-->
<!--            :prop="'inspectionDetailArr.' + i + '.dealWay'"-->
<!--            :rules="{-->
<!--              min: 0,-->
<!--              max:20,-->
<!--              message: '处理方式超出限制（20位）',-->
<!--              trigger: 'blur',-->
<!--            }"-->
<!--          >-->
<!--            <el-input-->
<!--              v-model="itemRow.dealWay"-->
<!--              placeholder="请输入处理方式"-->
<!--              style="width: 180px"-->
<!--            />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--        <el-col :span="4">-->
<!--          <el-button-->
<!--            class="item-add"-->
<!--            type="primary"-->
<!--            v-if="i == form.inspectionDetailArr.length - 1"-->
<!--            @click="addItem"-->
<!--            ><i class="el-icon-plus"></i-->
<!--          ></el-button>-->
<!--          <el-button-->
<!--            class="item-del"-->
<!--            type="danger"-->
<!--            v-if="i > 0 || form.inspectionDetailArr.length > 1"-->
<!--            @click="removeItem(i)"-->
<!--            ><i class="el-icon-minus"></i-->
<!--          ></el-button>-->
<!--        </el-col>-->
<!--      </el-row>-->
    </el-form>
    <div class="footer" v-if="!disabled">
      <el-button type="primary" @click="submitForm">保 存</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>
<script>
import {
  getEntranceInspection,
  addEntranceInspection,
  updateEntranceInspection,
} from "@/api/app/entranceInspection";

import { getInspectionList } from "@/api/app/inspection";
import { getDrugList } from "@/api/app/drug";
import { listAllStaff } from "@/api/app/staff";

export default {
  name: "EntranceInspection",
  dicts: ["app_inspection_res"],
  props: {
    entranceBatchId: {
      type: Number,
      default:null
    },
    disabled: {
      type: Boolean,
      default:false
    }
  },
  watch:{
    entranceBatchId: {
      handler(newVal, oldVal) {
        this.reset();
      },
      immediate: true,
    },
    "form.staffId": {
      handler(newVal) {
        this.staffList.forEach(item => {
          if(item.id === newVal) {
            this.form.staffName = item.realname
          }
        })
      },
      deep: true
    }
  },
  data() {
    var valiRes = (rule, value, callback) => {//包含小数的数字
            let index = rule.field.split(".")[1];
            if(index!=undefined && index!=null){
               if(this.form.inspectionDetailArr[index].itemName && !value){
                  callback(new Error('请选择对应检验检疫结果'));
               }else{
                callback();
               }
            }else{
              callback();
            }
    };
    return {
      inspectionItemOptions: [],
      inspectionResOptions: [],
      //entranceBatchId:null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      rules1:{ validator: valiRes, trigger: 'change' },
      staffList: [],
      staffName: null,
      staffId: null
    };
  },
  methods: {
    getStaff() {
      let params = {
        postId: 41
      }
      listAllStaff(params).then(res => {
        this.staffList = res.data
        if(res.data.length > 0) {
          this.staffName = res.data[0].realname
          this.staffId = res.data[0].id
        }
      })
    },
    addItem() {
      this.form.inspectionDetailArr.push({
        itemName: null,
        result: null,
        dealWay: null,
        checkName: null,
      });
    },
    removeItem(i) {
      this.form.inspectionDetailArr.splice(i, 1);
    },
    selectItem(value) {
      // let select = this.inspectionItemOptions.find(
      //   (item) => item.itemName === value
      // );
      // this.inspectionResOptions = select.result.length > 0 ? select.result : []
    },
    async getInspectionItem() {
      await getDrugList({}).then((response) => {
        response.data.forEach(item => {
          item.itemName = item.drugName
          item.result = item.result
            ? JSON.parse(item.result)
            : [];
        })
        this.inspectionItemOptions = response.data;
      });
    },
    getAtResultList(name) {
      let arr = []
      this.inspectionItemOptions.forEach(item => {
        if(item.itemName === name) {
          arr = item.result
        }
      })
      return arr
    },
    // 取消按钮
    cancel() {
      this.initForm();
      this.$emit('submit', null);
    },
    initForm(){
      this.form = {
        id: null,
        entranceBatchId: this.entranceBatchId,
        spirit: 'N',
        appearance: 'N',
        breathe: 'N',
        metabolite: 'N',
        otherRemark: null,
        inspectionDetail: null,
        inspectionDetailArr: [],
        staffName: null,
        staffId: null
      };
      this.resetForm("form");
    },
    // 表单重置
    async reset() {
      this.initForm();
      if(this.form.entranceBatchId){
         await this.getStaff()
         await this.getInspectionItem();
         await this.getDetail(this.form.entranceBatchId);
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.form.inspectionDetail = JSON.stringify(this.form.inspectionDetailArr);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateEntranceInspection(this.form).then((response) => {
              this.$modal.msgSuccess("保存成功");
              this.$emit('submit', null);
            });
          } else {
            addEntranceInspection(this.form).then((response) => {
              this.$modal.msgSuccess("保存成功");
              this.$emit('submit', this.entranceBatchId);
            });
          }
        }
      });
    },
    async getDetail(id) {
      await getEntranceInspection(id).then((response) => {
        if(response.data){
          this.form = response.data;
          if(response.data.staffId === null) {
            this.form.staffId = this.staffId;
            this.form.staffName = this.staffName;
          }
          let inspectionDetailArr = [];
          if(this.form.inspectionDetail == null){
            let arr = []
            this.inspectionItemOptions.forEach(item => {
              arr.push({  itemName: item.itemName,
                result: item.result[0].name,
                dealWay: null,
                checkName: null, })
            })
            inspectionDetailArr = arr
          }else{
            inspectionDetailArr = JSON.parse(this.form.inspectionDetail);
          }
          this.$set(this.form, "inspectionDetailArr",inspectionDetailArr );
        } else {
          let arr = []
          this.inspectionItemOptions.forEach(item => {
            arr.push({  itemName: item.itemName,
              result: item.result[0].name,
              dealWay: null,
              checkName: null, })
          })
          this.$set(this.form, "inspectionDetailArr", arr );
        }
      });
    },
  },
  created() {
  },
};
</script>
<style scoped>
.footer {
  padding-left: 40px;
}
.form-part {
  /* font-weight: bold; */
  font-size: 18px;
  height: 30px;
  line-height: 30px;
}
</style>
