<template>
  <el-container style="flex-grow:1">
    <el-aside class="containAside" max-width="500px" width='26%' style=" margin-right: 10px;">
      <div class="asideInfo">
        <div class="contentTitle">
          {{pageTitle}}
          <!-- <span>{{list.length}}头奶牛</span> -->
        </div>
        <div class="selectContent">
          <el-select v-model="findUser" placeholder="请选择过抗结果" style="width:230px">
            <el-option v-for="item in findUserList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
          <!-- <el-button type="primary" plain @click="filitDayList=filitDay">筛选</el-button> -->
        </div>
        <div class="tableNum">{{filitList.length}}头奶牛</div>
        <el-table class="handleTable" border :data="filitList" style="width: 100%" :height="(allHeight-184)+'px'" size="small" @row-click="rowClick">
          <el-table-column prop="牛号" label="牛号" fixed="left" align="center"></el-table-column>
          <el-table-column prop="发病日期" label="发病日期" width="160" align="center"></el-table-column>

          <el-table-column prop="疾病类型" label="疾病类型" width="140" align="center"></el-table-column>
          <el-table-column prop="疾病名称" label="疾病名称" width="160" align="center"></el-table-column>
          <el-table-column prop="发病揭发人" label="揭发人" align="center"></el-table-column>
          <el-table-column prop="过抗检测" label="过抗检测" align="center" width="100"></el-table-column>
        </el-table>
      </div>
    </el-aside>
    <el-main class="containMain">
      <div class="contentTitle">{{pageTitle}}</div>
      <el-form ref="form" :model="formData" label-width="80px" style="margin-top:20px;width:522px">
        <el-form-item label label-width="0">
          <el-input v-model="formData.cowID" disabled prefix-icon="el-icon-search" style="width:300px" maxlength="8" clearable></el-input>
          <!-- <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">操作牛号：{{editCowInfo['牛号']}}</div>
        <el-form-item label="发病日期">
          <el-input v-model="formData.diseaseDate" disabled style="width:217px"></el-input>
        </el-form-item>
        <!-- <el-form-item label="疾病类型">
          <el-select v-model="formData.category" placeholder="请选择">
            <el-option v-for="item in categoryList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item label="疾病名称">
          <el-select v-model="formData.name" disabled placeholder="请选择">
            <el-option v-for="item in nameList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="转归牛舍">
          <el-select v-model="cowshed" placeholder="请选择">
            <el-option v-for="item in cowshedList" :key="item['牛舍名称']" :label="item['牛舍名称']" :value="item['牛舍名称']"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="治愈日期">
          <el-input v-model="formData.recureDate" style="width:217px"></el-input>
        </el-form-item>

        <el-form-item label="转归状况">
          <el-select v-model="formData.recureStatus" placeholder="请选择">
            <el-option v-for="item in ['治愈']" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="乳区状态" v-if="formData.name=='乳房炎'">
          <div class="selectVal">
            <div class="item" @click="formData.RecureArea_FL=(formData.RecureArea_FL+1)%5" :style="{backgroundColor:RecureArea[formData.RecureArea_FL].color}">{{RecureArea[formData.RecureArea_FL].lable}}</div>
            <div class="item" @click="formData.RecureArea_FR=(formData.RecureArea_FR+1)%5" :style="{backgroundColor:RecureArea[formData.RecureArea_FR].color}">{{RecureArea[formData.RecureArea_FR].lable}}</div>
            <div class="item" @click="formData.RecureArea_BL=(formData.RecureArea_BL+1)%5" :style="{backgroundColor:RecureArea[formData.RecureArea_BL].color}">{{RecureArea[formData.RecureArea_BL].lable}}</div>
            <div class="item" @click="formData.RecureArea_BR=(formData.RecureArea_BR+1)%5" :style="{backgroundColor:RecureArea[formData.RecureArea_BR].color}">{{RecureArea[formData.RecureArea_BR].lable}}</div>
          </div>
        </el-form-item>

        <div style="margin-top:80px">
          <el-button @click="onSave(true)" type="primary" style="width:98px;" size="mediu">转归处理</el-button>
          <!-- <el-button @click="onSave(false)" type="warning" style="width:98px;" size="mediu">停药</el-button> -->
        </div>
      </el-form>
    </el-main>
    <el-aside class="containAside" max-width="450px" width='25%'>
      <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(1)
    //疾病类型
    this.getHaleInfo('wsVeterinary', 'getDiseaseCategory', [], 'list', '疾病名称').then((data) => {
      this.diseaseList = data
      if (data.length > 0) {
        setTimeout(() => {
          this.formData.category = this.categoryList[0]
          this.formData.name = this.nameList[0]
        }, 500)
      }
    })

    //药品列表
    this.getHaleInfo('wsVeterinary', 'getAllMedicine', [], 'list', '药品编号').then((data) => {
      this.allDrugList = this.getChild('#', data)
    })

    //牛舍列表
    this.getHaleInfo('wsCow', 'getAllGroupByFarmName', [
      this.$store.state.farmName
    ], 'list', '牛舍编号').then((data) => {
      var list = []
      data.forEach(item => {
        if (item["牛舍类别"] == "病牛舍") {
          list.push(item)
        }
      })
      this.cowshedList = list
      if (list.length > 0) {
        this.cowshed = list[0]['牛舍名称']
      }

    })
  },
  data() {
    return {
      cowshed: '',
      cowshedList: [],
      saving: false,
      formData: {
        "cowID": '',
        "diseaseDate": '',
        "category": '',
        "name": '',
        "RecureArea_FL": 0,
        "RecureArea_FR": 0,
        "RecureArea_BL": 0,
        "RecureArea_BR": 0,
        "recureDate": '',
        "recureStatus": '治愈'
      },
      tableData: [],
      diseaseList: [],
      editCowInfo: {},
      list: [],
      findUser: '',
      drugList: [],
      dialogVisible: false,
      prescriptionInfoList: [],
      prescription: '',
      useDrugList: [],
      allDrugList: [],
      innerVisible: false,
      innerinnerVisible: false,
      addForm: {
        '药品名称': '',
        '使用方法': '穿刺',
        '剂量': 1,
        '医嘱': ''
      },
      temperatureList: [{
        lable: '37度及以下',
        val: 0
      }, {
        lable: '37-37.5度',
        val: 1
      }, {
        lable: '37.5-38度',
        val: 2
      }, {
        lable: '38-38.5度',
        val: 3
      }, {
        lable: '38.5-39度',
        val: 4
      }, {
        lable: '39-39.5度',
        val: 5
      }, {
        lable: '39.5度-40度',
        val: 6
      }, {
        lable: '40-40.5度',
        val: 7
      }, {
        lable: '40.5-41度',
        val: 8
      }, {
        lable: '41度及以上',
        val: 9
      }],
      RecureArea: [{
        lable: '正常',
        color: 'rgba(133,195,6,1)'
      }, {
        lable: '一级',
        color: 'rgba(221,201,4,1)'
      }, {
        lable: '二级',
        color: 'rgba(234,123,29,1)'
      }, {
        lable: '三级',
        color: 'rgba(208,73,44,1)'
      }, {
        lable: '盲乳',
        color: 'rgba(0,150,224,1)'
      }],
      stopDrug: false,
      stopForm: {
        stopDate: '当天',
        sampleDate: 0
      }
    }
  },
  computed: {
    ...mapState(['userInfo', 'allHeight']),
    // describeList() {
    //   var list = []
    //   switch (this.formData.num) {
    //     case "1":
    //       list = ['单母胎', '单公胎']
    //       break;
    //     case "2":
    //       list = ['双母胎', '双公胎', '龙凤胎']
    //       break;
    //     case "3":
    //       list = ['三母胎', '三公胎', '两公一母', '两母一公']
    //       break;
    //   }
    //   return list
    // },
    pageTitle() {
      return this.$route.meta.title
    },
    filitList() {
      var list = []
      this.list.forEach(item => {
        if (this.findUser == '全部') {
          list.push(item)
        }
        else {
          if (item['过抗检测'] == this.findUser) {
            list.push(item)
          }
        }

      })
      return list
    },
    findUserList() {
      var list = ['全部', '阴性', '阳性']
      return list
    },
    nameList() {
      var list = []
      if (this.formData.category) {
        this.diseaseList.forEach(item => {
          if (list.indexOf(item['疾病名称']) == -1 && item['所属分类'] == this.formData.category) {
            list.push(item['疾病名称'])
          }
        })
      }
      return list
    },
    categoryList() {
      var list = []
      this.diseaseList.forEach(item => {
        if (list.indexOf(item['所属分类']) == -1) {
          list.push(item['所属分类'])
        }
      })
      return list
    },
    typeList() {
      var list = []
      if (this.formData.category && this.formData.name) {
        this.diseaseList.forEach(item => {
          if (item['疾病名称'] == this.formData.name && item['所属分类'] == this.formData.category) {
            list = item['主要症状'].split(';')
          }
        })
      }
      return list
    },
    prescriptionList() {
      var list = []
      this.prescriptionInfoList.forEach(item => {
        var flag = false
        for (var i = 0; i < list.length; i++) {
          if (list[i].name == item['处方名称']) {
            flag = true
            list[i].children.push(item)
            break
          }
        }
        if (!flag) {
          var json = {
            name: item['处方名称'],
            children: [item]
          }
          list.push(json)
        }
      })
      return list

    }
  },
  watch: {
    'formData.cowID'() {
      if (this.formData.cowID.length != 8) {
        return
      }

    },
    'formData.num'() {
      setTimeout(() => {
        // this.formData.describe = this.describeList[0]
      }, 100)
    },
    'formData.category'() {
      setTimeout(() => {
        this.formData.name = this.nameList[0]
      }, 100)
    },
    dialogVisible() {
      if (this.dialogVisible) {
        this.getHaleInfo('wsCow', 'getDiseasePreInfo', [
          this.formData.name
        ], 'list', '疾病名称').then((data) => {
          this.prescriptionInfoList = data
        })
      }
    }
  },
  methods: {
    deleteRow(row, index) {
      this.useDrugList.splice(index, 1)
    },
    changeDrug() {
      this.useDrugList = [...this.drugList]
      this.dialogVisible = true
    },
    sureDrug() {
      this.drugList = [...this.useDrugList]
      this.dialogVisible = false
    },
    sureAdd() {
      this.useDrugList.push(this.addForm)
      this.innerinnerVisible = false
      this.innerVisible = false
    },
    getChild(id, allList) {

      var list = []
      allList.forEach(item => {
        if (id == "#") {

          if (item['药品编号'].length == 2) {
            var jsonp = item
            jsonp['剂量'] = 1
            jsonp['使用方法'] = '穿刺'
            jsonp.children = this.getChild(item['药品编号'], allList)
            list.push(jsonp)
          }
        }
        else {
          var name = item['药品编号'].slice(0, id.length)
          if (item['药品编号'].length - id.length == 2 && name == id) {
            var jsonp = item
            jsonp['剂量'] = 1
            jsonp['使用方法'] = '穿刺'
            jsonp.children = this.getChild(item['药品编号'], allList)
            list.push(jsonp)
          }
        }
      })
      return list
    },
    changeuseDrugList() {
      console.log(this.prescription)
      if (this.prescription) {
        this.prescriptionList.forEach(item => {
          if (item.name == this.prescription) {
            this.useDrugList = this.useDrugList.concat(item.children)
          }
        })
      }
      console.log(this.useDrugList)
    },
    getList(type) {
      this.getHaleInfo('wsVeterinary', 'getPreTask', [
        this.$store.state.farmName
      ], 'list', '', 'YYYY-MM-DD HH:mm:ss').then((data) => {
        this.list = data
        if (data.length > 0) {
          setTimeout(() => {
            this.findUser = this.findUserList[0]
          }, 500)
        }
        if (this.list.length == 0 && type == 1) {
          this.$alert('暂无需要处理的奶牛', '提示', {
            confirmButtonText: '确定',
            callback: action => {

            }
          });
        }

      })
    },
    onSave(isSick) {
      if (!this.formData.cowID) {
        this.$message({
          message: '请录入牛只牛号',
          type: 'warning'
        });
        return
      }
      var formData = { ...this.formData }
      formData.diseaseDate = Date.parse(new Date(formData.diseaseDate)) + 28800000
      formData.recureDate = Date.parse(new Date(formData.recureDate))
      this.getHaleInfo('wsVeterinary', 'diseaseRecure', [
        formData
      ], 'json').then((data) => {
        console.log(data)
        if (data.rtnCode == -1) {
          this.$alert(data.rtnMessage, '提示', {
            confirmButtonText: '确定',
            callback: action => {
              this.formData.cowID = ''
            }
          });
        }
        else {
          this.changeCowshed()
        }
      })

    },
    newGuid() {
      var guid = "";
      for (var i = 1; i <= 32; i++) {
        var n = Math.floor(Math.random() * 16.0).toString(16);
        guid += n;
        if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
          guid += "-";
      }
      return guid;
    },
    changeCowshed() {

      this.getHaleInfo('wsCow', 'changeGroup', [
        this.formData.cowID, this.cowshed, '治愈出院', this.userInfo.username
      ], '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.getList()
          this.formData.cowID = ''
        }
      })

    },
    sureStop() {
      var time = new Date(this.editCowInfo['发病日期']).getTime() + 28800000
      var targetDate = new Date(time - 16 * 60 * 60 * 1000);
      this.getHaleInfo('wsVeterinary', 'diseaseDrugEnd', [
        this.editCowInfo['牛号'], Date.parse(targetDate), this.editCowInfo['疾病类型'], this.editCowInfo['疾病名称'], Date.parse(new Date()), (Date.parse(new Date()) + this.stopForm.sampleDate * 3600000)
      ], '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.getList()
          this.drugList = []
          this.formData.cowID = ''
          this.stopDrug = false
        }
      })
    },
    getNowCow() {

      this.getHaleInfo('wsCow', 'getCowExtendInfoByCowID', [
        this.formData.cowID, 3
      ], 'json').then((data) => {
        this.editCowInfo = data
        // console.log(data)
        var list = []
        Object.keys(data).forEach(item => {
          list.push({
            key: item,
            value: data[item]
          })
        })

        // console.log(list)

        this.tableData = list

        if (data['繁殖状态'] != '复检有胎' && data['繁殖状态'] != '初检已孕') {
          this.$alert('当前母牛无胎，不允许进行登记', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              this.formData.cowID = ''
            }
          });
        }
        else if (data['牛只类别'] == '成母牛' && parseInt(data['在胎天数']) < 150) {
          this.$alert('当前奶牛是成母牛，且在胎天数小于150天，不允许登记产犊（青年牛210天内允许报早产）！', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              this.formData.cowID = ''
            }
          });
        }

        if (parseInt(data['在胎天数']) > 262) {
          this.formData.type == '正产'
        }
        else {
          this.formData.type == '早产'
        }
      }).catch(() => {
        this.formData.cowID = ''
      })
    },
    rowClick(row) {
      this.editCowInfo = row
      this.formData = {
        "cowID": row['牛号'],
        "diseaseDate": row['发病日期'],
        "category": row['疾病类型'],
        "name": row['疾病名称'],
        "RecureArea_FL": parseInt(row['发病时左前区'] || 0),
        "RecureArea_FR": parseInt(row['发病时右前区'] || 0),
        "RecureArea_BL": parseInt(row['发病时左后区'] || 0),
        "RecureArea_BR": parseInt(row['发病时右后区'] || 0),
        "recureDate": this.getTime(new Date(), 'YYYY-MM-DD HH:mm:ss'),
        "recureStatus": '治愈',
        "recurePerson": this.userInfo.username
      }
      var list = []
      Object.keys(row).forEach(item => {
        list.push({
          key: item,
          value: row[item]
        })
      })
      this.tableData = list


    },
    handleNodeClick(data) {
      // console.log(data)
      if (data.children.length == 0) {
        data['使用方法'] = '穿刺'
        data['剂量'] = 1
        data['医嘱'] = ''
        this.addForm = data
        this.innerinnerVisible = true
      }
    }
  }
}
</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;
}

.containAside {
  padding: 0;
  margin-left: 10px;
  display: flex;
  flex-direction: column;
  .asideInfo {
    flex-grow: 1;
    background: rgba(255, 255, 255, 1);
    border-radius: 4px;
    padding: 15px;
  }
}
.tableNum {
  font-size: 13px;
  font-weight: bold;
  color: rgba(102, 102, 102, 1);
  line-height: 18px;
  padding-bottom: 15px;
}
.selectContent {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 0;
}

.selectVal {
  width: 140px;
  display: flex;
  align-items: center;
  justify-content: space-around;
  flex-wrap: wrap;

  .item {
    width: 60px;
    border-radius: 4px;
    height: 60px;
    text-align: center;
    font-size: 13px;
    font-weight: bold;
    color: rgba(255, 255, 255, 1);
    line-height: 60px;
    margin-bottom: 10px;
    cursor: pointer;
  }
}
</style>
