<template>
  <div style="height: 700px; overflow-y: scroll; overflow-x: hidden">
    <el-form
      ref="form"
      :disabled="disabled"
      :model="form"
      :rules="rules"
      label-position="top"
      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 :gutter="20">
        <el-col :span="4">
          <el-form-item label="途亡头数" prop="roadDealAmount">
            <el-input
              type="number"
              v-model.number="form.roadDealAmount"
              min="0"
              placeholder="请输入途亡头数"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="病死头数" prop="illnessDeadAmount">
            <el-input
              type="number"
              v-model.number="form.illnessDeadAmount"
              min="0"
              placeholder="请输入病死头数"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="病害头数" prop="illnessDiseaseAmount">
            <el-input
              type="number"
              v-model.number="form.illnessDiseaseAmount"
              min="0"
              placeholder="请输入病害头数"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="急宰头数" prop="snapKillAmount">
            <el-input
              type="number"
              v-model.number="form.snapKillAmount"
              min="0"
              placeholder="请输入急宰头数"
            />
          </el-form-item>
        </el-col>
<!--        <el-col :span="4">-->
<!--          <el-form-item label="处理原因" prop="dealReason">-->
<!--            <el-select v-model="form.dealReason">-->
<!--              <el-option v-for="item in disposalOptions" :key="item.id" :value="item.dealReason" :label="item.dealReason"></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="4">
          <el-form-item label="处理方式" prop="dealWay">
            <el-input
              disabled
              v-model.number="form.dealWay"
              :placeholder="disabled ? '' :'选择处理原因自动填充'"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <template v-if="treatmentTotal> 0">
      <el-divider content-position="left">无害化处理生猪详情</el-divider>
      <el-row class="mb20" :gutter="20">
        <el-col :span="6">
          <div>耳标号</div>
        </el-col>
        <el-col :span="6">
          <div>重量(kg)</div>
        </el-col>
      </el-row>
      <el-row
        v-for="(itemRow, i) in form.illnessPigsDetailArr"
        :key="i"
        :gutter="20"
      >
        <el-col :span="6">
          <el-form-item
            label=""
            label-width="0"
            :prop="'illnessPigsDetailArr.' + i + '.eartagNo'"
            :rules="rule1"
          >
            <el-select v-model="itemRow.eartagNo" @change="(value) => changeEarTag(value, i)">
              <el-option v-for="item in earTagList" :disabled="item.disable" :key="item.no" :value="item.no" :label="item.no"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label=""
            label-width="0"
            :prop="'illnessPigsDetailArr.' + i + '.weight'"
            :rules="rule2"
          >
            <el-input v-model="itemRow.weight" placeholder="请输入重量" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-button
            class="item-add"
            type="primary"
            v-if="i == form.illnessPigsDetailArr.length - 1 && treatmentTotal > form.illnessPigsDetailArr.length"
            @click="addItem(i)"
            ><i class="el-icon-plus"></i
          ></el-button>
          <el-button
            class="item-del"
            type="danger"
            v-if="i > 0 || form.illnessPigsDetailArr.length > 1"
            @click="removeItem(i)"
            ><i class="el-icon-minus"></i
          ></el-button>
        </el-col>
      </el-row>
      </template>
<!--      <el-divider content-position="left">产品无害化处理汇总</el-divider>-->
<!--      <el-row class="mb20" :gutter="20">-->
<!--        <el-col :span="12">-->
<!--          <el-form-item label="不合格产品重量(kg)" prop="unqualifiedWeight">-->
<!--            <el-input-->
<!--              v-model="form.unqualifiedWeight"-->
<!--              placeholder="请输入不合格产品重量"-->
<!--            />-->
<!--          </el-form-item>-->
<!--        </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 {
  getHarmlessTreatment,
  addHarmlessTreatment,
  updateHarmlessTreatment,
  getHarmlessEarTag
} from "@/api/app/harmlessTreatment";
import {
  getEntranceBatch
} from "@/api/app/entranceBatch";

