<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="600px">
    <el-form 
      :model="dataForm" 
      :rules="dataRule" 
      ref="dataForm" 
      @keyup.enter.native="dataFormSubmit()" 
      label-width="80px" 
      size="mini"
      style="margin-left: 20px;width: 500px">
      <el-form-item label="耳标" prop="eartag">
        <el-input
          type="textarea"
          :rows="2"
          placeholder="每个耳标之间用英文逗号隔开，最多可以添加50头猪"
          v-model="dataForm.eartag"
          :disabled="dataForm.id? true: false">
        </el-input>
      </el-form-item>
      <el-form-item label="猪舍" prop="pigstyId">
        <el-select 
          v-model="dataForm.pigstyId"
          style="width: 100%">
          <el-option
            v-for="item in pigstyList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="单元" prop="unitId">
        <el-select 
          v-model="dataForm.unitId"
          style="width: 100%">
          <el-option
            v-for="item in unitSelectedList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="栏期" prop="periodId">
        <el-select 
          v-model="dataForm.periodId"
          style="width: 100%" 
          @change="ifPigsty('periodId')">
          <el-option
            v-for="item in periodList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="性别" prop="sex">
        <el-select 
          v-model="dataForm.sex"
          style="width: 100%">
          <el-option
            v-for="item in gender"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="出生日期" prop="birthday">
        <el-date-picker
          v-model="dataForm.birthday"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择出生日期"
          @change="changeBirth"
          style="width: 100%">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="健康状态" prop="healthStatus">
        <el-select 
          v-model="dataForm.healthStatus"
          style="width: 100%">
          <el-option
            v-for="item in healthStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="体重" prop="weight">
        <el-input-number
          v-model="dataForm.weight"
          :step="0.01"
          :max="1000000"
          :min="0"
          style="width: 91%">
        </el-input-number>
        千克
      </el-form-item>
      <!-- <el-form-item label="产地" prop="originPlace">
        <el-select 
          v-model="dataForm.originPlace"
          style="width: 100%">
          <el-option
            v-for="item in originPlaceList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="品种" prop="breed">
        <el-select 
          v-model="dataForm.breed"
          style="width: 100%">
          <el-option
            v-for="item in breedList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="养殖状态" prop="outFenceStatus">
        <el-select 
          v-model="dataForm.outFenceStatus"
          style="width: 100%">
          <el-option
            v-for="item in outFenceStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="父亲" prop="fatherEartag">
        <el-input v-model="dataForm.fatherEartag"></el-input>
      </el-form-item>
      <el-form-item label="母亲" prop="motherEartag">
        <el-input v-model="dataForm.motherEartag"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="mini" @click="visible = false">关闭</el-button>
      <el-button size="mini" type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,
        dataForm: {
          id: '',
          eartag: '',
          pigstyId: '',
          unitId: '',
          // periodId: '',
          sex: '母',
          birthday: '',
          healthStatus: true,
          weight: 5,
          originPlace: '',
          breed: '',
          outFenceStatus: 0,
          motherEartag: '',
          fatherEartag: ''
        },
        dataRule: {
          eartag: [
            { required: true, message: '耳标不能为空', trigger: 'blur' }
          ],
          pigstyId: [
            { required: true, message: '栋舍不能为空', trigger: 'blur' }
          ],
          unitId: [
            { required: true, message: '单元不能为空', trigger: 'blur' }
          ],
          breed: [
            { required: true, message: '品种不能为空', trigger: 'blur' }
          ],
          birthday: [
            { required: true, message: '品种不能为空', trigger: 'blur' }
          ],
          healthStatus: [
            { required: true, message: '健康状态不能为空', trigger: 'blur' }
          ],
          outFenceStatus: [
            { required: true, message: '健康状态不能为空', trigger: 'blur' }
          ],
          sex: [
            { required: true, message: '性别不能为空', trigger: 'blur' }
          ],
          weight: [
            { required: true, message: '体重不能为空', trigger: 'blur' }
          ]
        },
        gender: [
          {
            value: '公',
            label: '公'
          },
          {
            value: '母',
            label: '母'
          }
        ],
        pigstyList: [], // 栋舍List
        unitList: [], // 单元List
        unitSelectedList: [], // 单元SelectedList
        // periodList: [], // 栏期List
        // periodSelectedList: [], // 栏期SelectedList
        healthStatus: [
          {
            value: true,
            label: '健康'
          },
          {
            value: false,
            label: '不健康'
          }
        ],
        breedList: [], // 品种List
        originPlaceList: [], // 产地List
        outFenceStatus: [
          {
            value: 0,
            label: '育肥'
          },
          {
            value: 1,
            label: '出栏'
          }
        ]
      }
    },
    methods: {
      // 在pbentry.vue调用该方法
      init (pigs) {
        this.visible = true
        this.dataForm.id = ''
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (pigs.length > 0) {
            console.log(pigs);
            let ids = []
            let eartags = []
            pigs.forEach(pig => {
              ids.push(pig.id)
              eartags.push(pig.eartag)
            })
            this.dataForm.id = ids.join()
            this.dataForm.eartag = eartags.join()
          }
        })
        if (pigs.length) {
          this.$http({
            url: this.$http.adornUrl(`/management/lairagerecord/info/${pigs[0].id}`),
            method: "get",
            params: this.$http.adornParams({})
          }).then(({data}) => {
            // this.dataForm.id = pigs.map(item => item.id)
            // this.dataForm.eartag = pigs.eartag.join()
            this.dataForm.pigstyId = data.lairageRecord.pigstyId
            this.dataForm.unitId = data.lairageRecord.unitId
            // this.dataForm.periodId = data.yearPigBase.periodId
            this.dataForm.sex = data.lairageRecord.sex
            this.dataForm.birthday = data.lairageRecord.birthday
            this.dataForm.healthStatus = data.lairageRecord.healthStatus
            this.dataForm.weight = data.lairageRecord.weight
            // this.dataForm.originPlace = data.yearPigBase.originPlace
            this.dataForm.breed = data.lairageRecord.breed
            this.dataForm.outFenceStatus = data.lairageRecord.outFenceStatus
            this.dataForm.motherEartag = data.lairageRecord.motherEartag
            this.dataForm.fatherEartag = data.lairageRecord.fatherEartag
          })
        }
        this.$http({
          url: this.$http.adornUrl("/management/pigsty/findAll"),
          method: "get",
          params: this.$http.adornParams({})
        }).then(async({ data }) => {
          // 栋舍List
          this.pigstyList = []
          let pigstyList = []
          data.all && (pigstyList = data.all)
          pigstyList.forEach(pigsty => {
            let item = {
              value: pigsty.id,
              label: pigsty.number
            }
            this.pigstyList.push(item)
          })
          // 单元List
          this.unitList = []
          let unitList = []
          let unitR = await this.$http({
            url: this.$http.adornUrl("/management/unit/findAll"),
            method: "get",
            params: this.$http.adornParams({})
          })
          unitR.data.all && (unitList = unitR.data.all)
          unitList.forEach(unit => {
            let item = {
              value: unit.id,
              label: unit.number,
              pigstyId: unit.pigstyId,
              // farmId: unit.farmId
            }
            this.unitList.push(item)
          })
          this.unitSelectedList = this.dataForm.pigstyId? this.unitList.filter(item => item.pigstyId === this.dataForm.pigstyId): this.unitList
          // 品种list
          let breedList = []
          let bloodR = await this.$http({
            url: this.$http.adornUrl(`/management/basebloodline/findAll`),
            method: 'get',
            params: this.$http.adornParams({}, false)
          })
          bloodR.data.all && (breedList = bloodR.data.all)
          this.breedList = []
          // this.originPlaceList = []
          breedList.forEach(breed => {
            let item = {
              value: breed.name,
              label: breed.name,
              origin: breed.origin
            }
            // let item02 = {
            //   value: breed.origin,
            //   label: breed.origin
            // }
            this.breedList.push(item)
            // this.originPlaceList.push(item02)
          })
        })
      },
      // // 根据栋舍选择限制单元和栏期
      // pigstyChange (val) {
      //   this.unitSelectedList = this.unitList.filter(item => item.pigstyId === val)
      //   console.log(this.unitSelectedList);
      //   // this.periodSelectedList = this.periodList.filter(item => item.pigstyId === val)
      // },
      // 需要先选择猪舍，才能选择单元或栏期
      // ifPigsty (val) {
      //   if (!this.dataForm.pigstyId) {
      //     this.$message.error('请先选择猪舍')
      //     this.dataForm[val] = ''
      //   }
      // },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`${!this.dataForm.id ?'/management/lairagerecord/batchLairage': '/management/lairagerecord/update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'eartag': this.dataForm.eartag,
                'farmId': parseInt(this.$cookie.get('formFarmId')),
                'pigstyId': this.dataForm.pigstyId,
                'unitId': this.dataForm.unitId,
                // 'periodId': this.dataForm.periodId,
                'sex': this.dataForm.sex || undefined,
                'birthday': this.dataForm.birthday || undefined,
                'healthStatus': this.dataForm.healthStatus,
                'weight': this.dataForm.weight,
                'originPlace': this.dataForm.breed? (this.breedList.filter(item => item.value === this.dataForm.breed))[0].origin: undefined,
                'breed': this.dataForm.breed || undefined,
                'outFenceStatus': this.dataForm.outFenceStatus,
                'motherEartag': this.dataForm.motherEartag || undefined,
                'fatherEartag': this.dataForm.fatherEartag || undefined
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.visible = false
                let addLength = this.dataForm.eartag.split(',').length
                this.$emit('refreshDataList', `${!this.dataForm.id? 'add-' + addLength: ''}`)
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  // onClose: () => {
                  //   this.visible = false
                  //   this.$emit('refreshDataList')
                  // }
                })
                // this.resetForm()
                this.visible = false
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 获取出生日期
      changeBirth(val) {
        let birth = new Date(val);
        let now = new Date();
        let days = now.getTime() - birth.getTime();
        if (days < 0) {
          this.$confirm(`出生日期有误`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            this.dataForm.birthday = ''
            console.log("还没出生呢...");
          }).catch(() => {});
        }
      }
    },
    watch: {
      'dataForm.pigstyId': {
        handler(newValue, oldValue) {
          if (oldValue) {
            this.dataForm.unitId = ''
            // this.dataForm.periodId = ''
          }
          this.unitSelectedList = this.unitList.filter(item => item.pigstyId === newValue)
        }
      }
    }
  }
</script>
