<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="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择进场时间"
              style="width: 160px"
            >
            </el-date-picker>
          </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-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="检疫证文件" prop="animalCertPics">
            <FileUpload
              v-model="form.animalCertPics"
              :isPDF="true"
              :fileType="['pdf']"
              :limit="1"
              @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="24">
          <el-form-item label="牲畜耳标号" prop="animalEartags">
            <el-input
              v-model="form.animalEartags"
              type="textarea"
              placeholder="请输入牲畜耳标号"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="form.remark" maxlength="50" 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>
  </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';
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
    }
  },
  watch:{
    entranceBatchId: {
      handler(newVal, oldVal) {
        this.reset();
      },
      immediate: true,
    },
  },
  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();
            }
        };

    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{11}$/,
              message: '检疫证号格式输入错误（11位数字）',
              trigger: 'blur'
          },
        ],
        cargoOwner: [
          { required: true, message: "货主不能为空", trigger: "blur" },
          { min: 1, max: 30, message: "货主输入超出限制（30位）", trigger: "blur" },
        ],
        companyNo: [
          { required: true, message: "主体识别号不能为空", trigger: "blur" },
          { min: 18, 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" },
        ],
        remark: [
          { min: 0,max:50, message: "备注输入超出最大长度限制（50位）", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    //选择供应商
    selectSupplier(value) {

      let supplier = this.supplierOptions.find(
        (item) => item.id === value
      );
      this.$set(this.form,"supplier",supplier);
      // 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) => {
          this.supplierOptions = response.data;
        });
    },
    getPigCategoryOptions() {
      getAllPigCategory().then((response) => {
        this.pigCategoryOptions = response.data;
      });
    },
    getPigpenOptions() {
      getAllPigpen().then((response) => {
        this.pigpenOptions = response.data;
      });
    },
    //获取解析结果
    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);
    },
    //拼接完整地址
    getFullAddr(url) {
      if (url.indexOf(this.baseUrl) === -1 && !isExternal(url)) {
        url = this.baseUrl + url;
      }
      return url;
    },
    // 取消按钮
    cancel() {
      this.$emit('submit');
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: this.entranceBatchId,
        supplierId: null,
        originPlace:null,
        supplier: {
          phone: null,
          supplySpecies: null,
          originPlace: null,
          region: null,
          businessPlace: null,
        },
        entranceTime: new Date(),
        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,
      };
      this.resetForm("form");
      if(this.form.id){
        this.getDetail(this.form.id);
      }
    },
    /** 提交按钮 */
    submitForm() {
      console.log("submitForm")
      this.form.amount = parseInt(this.form.amount);
      if (this.form.id != null) {
        return updateEntranceBatch(this.form).then((response) => {
          this.$modal.msgSuccess("修改成功");
          this.$emit('submit');
          this.reset();
        });
      } else {
       return addEntranceBatch(this.form).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.$emit('submit');
          this.reset();
        });
      }
    },
    handleSubmit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          console.log("handleSubmit")
          this.checkSupplier();
        }
      });
    },
    checkSupplier() {
      console.log("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;
      console.log(this.form)
      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) => {
        console.log(456)
          this.form = response.data;
          // this.form.supplier.regionArr = this.form.supplier.region
          // ? this.form.supplier.region.split(",")
          // : null;


      });
    },
  },

  created() {
    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>
