<template>
  <el-dialog
    title="农户管理"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose"
    width="700px"
  >
    <el-form
      ref="baseForm"
      class="base-form"
      label-position="right"
      label-width="95px"
      :model="baseForm"
      :rules="rules"
      size="small"
    >
      <el-row>
        <el-col :span="24" style="background:#F5F7FA;padding-top:20px;margin-bottom:20px;">
          <el-form-item label="所属区域" prop="areaId">
            <el-row>
              <el-col :span="24" style="padding-right:5%">
                <select-tree 
                  :placeholder="'请选择区域'" 
                  style="width:100%"
                  :treeData="treeData"
                  @handlerClick="handlerClick"
                  :checkVal="cusareaName"
                ></select-tree>
              </el-col>
            </el-row>
          </el-form-item>
          <el-col>
            <el-row class="area">
              <el-col>
                  <label>总面积：</label>{{ areaAll }}亩
              </el-col>
              <el-col>
                <label>总水权：</label>{{ waterRightAll }}m³
              </el-col>
              <el-col>
                  <label>亩产水权：</label>{{ yieldPer }}亩/m³
              </el-col>
              <el-col>
                  <label>剩余水权：</label>{{ residualWaterRight }}m³
              </el-col>
            </el-row>
          </el-col>
        </el-col>
        <el-col :span="24">
          <el-row>
            <el-col :span="12">
              <el-form-item label="农户姓名" prop="farmerName">
                <el-row>
                  <el-col>
                    <el-input
                      v-model="baseForm.farmerName"
                      filterable
                      style="width: 100%"
                      placeholder="请输入农户姓名"
                    >
                    </el-input>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证号" prop="farmerIdcard">
                <el-row>
                  <el-col>
                    <el-input
                      v-model="baseForm.farmerIdcard"
                      filterable
                      style="width: 100%"
                      maxlength="18"
                      placeholder="请输入身份证号"
                    >
                    </el-input>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="24">
          <el-row>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="farmerPhone">
                <el-row>
                  <el-col>
                    <el-input
                      v-model="baseForm.farmerPhone"
                      type="number"
                      filterable
                      style="width: 100%"
                      maxlength="11"
                      placeholder="请输入联系电话"
                    >
                    </el-input>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
              <el-col :span="12">
                <el-form-item label="土地面积" prop="farmerAreasize">
                  <el-row>
                    <el-col style="position:relative">
                      <el-input
                        v-model="baseForm.farmerAreasize"
                        type="number"
                        filterable
                        style="width: 90%"
                        placeholder="请输入土地面积"
                      >
                      </el-input>
                      <span style="position:absolute;margin-left:10px">亩</span>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
          </el-row>
        </el-col>
        <el-col :span="24">
          <el-row>
            <el-col :span="12">
              <el-form-item label="水权" prop="farmerWramount">
                <el-row>
                  <el-col>
                    <el-input
                      v-model="baseForm.farmerWramount"
                      type="number"
                      filterable
                      style="width: 100%"
                      placeholder="请输入水权"
                    >
                    </el-input>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
    <div style="text-align: right">
      <el-button type="info" plain @click="resetForm('baseForm')"
        >取消</el-button
      >
      <el-button
        type="primary"
        style="margin-left:16px;"
        @click="submitForm('baseForm')"
        :disabled="dialogSubmitLoading"
        :loading="dialogSubmitLoading"
        >确定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { Message } from 'element-ui'
import { isValidIDCard, checkPhone } from '@/utils/index.js'
import SelectTree from '@/components/SelectTree';
import { addFarmer,editFarmer, getAreaInfo } from '@/api/farmer/list.js'

