<template>
  <div style="height: 850px; overflow-y: scroll">
    <el-form ref="form" :model="form" :disabled="disabled" :rules="rules" label-width="100px">
      <el-divider content-position="left">供应商信息</el-divider>
      <el-row>
        <el-col :span="8">
          <el-form-item label="供应商" prop="supplierId">
            <el-select
              v-model="form.supplierId"
              filterable
              placeholder="请选择供应商"
              @change="selectSupplier"
            >
              <el-option
                v-for="item in supplierOptions"
                :key="item.id"
                :label="item.supplierName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系电话" prop="supplier.phone">
            <el-input
              v-model="form.supplier.phone"
              placeholder="请输入联系电话"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供应类型" prop="supplier.supplySpecies">
            <el-select v-model="form.supplier.supplySpecies" disabled>
              <el-option
                v-for="dict in dict.type.app_supply_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row>
        <!-- <el-col :span="12">
          <el-form-item label="所在省市县" prop="supplier.regionArr">
            <el-cascader
              style="width:300px"
              disabled
              :options="regionOptions"
              v-model="form.supplier.regionArr"
            >
            </el-cascader>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="经营地点" prop="supplier.businessPlace">
            <el-input
              v-model="form.supplier.businessPlace"
              placeholder="请输入经营地点"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">检疫证信息</el-divider>

      <el-row>
        <el-col :span="6">
          <el-form-item label="进场时间" prop="entranceTime">
            <el-date-picker
              clearable
              v-model="form.entranceTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择进场时间"
              style="width: 200px"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="畜种" prop="animalType">
            <el-select v-model="form.animalType" placeholder="请选择畜种">
              <el-option
                v-for="item in animalList"
                :key="item.typeValue"
                :label="item.typeName"
                :value="item.typeValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="品种" prop="variety">
            <el-select v-model="form.variety" placeholder="请选择品种">
              <el-option
                v-for="item in pigCategoryOptions"
                :key="item.categoryName"
                :label="item.categoryName"
                :value="item.categoryName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="产地" prop="originPlace">
            <el-select v-model="form.originPlace" >
              <el-option
                v-for="dict in dict.type.app_origin_type"
                :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="pigpens">
            <el-select v-model="form.pigpens" placeholder="请选择待宰圈">
              <el-option
                v-for="item in pigpenOptions"
                :key="item.pigpenName"
                :label="item.pigpenName"
                :value="item.pigpenName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="6">
          <el-form-item label="车牌号码" prop="transportVehicle">
<!--            <el-input-->
<!--              v-model="form.transportVehicle"-->
<!--              placeholder="请输入车牌号码"-->
<!--            />-->
            <el-select v-model="form.transportVehicle">
              <el-option v-for="item in carNumList" :key="item" :value="item" :label="item"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="检疫证文件" prop="animalCertPics">
            <FileUpload
              :disable="form.originPlace === null"
              v-model="form.animalCertPics"
              :certificate="certificate"
              :isTicket="true"
              :fileType="['pdf','png', 'jpg', 'jpeg']"
              :limit="1"
              :fileSize="4"
              @parse="getParesRes"
            />
            <!-- <ImageUpload
              v-model="form.animalCertPics"
              :isTicket="true"
              :limit="1"
              :fileSize="4"
              @parse="getParesRes"
            /> -->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="检疫证号" prop="animalCertNo">
            <el-input
              v-model="form.animalCertNo"
              placeholder="请输入检疫证号"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="重量（kg）" prop="weight">
            <el-input v-model="form.weight" placeholder="请输入重量" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="货主" prop="cargoOwner">
            <el-input v-model="form.cargoOwner" placeholder="请输入货主" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系方式" prop="cargoOwnerPhone">
            <el-input
              v-model="form.cargoOwnerPhone"
              placeholder="请输入货主联系方式"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="主体识别号" prop="companyNo">
            <el-input v-model="form.companyNo" placeholder="请输入主体识别号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="动物种类" prop="animalCategory">
            <el-input
              v-model="form.animalCategory"
              placeholder="请输入动物种类"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="数量" prop="amount">
            <el-input v-model="form.amount" placeholder="请输入数量" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="单位" prop="units">
            <el-select v-model="form.units" placeholder="请选择单位">
              <el-option
                v-for="dict in dict.type.app_animal_units"
                :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="useto">
            <el-input v-model="form.useto" placeholder="请输入用途" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="启运地点" prop="fromPlace">
            <el-input v-model="form.fromPlace" placeholder="请输入启运地点" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="到达地点" prop="toPlace">
            <el-input v-model="form.toPlace" placeholder="请输入到达地点" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="承运人" prop="carrier">
            <el-input v-model="form.carrier" placeholder="请输入承运人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系方式" prop="carrierPhone">
            <el-input
              v-model="form.carrierPhone"
              placeholder="请输入承运人联系方式"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="运载方式" prop="yunzaifangshi">