import { getAllDisposal } from "@/api/app/deadDisposal";
export default {
  name: "harmlessTreatment",
  props: {
    entranceBatchId: {
      type: Number,
      default: null,
    },
    disabled: {
      type: Boolean,
      default:false
    },
    // variety: {
    //   type: String,
    //   default: null,
    // }
  },
  watch: {
    entranceBatchId: {
      handler(newVal, oldVal) {
        this.reset();
      },
      immediate: true,
    },
    "form.roadDealAmount": {
      handler(newVal) {
        if(newVal > 0 || this.form.illnessDeadAmount > 0 || this.form.illnessDiseaseAmount > 0) {

          this.form.dealWay = '无害化处理'
        } else {
          this.form.dealWay = ''
        }
      },
      deep: true
    },
    "form.illnessDeadAmount": {
      handler(newVal) {
        if(newVal > 0 || this.form.roadDealAmount > 0 || this.form.illnessDiseaseAmount > 0) {
          this.form.dealWay = '无害化处理'
        } else {
          this.form.dealWay = ''
        }
      },
      deep: true
    },
    "form.illnessDiseaseAmount": {
      handler(newVal ) {
        if(newVal > 0 || this.form.roadDealAmount > 0 || this.form.illnessDeadAmount > 0) {
          this.form.dealWay = '无害化处理'
        } else {
          this.form.dealWay = ''
        }
      },
      deep: true
    },
    // "form.dealReason": {
    //   handler(newVal) {
    //     if(newVal) {
    //       this.disposalOptions.forEach(item => {
    //         if(item.dealReason === newVal) {
    //           this.form.dealWay = item.dealWay
    //         }
    //       })
    //     }
    //   },
    //   deep: true
    // },
  },
  computed:{
    treatmentTotal(){
      let total = this.form.illnessDeadAmount + this.form.roadDealAmount + this.form.illnessDiseaseAmount;
      let num = total - this.form.illnessPigsDetailArr.length;
      if(num<0){
        this.form.illnessPigsDetailArr.splice(num)
      }
      if(total >0 && this.form.illnessPigsDetailArr == 0){
         this.form.illnessPigsDetailArr.push( {
            eartagNo: null,
            weight: null,
          })
      }
      console.log(total,num)
      return total
    }
  },
  data() {
    var validateNumber1 = (str) => {
      const regex =
        /^(?!.*\.\d{3,})(?:0|0?\.\d{1,2}|[1-9]\d{0,4}(?:\.\d{1,2})?)$/;
      const num = parseFloat(str);
      return regex.test(str) && num >= 0 && num <= 99999.99;
    };
    var valiWeight1 = (rule, value, callback) => {
      //包含小数的数字
      var msg = "不合格产品重量范围（0~99999.99）";
      if (value && !validateNumber1(value)) {
        callback(new Error(msg));
      } else {
        callback();
      }
    };
    var validateNumber = (str) => {
      const regex =
        /^(?!0+\.00$)(?!.*\.\d{3,})(?:0?\.[1-9]\d?|0?\.0[1-9]|[1-9]\d{0,2}(?:\.\d{1,2})?)$/;
      const num = parseFloat(str);
      return regex.test(str) && num >= 0.01 && num <= 999.99;
    };
    var valiWeight = (rule, value, callback) => {
      //包含小数的数字
      var msg = "重量范围（0.01~999.99）";
      if (value && !validateNumber(value)) {
        callback(new Error(msg));
      } else {
        callback();
      }
    };
    var valiAmount = (rule, value, callback) => {
      var msg = "输入超出设定范围限制（0~999）";
      if (rule.field == "illnessDeadAmount") {
        msg = "病死头数" + msg;
      } else if (rule.field == "illnessDiseaseAmount") {
        msg = "病害头数" + msg;
      } else if (rule.field == "snapKillAmount") {
        msg = "急宰头数" + msg;
      }
      const regex = /^([0-9]\d{0,2})$/;
      if (
        value &&
        !(regex.test(value) && parseInt(value) >= 0 && parseInt(value) <= 999)
      ) {
        callback(new Error(msg));
      } else {
        callback();
      }
    };
    return {
      disposalOptions: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        illnessDeadAmount: [{ validator: valiAmount, trigger: "blur" }],
        illnessDiseaseAmount: [{ validator: valiAmount, trigger: "blur" }],
        snapKillAmount: [{ validator: valiAmount, trigger: "blur" }],
        // unqualifiedWeight: [{ validator: valiWeight1, trigger: "blur" }],
      },
      rule1: [
        {
          pattern: /^\d{15}$/,
          message: '耳标号格式输入错误（15位数字）',
          trigger: 'blur',
        },
      ],
      rule2: [
      { validator: valiWeight, trigger: "blur" }
      ],
      earTagList: []
    };
  },
  methods: {
    addItem(i) {
      if(this.form.illnessPigsDetailArr[i].eartagNo) {
        this.earTagList.forEach(item => {
          if(item.no === this.form.illnessPigsDetailArr[i].eartagNo) {
            item.disable = true
          }
        })
        this.form.illnessPigsDetailArr.push({
          eartagNo: null,
          weight: null,
        });
      } else {
        this.$alert('请先选择耳标号再继续添加', '警告', {
          confirmButtonText: '确定',
        })
        return
      }
    },
    removeItem(i) {
      let no = this.form.illnessPigsDetailArr[i].eartagNo;
      if(no) {
        this.earTagList.forEach(item => {
          if(item.no === no) {
            item.disable = false
          }
        })
      }
      this.form.illnessPigsDetailArr.splice(i, 1);
    },
    getDisposal() {
      getAllDisposal().then((response) => {
        this.disposalOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.initForm();
      this.$emit("submit", null);
    },
    initForm(){
      this.form = {
        id: null,
        entranceBatchId: this.entranceBatchId,
        illnessDeadAmount: 0,
        illnessDiseaseAmount: 0,
        snapKillAmount: null,
        unqualifiedWeight: null,
        illnessPigsDetail: null,
        roadDealAmount: 0,
        illnessPigsDetailArr: [

        ],
        dealWay: null,
        dealReason: null
      };
      this.resetForm("form");
    },
    // 表单重置
    async reset() {
      this.initForm()
      if (this.form.entranceBatchId) {
        await this.getEarTag()
        await this.getDetail(this.form.entranceBatchId);
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.form.illnessPigsDetail = JSON.stringify(
        this.form.illnessPigsDetailArr
      );
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateHarmlessTreatment(this.form).then((response) => {
              this.$modal.msgSuccess("保存成功");
              this.$emit("submit", null);
            });
          } else {
            addHarmlessTreatment(this.form).then((response) => {
              this.$modal.msgSuccess("保存成功");
              this.$emit("submit", null);
            });
          }
        }
      });
    },
    async getDetail(id) {
      await getHarmlessTreatment(id).then((response) => {
        if (response.data) {
          this.form = response.data;
          let illnessPigsDetailArr = JSON.parse(this.form.illnessPigsDetail);
          this.$set(this.form, "illnessPigsDetailArr", illnessPigsDetailArr);

        }
      });
    },
    async getEarTag() {
      let params = {
        id: this.entranceBatchId,
        variety: this.variety
      }
      await getHarmlessEarTag(params).then(res => {
        if(res.data) {
          if(res.data.length > 0) {
            this.earTagList = res.data.flatMap(obj => Object.keys(obj).map(key => ({no: parseInt(key), value: obj[key], disable: false})))
          } else {
            this.earTagList = []
          }
        } else {
            this.earTagList = []
        }
        
      })
    },
    changeEarTag(e,i) {
      this.earTagList.forEach(item => {
        if(item.no === e) {
          this.form.illnessPigsDetailArr[i].weight = item.value
        }
      })
    }
  },
  created() {
    this.reset();
    this.getDisposal();
  },
};
</script>
<style scoped>
.footer {
  padding-left: 40px;
}
.form-part {
  /* font-weight: bold; */
  font-size: 18px;
  height: 30px;
  line-height: 30px;
}
</style>
