<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%"
          @change="pigstyChange">
          <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%"
          @change="ifPigsty('unitId')">
          <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>
    <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: '',
          pigIds: []
          // periodId: '',
          // sex: '',
          // birthday: '',
          // healthStatus: true,
          // weight: '',
          // 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' }
          ],
          // periodId: [
          //   { 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: [
        //   {
        //     value: 1,
        //     label: '杜巴嘉'
        //   },
        //   {
        //     value: 2,
        //     label: '长白'
        //   }
        // ], // 品种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()
          let ids = []
          let eartags = []
          this.dataForm.pigIds = []
          pigs.forEach(pig => {
            ids.push(pig.id)
            this.dataForm.pigIds.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/yearpigbase/info/${pigs[0].id}`),
        //     method: "get",
        //     params: this.$http.adornParams({})
        //   }).then(({data}) => {
        //     this.dataForm.id = data.yearPigBase.id
        //     this.dataForm.eartag = data.yearPigBase.eartag
        //     this.dataForm.pigstyId = data.yearPigBase.pigstyId
        //     this.dataForm.unitId = data.yearPigBase.unitId
        //     this.dataForm.periodId = data.yearPigBase.periodId
        //     this.dataForm.sex = data.yearPigBase.sex
        //     this.dataForm.birthday = data.yearPigBase.birthday
        //     this.dataForm.healthStatus = data.yearPigBase.healthStatus
        //     this.dataForm.weight = data.yearPigBase.weight
        //     this.dataForm.originPlace = data.yearPigBase.originPlace
        //     this.dataForm.breed = data.yearPigBase.breed
        //     this.dataForm.outFenceStatus = data.yearPigBase.outFenceStatus
        //     this.dataForm.motherEartag = data.yearPigBase.motherEartag
        //     this.dataForm.fatherEartag = data.yearPigBase.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.unitList
          // // 栏期List
          // this.periodList = []
          // let periodList = []
          // let periodR = await this.$http({
          //   url: this.$http.adornUrl("/management/period/findAll"),
          //   method: "get",
          //   params: this.$http.adornParams({})
          // })
          // periodR.data.all && (periodList = periodR.data.all)
          // periodList.forEach(period => {
          //   let item = {
          //     value: period.id,
          //     label: period.number,
          //     pigstyId: period.pigstyId
          //   }
          //   this.periodList.push(item)
          // })
          // this.periodSelectedList = this.periodList




          
        })
      },
      // 根据栋舍选择限制单元和栏期
      pigstyChange (val) {
        this.unitSelectedList = this.unitList.filter(item => item.pigstyId === val)
        // this.periodSelectedList = this.periodList.filter(item => item.pigstyId === val)
      },
      // 需要先选择猪舍，才能选择单元或栏期
      ifPigsty () {
        if (!this.dataForm.pigstyId) {
          this.$message.error('请先选择猪舍')
          this.dataForm.unitId = ''
        }
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/management/yearpigbase/transferPeriod`),
              method: 'post',
              data: this.$http.adornData({
                'pigIds': this.dataForm.pigIds,
                'unitId': this.dataForm.unitId
                // 'farmId': parseInt(this.$cookie.get('formFarmId')),
                // 'pigstyId': this.dataForm.pigstyId,
              }, false)
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.visible = false
                this.$emit('refreshDataList')
                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)
            this.periodSelectedList = this.periodList.filter(item => item.pigstyId === newValue)
          }
        }
      }
    }
  }
</script>