<!--            <el-input v-model="form.yunzaifangshi" placeholder="请输入运载方式" />-->
            <el-select v-model="form.yunzaifangshi" placeholder="请选择运载方式">
              <el-option :value="'道路'" label="道路"></el-option>
              <el-option :value="'铁路'" label="铁路"></el-option>
              <el-option :value="'水路'" label="水路"></el-option>
              <el-option :value="'航空'" label="航空"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="运载牌照" prop="yunzaipaihao">
            <el-input
              v-model="form.yunzaipaihao"
              placeholder="请输入运载牌照"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="form.originPlace === '3'">
          <el-form-item label="消毒情况" prop="xiaoduqingkuang">
            <el-select v-model="form.xiaoduqingkuang" placeholder="请选择消毒情况">
              <el-option :value="'是'" label="是"></el-option>
              <el-option :value="'否'" label="否"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-row>
            <el-col :span="20">
              <el-form-item label="牲畜耳标号" prop="animalEartags">
                <el-input
                  v-model="form.animalEartags"
                  type="textarea" autosize
                  placeholder="请输入牲畜耳标号(多个耳标号请用 , 分割)"
                />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <div style="margin-top: 5px; margin-left: 5px">
                <el-button type="primary" size="mini" @click="addAnimalEartags">添加连号</el-button>
                <el-button size="mini" @click="resetAnimalEartags">重置</el-button>
              </div>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" :autosize="{ minRows: 2 }"   v-model="form.remark" maxlength="100" show-word-limit placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="footer" v-if="!disabled">
      <el-button type="primary" @click="handleSubmit">保 存</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
    <el-dialog
      title="添加耳标连号"
      :visible.sync="showTag"
      width="30%"
      append-to-body
    >
      <el-form ref="tag" :model="eartagForm" :rules="rules">
        <el-form-item label="请输入起始耳标号(15位)" prop="start">
          <el-input v-model="eartagForm.start" placeholder="请输入起始耳标号" maxlength="15" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="请输入终止尾号(后4位)" prop="end">
          <el-input v-model="eartagForm.end" placeholder="请输入终止尾号" maxlength="4" show-word-limit></el-input>
        </el-form-item>
      </el-form>
       <span slot="footer" class="dialog-footer">
        <el-button @click="showTag = false">取 消</el-button>
        <el-button type="primary" @click="confirmTag">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getEntranceBatch,
  addEntranceBatch,
  updateEntranceBatch,
} from "@/api/app/entranceBatch";
import { getAllSupplier } from "@/api/app/supplier";
import { getAllPigCategory } from "@/api/app/pigCategory";
import { getAllPigpen } from "@/api/app/pigpen";
import FileUpload from "@/components/FileUpload";
import { isExternal } from "@/utils/validate";
import { regionData, regionDataPlus, CodeToText, TextToCode } from 'element-plus-china-area';
import { formatDate } from "@/utils";
import { mapState } from "vuex";

