<template>
  <el-container style="flex-grow:1" v-loading="loading">
    <el-aside class="containAside" max-width="500px" width='26%' style=" margin-right: 10px;">
      <div class="asideInfo">
        <div class="contentTitle">
          {{pageTitle}}
          <span></span>
        </div>
        <div class="selectContent">
          <el-select v-model="task" placeholder="请选择干奶任务" style="width:180px">
            <el-option v-for="item in ['提前干奶','干奶预警']" :key="item" :label="item" :value="item"></el-option>
          </el-select>
          <el-select v-model="cowshed" placeholder="请选择牛舍" style="width:180px">
            <el-option v-for="item in cowShedList" :key="item" :label="item" :value="item"></el-option>
          </el-select>

          <el-button type="primary" plain @click="isBath=!isBath">{{isBath?'单头':'批量'}}</el-button>
        </div>
        <div class="tableNum">{{filitList.length}}头奶牛</div>
        <el-table class="handleTable" border :data="filitList" style="width: 100%" @selection-change="handleSelectionChange" :height="(allHeight-184)+'px'" size="small" @row-click="rowClick">
          <el-table-column type="selection" v-if="isBath"></el-table-column>
          <el-table-column prop="牛号" label="牛号" fixed="left" align="center"></el-table-column>
          <el-table-column prop="当前牛舍" label="牛舍" align="center"></el-table-column>
          <!-- <el-table-column prop="内容" label="内容" align="center" >
          </el-table-column>-->
          <el-table-column prop="建议干奶日期" label="建议干奶日期" min-width="100" align="center"></el-table-column>
          <el-table-column prop="配种日期" label="配种日期" min-width="100" align="center"></el-table-column>
          <el-table-column prop="预产日期" label="预产日期" min-width="100" align="center"></el-table-column>
          <el-table-column prop="怀孕天数" label="怀孕天数" align="center"></el-table-column>
          <el-table-column prop="胎次" label="胎次" align="center"></el-table-column>
          <el-table-column prop="盲乳个数" label="盲乳个数" align="center"></el-table-column>
        </el-table>
      </div>
    </el-aside>
    <el-main class="containMain">
      <div class="contentTitle">干奶信息登记</div>
      <el-form ref="form" :model="formData" label-width="100px" style="margin-top:20px;width:522px;">
        <el-form-item label label-width="0">
            <el-autocomplete v-model="formData.cowID" prefix-icon="el-icon-search"  :fetch-suggestions="querySearchAsync" style="width:200px" clearable placeholder="请输入内容" @select="chooseCow"></el-autocomplete>
       
          <!-- <el-button type="primary" @click="getNowCow" style="width:90px;margin-left:12px">确认</el-button> -->
        </el-form-item>
        <div class="sub" v-if="tableData.length>0">操作牛号：{{tableData[0].value}}</div>

        <el-form-item label="干奶类型">
          <el-select v-model="formData.dryType" placeholder="请选择">
            <el-option v-for="item in ['提前干奶', '推后干奶', '正常干奶']" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否异常干奶">
          <el-radio-group v-model="formData.isAbnormal">
            <el-radio label="0">是</el-radio>
            <el-radio label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="异常干奶原因" v-if="formData.isAbnormal=='0'">
          <el-select v-model="formData.abnormalReason" placeholder="请选择">
            <el-option v-for="item in  ['禁配', '营养代谢性疾病', '消化系统疾病', '乳房疾病', '四肢疾病', '外科感染', '损伤', '疝']" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="药物名称">
          <el-select v-model="formData.drugName" placeholder="请选择">
            <el-option v-for="item in ['安倍宁', '奶扶舒', '齐利宁', '乳炎平', '赛福魁']" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="药物剂量">
          <el-input v-model="formData.drugDose" style="width:215px"></el-input>
        </el-form-item>
        <div style="margin-top:80px">
          <el-button @click="onSave" type="primary" style="width:98px;" size="mediu">确认提交</el-button>
        </div>
      </el-form>
    </el-main>
    <el-aside class="containAside" max-width="450px" width='25%' style=" margin-left: 10px;" v-if="!isBath">
      <div class="asideInfo">
        <div class="contentTitle">牛只信息</div>
        <el-table class="handleTable" border :data="tableData" style="width: 100%" :height="(allHeight-70)+'px'" size="small">
          <el-table-column prop="key" label="参数"></el-table-column>
          <el-table-column prop="value" label="当前牛只信信息"></el-table-column>
        </el-table>
      </div>
    </el-aside>
  </el-container>