export default {
  name: 'addedFarmers',
  components:{
    SelectTree
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    treeData: {
      type: Array,
      default: () => []
    },
    editFarmerData: {
      type: Object,
      default: () => {}
    },
    isEdit:{
      type: Boolean,
      default: false
    },
    currentClickId: {
      type: Number | String
    }
  },
  data() {
    return {
      treeDataArr: [],
      dialogSubmitLoading: false,
      dialogVisible: false,
      baseForm: { ...this.editFarmerData },
      hasFetched: false,
      cusareaName: '',
      areaAll: '0',
      waterRightAll: '0',
      yieldPer: '0',
      residualWaterRight: '0',
      areasizeResidue: '0',
      currentItem: {},
      rules: {
        areaId: [
          { required: true, message: '请选择所属区域', trigger: 'blur' }
        ],
        farmerName: [
          { required: true, message: '请输入农户姓名', trigger: 'blur' }
        ],
        farmerIdcard: [
          {
            required: true, validator: (rule, value, callback) => {
              if (!value) callback(new Error('请输入农户身份证号'));
              const vaild = isValidIDCard(value)
              if (vaild) {
                callback()
              } else { 
                callback(new Error('请正确输入农户身份证号'));
              }
            
          }, trigger: 'blur' }
        ],
        farmerPhone: [
          { required: true, validator: (rule, value, callback) => {
              if (!value) callback(new Error('请输入联系电话'));
              const vaild = checkPhone(value)
              if (vaild) {
                callback()
              } else {
                callback(new Error('请正确输入联系电话'));
              }

            },  trigger: 'blur' }
        ],
        farmerAreasize: [
          {
            required: true, validator: (rule, value, callback) => {
              if (!value) { callback(new Error('请输入土地面积')); return }
              if (+value < 0) {  callback(new Error('土地面积不能为负数')); return }
              if (isNaN(value)) { callback(new Error('请正确输入您的土地面积')); return }
              if (this.isEdit) {
                if (+value > (+this.areasizeResidue) + (+this.editFarmerData.farmerAreasize)) {
                  callback(new Error('输入的土地面积不能大于总面积'))
                  return
                } else {
                  callback()
                }
              } else {
                if (+value > +this.areasizeResidue) {
                  callback(new Error('输入的水权不能大于剩余面积'))
                  return
                } else {
                  callback()
                }
              }
            }, trigger: 'blur' }
        ],
        farmerWramount: [
          {
            required: true, validator: (rule, value, callback) => {
              if (value == 0) { callback(new Error('请输入水权')); return }
              if (+value < 0) { callback(new Error('水权不能为负数')); return }
              if (isNaN(value)) { callback(new Error('请正确输入您的水权')); return }
              if (this.isEdit) {
                if (+value > (+this.residualWaterRight) + (+this.editFarmerData.farmerWramount)) {
                  callback(new Error('输入的水权不能大于剩余水权'))
                  return
                } else { 
                  callback()
                }
              } else { 
                if (+value > +this.residualWaterRight) {
                  callback(new Error('输入的水权不能大于剩余水权'))
                  return
                } else { 
                  callback()
                }
              }
            }, trigger: 'blur' }
        ]
      }
    };
  },
  watch: {
    visible(val) {
      if (val !== this.dialogVisible) {
        this.dialogVisible = val;
      }
      if (!val) {
        this.$refs.baseForm?.clearValidate()
        this.baseForm = { areaId:'' }
        this.$emit('closeHandler')
        this.cusareaName = ''
        this.clearItem()
      }
    },
    'baseForm.farmerAreasize': {
      handler(val) {
        if (this.yieldPer > 0) { 
          this.baseForm.farmerWramount = Number(this.yieldPer) * val
        }
      },
      deep: true,
      immediate: true
    },
    editFarmerData: {
      handler(val) {
        if (this.isEdit && val?.areaId) { 
          this.baseForm = { ...val }
          this.handlerClick(val)
        } else {
          this.baseForm = { areaId: '' }
          this.cusareaName =  ''
        }
      },
      deep: true
    },
    treeData: {
      handler(val) {
        this.treeDataArr = val ?? [];
      },
      deep: true,
      immediate: true
    },
    'baseForm.areaId': {
      handler(val) {
        val && this.$refs.baseForm?.clearValidate('areaId')
      },
      deep: true
    }
  },
  methods: {
    setItem(value) { 
      this.areaAll = value?.waterrightAreasize || '0'
      this.areaAll = (+this.areaAll).toFixed(2)
      this.waterRightAll = value?.waterrightAmount || '0'
      this.waterRightAll = (+this.waterRightAll).toFixed(2)
      this.yieldPer = value ? value?.waterrightAmount == 0 ? 0 : (value?.waterrightAreasize) / (value?.waterrightAmount) : 0
      this.yieldPer = (+this.yieldPer).toFixed(2)
      this.residualWaterRight = value?.amountResidue ?? 0
      this.areasizeResidue = value?.areasizeResidue ?? 0
      this.residualWaterRight = (+this.residualWaterRight).toFixed(2)
    },
    clearItem() { 
      this.areaAll = 0.00
      this.waterRightAll = 0.00
      this.yieldPer = 0.00
      this.residualWaterRight = 0.00
    },
    findItemByAreaId(areaId,list) {
      return list.find(item => item.areaId === areaId)
    },
    async handlerClick(item) {
      const res = await getAreaInfo({
        waterrightYear: new Date().getFullYear(),
        areaId: item.areaId
      })
      this.currentItem = item
      const value = res?.data
      this.cusareaName = item?.cusareaName
      const areaId = item?.areaId || ''
      this.baseForm.areaId = areaId
      this.$set(this.baseForm,'areaId', areaId)
      this.setItem(value)
    },
    resetForm() {
      this.dialogVisible = false;
      this.cusareaName = ''
    },
    async handlerAddFarmer() {
      if (this.currentItem?.children?.length > 0) {
        Message.warning('请选择最小行政区块')
        return
       }
      if(!this.isEdit){
        const res = await addFarmer(this.baseForm)
        if(res?.code === "000000") {
          this.handleClose()
          this.cusareaName = ''
          this.$emit('refresh')
        }
      }else{
        const res = await editFarmer(this.baseForm)
        if(res?.code === "000000") {
          this.handleClose()
          this.cusareaName = ''
          this.$emit('refresh')
        }
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        valid && this.handlerAddFarmer()
      })
    },
    handleClose() {
      this.$emit('update:visible', false);
      this.resetForm('baseForm');
    },
  }
};
</script>

<style lang="scss" scoped>
.input-number {
  width: 100%;
}
.el-col-5{
  width:auto;
  min-width: 20%;
}
.area{
  margin:0 0 20px 20px;
  display: flex;
  .el-col{
    min-width: 25%;
  }
  label{
    color:#999;
    font-weight: 400;
    font-size: 14px;
  }
}
.base-form {
  max-height: 70vh;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 0 20px;
}
.history{
  text-align: right;
  line-height: 32px;
  span{
    color:rgb(20, 164, 120);
    cursor: pointer;
  }
}
</style>
<style lang="css" scoped>
::v-deep .el-dialog__header {
  border-bottom: 1px solid #ebeef5;
}
</style>