export default {
  name: "EntranceBasicInfo",
  dicts: ["app_origin_type", "app_supply_type","app_animal_units"],
  props: {
    entranceBatchId: {
      type: Number,
      default:null
    },
    disabled: {
      type: Boolean,
      default:false
    }
  },
  data() {
    var validateNumber = (str)=>{
      const regex = /^(?!0+\.00$)(?!.*\.\d{3,})(?:0?\.[1-9]\d?|0?\.0[1-9]|[1-9]\d{0,4}(?:\.\d{1,2})?)$/;
      const num = parseFloat(str);
      return regex.test(str) && num >= 0.01 && num <= 99999.99;
    }
    var valiWeight = (rule, value, callback) => {//包含小数的数字
            if ( value && !validateNumber(value)) {
                callback(new Error('重量范围（0.01~99999.99）'));
            } else {
                callback();
            }
        };
        var valiAmount = (rule, value, callback) => {
          const regex = /^([1-9]\d{0,2})$/;
            if ( !(regex.test(value) && parseInt(value) >= 1 && parseInt(value) <= 999)) {
                callback(new Error('数量范围（1~999）'));
            } else {
                callback();
            }
        };
        var getInvalidNumbers = (array) => {
          const regex = /^\d{15}$/;
          return array.filter(item => !regex.test(item));
        }
    var validateEarTag = (rule, value, callback) => {
      const regex = /^\d{15}$/;
      let arr = value.split(/[，,]/).map(item => item.trim()).filter(item => item !== '');
      if(!arr.every(item => regex.test(item))) {
        callback(new Error(getInvalidNumbers(arr) + '耳标号必须是15位数字'))
      } else {
        callback()
      }
    };
    // 校验start最后4位小于end的自定义验证规则
    const validateStartEnd = (rule, value, callback) => {
      if (!value || !this.form.start) {
        callback();
        return;
      }
      if (value.length !== 4) {
        callback(new Error('必须为4位数字'));
        return;
      }
      if (!/^\d{4}$/.test(value)) {
        callback(new Error('必须为纯数字'));
        return;
      }
      const startStr = this.form.start.toString();
      if (startStr.length !== 15) {
        callback(new Error('起始号码必须为15位'));
        return;
      }
      const startLast4 = startStr.slice(-4);
      const endValue = value;
      if (parseInt(startLast4) > parseInt(endValue)) {
        callback(new Error('结束号码后4位必须大于起始号码后4位'));
        return;
      }

      callback();
    }
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      supplierOptions: [],
      pigCategoryOptions: [],
      pigpenOptions: [],
      //地区
      regionOptions: regionData,
      //entranceBatchId:null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        supplierId: [
          { required: true, message: "供应商不能为空", trigger: "change" },
        ],
        entranceTime: [
          { required: true, message: "进场时间不能为空", trigger: "blur" },
        ],
        variety: [
          { required: true, message: "品种不能为空", trigger: "change" },
        ],
        transportVehicle:[
          { min: 0, max: 10, message: "运输车牌号输入超出最大长度限制（10位）", trigger: "blur" },
        ],
        originPlace: [
          { required: true, message: "产地不能为空", trigger: "change" },
        ],
        weight: [
          { validator: valiWeight, trigger: "blur" },
        ],
        animalCertNo: [
          { required: true, message: "检疫证号不能为空", trigger: "blur" },
          {
              pattern: /^\d+$/,
              message: '检疫证号格式输入错误（数字）',
              trigger: 'blur'
          },
        ],
        cargoOwner: [
          { required: true, message: "货主不能为空", trigger: "blur" },
          { min: 1, max: 30, message: "货主输入超出限制（30位）", trigger: "blur" },
        ],
        companyNo: [
          { required: true, message: "主体识别号不能为空", trigger: "blur" },
          { min:1,max: 18, message: "主体识别号超出限制（18位）", trigger: "blur" },
        ],
        cargoOwnerPhone: [
          { required: true, message: "联系方式不能为空", trigger: "blur" },
          {
              pattern: /^1[3-9]\d{9}$/,
              message: '联系方式格式输入错误',
              trigger: 'blur'
          },
        ],
        animalCategory: [
          { required: true, message: "动物种类不能为空", trigger: "blur" },
          { min: 1, max: 10, message: "动物种类超出限制（10位）", trigger: "blur" },
        ],
        amount: [
          { required: true, message: "数量不能为空", trigger: "blur" },
          { validator: valiAmount, trigger: "blur" },
        ],
        units: [{ required: true, message: "单位不能为空", trigger: "blur" }],
        useto: [
          { required: true, message: "用途不能为空", trigger: "blur" },
          { min: 1, max: 10, message: "用途输入超出限制（10位）", trigger: "blur" },
        ],
        fromPlace: [
          { required: true, message: "启运地点不能为空", trigger: "blur" },
          { min: 1, max: 50, message: "启运地点输入超出最大长度限制（50位）", trigger: "blur" },
        ],
        toPlace: [
          { required: true, message: "到达地点不能为空", trigger: "blur" },
          { min: 1, max: 50, message: "到达地点输入超出最大长度限制（50位）", trigger: "blur" },
        ],
        carrier: [
          { required: true, message: "承运人不能为空", trigger: "blur" },
          { min: 1, max: 30, message: "承运人输入超出最大长度限制（30位）", trigger: "blur" },
        ],
        carrierPhone: [
          {
            required: true,
            message: "联系方式不能为空",
            trigger: "blur",
          },
          {
              pattern: /^1[3-9]\d{9}$/,
              message: '联系方式格式输入错误',
              trigger: 'blur'
          },
        ],
        animalEartags: [
          { required: true, message: "牲畜耳标号不能为空", trigger: "blur" },
          { min: 15, message: "耳标号格式输入错误", trigger: "blur" },
          { validator: validateEarTag, trigger: "blur" }
        ],
        start: [
          { required: true, message: "牲畜耳标号不能为空", trigger: "blur" },
          { min: 15, message: "耳标号格式输入错误", trigger: "blur" },
          { pattern: /^\d{15}$/, message: '必须是15位数字', trigger: 'blur' }
        ],
        end: [
          { required: true, message: "终止尾号不能为空", trigger: "blur" },
          { validator: validateStartEnd, trigger: 'blur' }
        ],
        remark: [
          { min: 0,max: 100, message: "备注输入超出最大长度限制（100位）", trigger: "blur" },
        ],
        yunzaifangshi: [{ required: true, message: "运载方式不能为空", trigger: "blur" },],
        yunzaipaihao: [{ required: true, message: "运载牌照不能为空", trigger: "blur" },],
        xiaoduqingkuang: [{ required: true, message: "消毒情况不能为空", trigger: "change" },],
      },
      // 标记是否正在从详情回填
      isFromDetail: false,
      carNumList: [],
      certificate: 0,
      eartagForm: {
        start: null,
        end: null
      },
      showTag: false
    };
  },
  computed: {
    ...mapState({
      animalList: state => state.user.animalList
    })
  },
  watch:{
    entranceBatchId: {
      handler(newVal, oldVal) {
        this.reset();
      },
    },
    "form.animalType": {
      handler(newVal, oldVal) {
        this.getPigCategoryOptions()
      },
      deep: true,
    },
    "form.originPlace": {
      handler(newVal) {
        if(newVal == 3) {
          this.certificate = 1
        } else {
          this.certificate = 0
        }
      },
      deep: true
    },
    "form.supplierId": {
      handler(newVal) {
        if(newVal) {
          this.selectSupplier(newVal)
        }
      },
    }
  },
  methods: {
    // 重置连号
    resetTag() {
      this.eartagForm = {
        start: null,
        end: null
      }
    },
    // 添加连号
    addAnimalEartags() {
      this.resetTag()
      this.showTag = true
    },
    // 重置连号
    resetAnimalEartags() {
      this.$set(this.form, 'animalEartags', null)
    },
    // 确认连号
    confirmTag() {
      this.$refs.tag.validate((valid) => {
        if(valid) {
          try {
            const start = this.eartagForm.start;
            const end = this.eartagForm.end;
            // 获取前缀（前11位）
            const prefix = start.slice(0, 11);
            // 获取起始后4位
            const startLast4 = start.slice(-4);

            const startNum = parseInt(startLast4);
            const endNum = parseInt(end);

            if (startNum > endNum) {
              this.$message.error('结束号码必须大于起始号码');
              return;
            }

            // 生成号码数组
            const numbers = [];
            for (let i = startNum; i <= endNum; i++) {
              // 将数字转为4位字符串，不足4位前面补0
              const suffix = i.toString().padStart(4, '0');
              numbers.push(prefix + suffix);
            }

            // 用逗号连接
            let str = numbers.join(',');
            let result = null
            if(this.form.animalEartags) {
              let lastDigit = this.form.animalEartags.slice(-1);
              if(lastDigit === ',') {
                console.log(111)
                result = this.form.animalEartags + str
              } else {
                result = this.form.animalEartags +',' + str
              }
            } else {
              result = str
            }
            this.$set(this.form, 'animalEartags', result)
            this.showTag = false
          } catch (error) {
            this.$message.error('生成号码时发生错误：' + error.message);
          }
        }
      })
    },
    //选择供应商
    selectSupplier(value) {
      let supplier = this.supplierOptions.find(
        (item) => item.id === value
      );
      console.log(supplier)
      this.carNumList = supplier.carNum ? supplier.carNum.split(',') : []
      this.$set(this.form,"supplier",supplier);
      this.$set(this.form,"transportVehicle",this.carNumList.length > 0 ? this.carNumList[0] : null);
      // this.form.transportVehicle = this.carNumList.length > 0 ? this.carNumList[0] : null

      // this.$set(this.form,"originPlace",this.form.supplier?this.form.supplier.originPlace:null);
      // this.form.supplier.regionArr = this.form.supplier.region
      //   ? this.form.supplier.region.split(",")
      //   : null;
    },
    async getSupplierOptions() {
      await getAllSupplier().then((response) => {
          let arr = []
          response.data.forEach(item => {
            if(item.inBlacklist === '0') {
              arr.push(item)
            }
          })
          this.supplierOptions = arr;
        });
    },
    getPigCategoryOptions() {
      // 如果是从详情回填，不执行自动设置
      if (this.isFromDetail) return;
      if(!this.form.animalType) return;
      let params = {
        animalType: this.form.animalType
      }
      getAllPigCategory(params).then((res) => {
        this.pigCategoryOptions = res.data;
        if(res.data && res.data.length > 0) {
            this.form.variety = this.pigCategoryOptions[0].categoryName
        } else {
          this.form.variety = null
        }
      });
      let animalName = this.animalList.find(item => item.typeValue === this.form.animalType)?.typeName
      this.form.animalCategory = animalName
    },
    getPigpenOptions() {
      getAllPigpen().then((response) => {
        this.pigpenOptions = response.data;
      });
    },
    // 拿到✅后下一个字符
    getCharAfterCheckmark(str) {
      const checkmarkIndex = str.indexOf('√');
      if (checkmarkIndex !== -1 && checkmarkIndex < str.length - 1) {
        return str.charAt(checkmarkIndex + 1);
      }
      return null; // 如果没有√或√在字符串末尾
    },
    // 拿到✅后下一个字符
    getCharAfterCheckmark2(str) {
      const checkmarkIndex = str.indexOf('√');
      if (checkmarkIndex !== -1 && checkmarkIndex < str.length - 1) {
        return str.charAt(checkmarkIndex + 2);
      }
      return null; // 如果没有√或√在字符串末尾
    },
    //获取解析结果
    getParesRes(val){
      console.log(val)
      this.$set(this.form, "amount",val.amount?val.amount:null);
      this.$set(this.form, "animalCategory",val.animalCategory?val.animalCategory:null);
      this.$set(this.form, "animalCertNo",val.animalCertNo?val.animalCertNo:null);
      this.$set(this.form, "animalEartags",val.animalEartags?val.animalEartags:null);
      this.$set(this.form, "cargoOwner",val.cargoOwner?val.cargoOwner:null);
      this.$set(this.form, "cargoOwnerPhone",val.cargoOwnerPhone?val.cargoOwnerPhone:null);
      this.$set(this.form, "carrier",val.carrier?val.carrier:null);
      this.$set(this.form, "carrierPhone",val.carrierPhone?val.carrierPhone:null);
      this.$set(this.form, "companyNo",val.companyNo?val.companyNo:null);
      this.$set(this.form, "fromPlace",val.fromPlace?val.fromPlace:null);
      this.$set(this.form, "toPlace",val.toPlace?val.toPlace:null);
      this.$set(this.form, "units",val.units?val.units:null);
      this.$set(this.form, "useto",val.useto?val.useto:null);
      this.$set(this.form, "remark",val.remark?val.remark:null);
      // this.$set(this.form, 'yunzaifangshi', val.transport? getCharAfterCheckmark2(val.transport) : null)
      this.$set(this.form, 'yunzaipaihao', val.transportVehicle ? val.transportVehicle : null)
      this.$set(this.form, 'xiaoduqingkuang', val.xiaodu ? this.getCharAfterCheckmark(val.xiaodu) : '是')

    },
    //拼接完整地址
    getFullAddr(url) {
      if (url.indexOf(this.baseUrl) === -1 && !isExternal(url)) {
        url = this.baseUrl + url;
      }
      return url;
    },
    // 取消按钮
    cancel() {
      this.initForm();
      this.$emit('submit', null);
    },
    //
    initForm(){
      this.form = {
        id: this.entranceBatchId,
        supplierId: null,
        originPlace:null,
        supplier: {
          phone: null,
          supplySpecies: null,
          originPlace: null,
          region: null,
          businessPlace: null,
        },
        entranceTime: formatDate(new Date()),
        animalType: this.animalList.length > 0 ? this.animalList[0].typeValue: null,
        variety: null,
        transportVehicle: null,
        weight: null,
        pigpens: null,
        animalCertNo: null,
        animalCertPics: null,
        cargoOwner: null,
        companyNo: null,
        cargoOwnerPhone: null,
        animalCategory: null,
        amount: null,
        units: null,
        useto: null,
        fromPlace: null,
        toPlace: null,
        carrier: null,
        carrierPhone: null,
        animalEartags: null,
        remark: null,
        yunzaifangshi: '道路',
        yunzaipaihao: null,
        xiaoduqingkuang: '是'
      };
      this.resetForm("form");
    },
    // 表单重置
    reset() {
      this.initForm();
      this.form.variety = this.pigCategoryOptions.length > 0 ?  this.pigCategoryOptions[0].categoryName : ''
      if(this.form.id){
        this.getDetail(this.form.id);
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.form.amount = parseInt(this.form.amount);
      if (this.form.id != null) {
        return updateEntranceBatch(this.form).then((response) => {
          this.$modal.msgSuccess("保存成功");
          // 只有为 true 的时候 才能关闭
          this.$emit('submit', null);
          this.reset();
        });
      } else {
       return addEntranceBatch(this.form).then((response) => {
          if(response.data)
          this.$modal.msgSuccess("保存成功");
          this.$emit('submit', response.data.id);
          // this.reset();
        });
      }
    },
    handleSubmit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          console.log("handleSubmit")
          this.checkSupplier();
        }
      });
    },
    checkSupplier() {
      if (this.form.supplier.supplierName != this.form.cargoOwner) {
        let that = this;
        this.$modal
          .confirm("供应商名称和货主名称不一致，是否继续保存？")
          .then(function () {
            return that.checkAnimalSum();
          }).catch(() => {});
      }else{
        return this.checkAnimalSum();
      }
    },
    checkAnimalSum() {
      console.log("checkAnimalSum")
      let animalSum = this.form.animalEartags
            ? this.form.animalEartags.split(",").length
            : 0;
      if (animalSum != this.form.amount?this.form.amount:0) {
        let that = this;
        this.$modal
          .confirm("数量与耳标数量不一致，是否继续保存？")
          .then(function () {
            return that.submitForm();
          }).catch(() => {});
      }else{
        return this.submitForm();
      }
    },
    getDetail(id) {
      getEntranceBatch(id).then((response) => {
        this.isFromDetail = true; // 开始标记
        this.form = response.data;
        this.supplierOptions.forEach(item => {
          if(item.id === this.form.supplierId) {
            this.form.supplier.supplierName = item.supplierName
          }
        })
        // 等下一个事件循环再取消标记
        this.$nextTick(() => {
          this.isFromDetail = false;
        });
      });
    },
  },

  created() {
    this.reset()
    console.log(this.form)
    this.getSupplierOptions();
    // this.getPigCategoryOptions();
    this.getPigpenOptions();
  },
};
</script>
<style scoped>
.footer {
  padding-left: 40px;
}
.form-part {
  /* font-weight: bold; */
  font-size: 18px;
  height: 30px;
  line-height: 30px;
}
</style>