</template>
<script>
import formValidator from '../formValidator'
import axios from 'axios'
import { mapState } from 'vuex'
export default {
  created() {
    //妊娠检查列表
    this.getList()
    // //配种方式
    // this.getHaleInfo('wsCow', 'getUserDict', ['MateMode'], 'list').then((data) => {
    //     this.mateModes = data
    //     this.formData.mateMode = data[0]['详细方式']
    // })
    // //冻精列表
    // this.getHaleInfo('wsCow', 'getAllBullByFarmName', [
    //     this.$store.state.farmName, true
    // ], 'list').then((data) => {
    //     this.bulls = data
    // })

  },
  data() {
    return {
      saving: false,
      formData: {
        cowID: '',
        dryDate: '',
        currFarm: '',
        currGroup: '',
        mateDate: '',
        currCategory: '',
        dryType: '正常干奶',
        isAbnormal: '1',
        abnormalReason: '禁配',
        isDrugTreated: true,
        drugName: '安倍宁',
        drugDose: ''
      },
      mateModes: [],
      methods: ['人工观察', '计步器揭发', '同期发情'],
      bulls: [],
      tableData: [],
      list: [],
      cowshed: '',
      task: '干奶预警',
      isBath: false,
      chooseList: [],
      loading: false,
      editRow:{}
    }
  },
  computed: {
    ...mapState(['userInfo', 'allHeight']),
    pageTitle() {
      return this.$route.meta.title
    },
    bullMsg() {
      var jsonp = {}
      if (this.formData.bull) {
        this.bulls.forEach(item => {
          if (item['牛号'] == this.formData.bull) {
            jsonp = item
          }
        })
      }

      return jsonp


    },
    filitList() {
      var list = []
      if (this.cowshed) {
        if (this.cowshed == '全部牛舍') {
          list = this.list
        }
        else {
          this.list.forEach(item => {
            if (item['当前牛舍'] == this.cowshed) {
              list.push(item)
            }
          })
        }

      }
      return list
    },
    cowShedList() {
      var list = ['全部牛舍']
      this.list.forEach(item => {
        if (list.indexOf(item['当前牛舍']) === -1) {
          list.push(item['当前牛舍'])
        }
      })
      return list
    },
    allCowList(){
      var list=[]
      this.list.forEach(item=>{
        var jsonp={...item}
        jsonp.value=item['牛号']
        list.push(jsonp)
      })
      return list
    }
  },
  watch: {
    task() {
      this.getList()
      this.cowshed = ''
    }
  },
  methods: {
    getList() {
      this.getHaleInfo('wsVeterinary', 'getDryMilkTask', [this.$store.state.farmName, this.task == '提前干奶'], 'list').then((data) => {
        console.log(data)
        this.list = data



      })
    },
    onSave() {
      if (this.formData.cowID!=this.editRow['牛号']) {
        this.$message({
          message: '请录入牛只牛号',
          type: 'warning'
        });
        return
      }

      if (!this.formData.drugDose) {
        this.$message({
          message: '请录入药物剂量',
          type: 'warning'
        });
        return
      }

      if (this.isBath) {
        this.saveList(0)
        return
      }

      var formData = { ...this.formData }
      formData.isAbnormal = (formData.isAbnormal == '0')
      if (!formData.isAbnormal) {
        delete formData.abnormalReason
      }

      this.getHaleInfo('wsVeterinary', 'addDryMilk', [formData], 'json').then((data) => {
        console.log(data)
        if (data.rtnCode == -1) {
          this.$alert(data.rtnMessage, '提示', {
            confirmButtonText: '确定',
            callback: action => {
              this.formData.cowID = ''
            }
          });
        }
        else {
          this.$message({
            message: '录入成功',
            type: 'success'
          });
          this.formData.cowID = ''
          this.getList()
        }
      })
    },
    saveList(index) {
      this.loading = true
      if (index >= this.chooseList.length) {
        this.loading = false
        this.$alert('成功录入' + this.chooseList.length + '头干奶信息', '成功', {
          confirmButtonText: '确定',
          callback: action => {
            this.chooseList = []
            this.getList()
            this.formData.cowID = ''
          }
        });
        return
      }
      var formData = {
        cowID: this.chooseList[index]['牛号'],
        dryDate: Date.parse(new Date()),
        currFarm: this.chooseList[index]['牧场'],
        currGroup: this.chooseList[index]['当前牛舍'],
        mateDate: Date.parse(new Date(this.chooseList[index]['配种日期'])),
        currCategory: this.chooseList[index]['当前牛舍'],
        dryType: this.formData.dryType,
        isAbnormal: this.formData.isAbnormal == '0',
        abnormalReason: this.formData.abnormalReason,
        isDrugTreated: true,
        drugName: this.formData.drugName,
        drugDose: this.formData.drugDose
      }

      if (!formData.isAbnormal) {
        delete formData.abnormalReason
      }

      this.getHaleInfo('wsVeterinary', 'addDryMilk', [formData], 'json').then((data) => {
        console.log(data)
        if (data.rtnCode == -1) {
          this.loading = false
          this.$alert(this.chooseList[index]['牛号'] + data.rtnMessage + ',已录入' + index + '头牛,录入中断', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              this.chooseList = []
              this.getList()
              this.formData.cowID = ''
            }
          });
        }
        else {
          this.saveList(index + 1)
        }
      })
    },
    getNowCow(row) {
      // console.log(row)
      var list = []
      Object.keys(row).forEach(item => {
        list.push({
          key: item,
          value: row[item]
        })
      })



      // console.log(list)

      this.tableData = list


    },
    rowClick(row) {
      // console.log(row)
      if (!this.isBath) {
        // this.formData = {
        //     cowID: row['牛号'],
        //     geCheckMethod: '直肠检测法',
        //     geCheckResult: '',
        //     isReCheck: false,
        //     operators: ''
        // }
        this.formData = {
          cowID: row['牛号'],
          dryDate: Date.parse(new Date()),
          currFarm: row['牧场'],
          currGroup: row['当前牛舍'],
          mateDate: Date.parse(new Date(row['配种日期'])),
          currCategory: row['当前牛舍'],
          dryType: '正常干奶',
          isAbnormal: '1',
          abnormalReason: '禁配',
          isDrugTreated: true,
          drugName: '安倍宁',
          drugDose: ''
        }

        var jsonp = { ...row }
        this.editRow=row

        this.getNowCow(jsonp)
      }

    },
    handleSelectionChange(val) {
      this.chooseList = val
      if (val.length > 0) {
        this.formData.cowID = val[0]['牛号'] + '...'
      }
      else {
        this.formData.cowID = ''
      }

    },
      querySearchAsync(queryString, cb) {
        var restaurants = this.allCowList;
        var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

      
        var timeout = setTimeout(() => {
          cb(results);
        }, 3000 * Math.random());
      },
      createStateFilter(queryString) {
        return (state) => {
          return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      chooseCow(val){
        this.rowClick(val)
      }
  }
}
</script>
<style lang="less" scoped>
.containMain {
  background: rgba(255, 255, 255, 1);
  border-radius: 4px;
  padding: 15px;
  // margin-right: 10px;
  .contentTitle {
    border-bottom: 1px solid #f2f4f5;
  }
  // min-width: 450px;

  .sub {
    font-size: 14px;
    font-weight: 600;
    color: rgba(102, 102, 102, 1);
    line-height: 20px;
    margin-bottom: 40px;
    padding-left: 20px;
  }
}

.contentTitle {
  font-size: 16px;
  font-weight: bold;
  color: rgba(0, 0, 0, 1);
  line-height: 22px;
  letter-spacing: 1px;
  padding-bottom: 14px;
  span {
    font-size: 13px;
    color: rgba(102, 102, 102, 1);
    line-height: 18px;
    margin-left: 10px;
  }
}

.selectContent {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 0;
}

.tableNum {
  font-size: 13px;
  font-weight: bold;
  color: rgba(102, 102, 102, 1);
  line-height: 18px;
  padding-bottom: 15px;
}

.containAside {
  padding: 0;

  display: flex;
  flex-direction: column;
  .asideInfo {
    flex-grow: 1;
    background: rgba(255, 255, 255, 1);
    border-radius: 4px;
    padding: 15px;
  }
}

.item {
  .item-title {
    font-size: 14px;
    font-weight: bold;

    color: rgba(0, 0, 0, 1);
    line-height: 20px;
    letter-spacing: 1px;
  }

  .text {
    font-size: 13px;
    color: rgba(0, 0, 0, 1);
    line-height: 18px;
    letter-spacing: 1px;
    word-wrap: break-word;
    padding: 10px 0 15px;
  }
}
</style>
