<template>
  <div class="global">
    <div class="mainContainer">
      <div class="header">
        <span>粮情检测类型:</span>
        <span>{{ checkPerson }}</span>
      </div>

      <div class="table">
        <el-table
          border
          stripe
          ref="orderTable"
          highlight-current-row
          :data="tbdata"
          height="550"
          row-key="index"
          @current-change="handleCurrentChange"
        >
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="50px"
          />
          <el-table-column
            prop="createTime"
            label="检查时间"
            align="center"
          /><el-table-column
            prop="fieldValue"
            label="检查项对应名称"
            align="center"
            v-if="false"
          />
          <el-table-column prop="fieldDetail" label="检查项" align="center" />
          <el-table-column prop="whether" label="选项" align="center">
            <template slot-scope="scope">
              <el-radio-group
                v-model="scope.row.whether.radio"
                @change.native="showClick(scope.$index, scope.row)"
              >
                <el-radio label="1">{{ scope.row.whether.status1 }}</el-radio>
                <el-radio label="0">{{ scope.row.whether.status2 }}</el-radio>
<!--                 <div v-if="type == '2' ">
                  <el-button>新增显示</el-button>
                </div> -->
                <div v-if="type == '1' || type == '3'">
                  <el-link :underline='false' class="spike" id="spike"
                     v-if='scope.row.whether.radio ==1 && scope.row.fieldDetail.indexOf("异常") != -1'
                     @click='showHandler(scope.row)'
                     >
                     {{scope.row.fieldDetail + '  >>'}}
                     </el-link>
                </div>

                <!-- <el-button   v-if='scope.row.whether.radio ==1 && scope.row.fieldDetail.indexOf("异常") != -1'>{{scope.row.fieldDetail + '  >>'}}</el-button> -->
              </el-radio-group>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="btns">
        <el-button type="success" @click="cancel()" plain>取消</el-button>

        <el-button type="success" v-if="!flag" @click="saveInfo"
          >暂存</el-button
        >
        <el-button type="success" v-if="flag" @click="saveInfo">保存</el-button>

<!--       <div v-if='type="1" || type="3"'>

      </div> -->
      </div>

      <!-- 新增虫害异常 -->
      <el-dialog title="虫害异常描述" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item label="虫害密度" :label-width="formLabelWidth">
            <el-input
              type="textarea"
              v-model="form.pestDensity"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="发生部位" :label-width="formLabelWidth">
            <el-input
              type="textarea"
              v-model="form.pestOccurPosition"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="发生面积" :label-width="formLabelWidth">
            <el-input
              type="textarea"
              v-model="form.pestOccurArea"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="虫害种类" :label-width="formLabelWidth">
            <el-input
              type="textarea"
              v-model="form.pestType"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveFormData()">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 新增水分检测异常 -->
      <el-dialog
        title="水分异常描述"
        :visible.sync="dialogFormVisible1"
        width="40%"
      >
        <el-form :model="form">
          <el-input
            type="textarea"
            v-model="form.abnormalWater"
            autocomplete="off"
          ></el-input>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible1 = false">取 消</el-button>
          <el-button type="primary" @click="dialogFormVisible1 = false"
            >确 定</el-button
          >
        </div>
      </el-dialog>
      <!-- 新增粮情异常 -->
      <el-dialog
        title="粮情异常描述"
        :visible.sync="dialogFormVisible2"
        width="40%"
      >
        <el-form :model="form">
          <el-form-item>
            <el-input
              type="textarea"
              v-model="form.abnormalGrain"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="saveForm">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  addGrainInfo,
  getCheckItems,
  getAddInfo,
  checkGrainInfo,
  editGrainInfo,
  addInfo,
  getDateTimeNow
} from "@/api/grainCheck/index"
export default {
  name: "AddNewGrain",
  data() {
    return {
      // 单选绑定
      dialogFormVisible: false, // 虫害异常表单
      dialogFormVisible1: false, // 水分异常表单
      dialogFormVisible2: false, // 粮情异常表单
      formLabelWidth: "80px",
      flag: false, // 单选项被全部选择，暂存改为保存
      checkTime: "",

      //form 表单数据
      form: {
        // pest: false,
        pestDensity: "", // 虫害密度
        pestOccurArea: "", //发生面积
        pestOccurPosition: "", // 发生部位
        pestType: " ", // 虫害种类
        abnormalGrain: "", // 粮情异常描述
        abnormalWater: "" // 水分检测异常描述
      },
      // 初始化表格拿到数据
      tbdata: [],
      // 查看修改时加载数据
      describe:{},
      // 通过路由带过来的数据
      data: {},
      // 每行id
      id: "",
      // 按钮类型
      type: "",
      // 检查类型
      checkPerson: "",
      data2: {},
      // 先自定义后台接收数据的模板然后拼接
      data3: {
        checkTime: "2020-12-06 12:00:00",
        checkList: "h",
        choose: "h",
        checkDescribe: {},
        grainCheckChooseRecordPO: {
          turnOnLight: "0",
          perintGrainTemperatureResut: "0"
        },
        checkPerson: "总经理每季检查粮情66",
        recordStatus: "0",
        anomalousStatus: "1",
        ready: "1",
        grainAbnormalDescribe: {
          abnormalGrain: "1",
          abnormalWater: "1",
          pestDensity: "每立方米500只蝗虫111222",
          pestOccurPosition: "山西省太原市5号粮库",
          pestOccurArea: "100亩",
          pestType: "蝗虫灾害"
        }
      }
    }
  },
  mounted() {
    // 初始化的时候把参数拼接到要传输的数据里
    let routeParams = this.$route.query
    this.id = routeParams.data.id
    this.type = routeParams.type
    this.checkPerson = routeParams.data.checkPerson
    this.data = routeParams
    this.describe =JSON.parse(routeParams.data.checkDescribe)

    this.data3.checkTime = routeParams.data.checkTime
    this.data3.checkPerson = routeParams.data.checkPerson
    this.data3.recordStatus = routeParams.data.recordStatus || "1"
    this.data3.anomalousStatus = routeParams.data.anomalousStatus || "1"

    // 新增初始化数据
    this.getinfo()
  },
  methods: {
    showHandler(val){
      console.log(val,'val...')
      if(val.fieldValue =='pest_abnormal'){
        this.dialogFormVisible = true
      }else if(val.fieldValue =='water_abnormal'){
        this.dialogFormVisible1 = true
      }else if(val.fieldValue =='grain_abnormal'){
        this.dialogFormVisible2 = true
      }
    },
    getinfo() {
      // 目前只有一页，在前端写死了请求参数
      // 在内部判断是新增修改还是查看
      let data1 = { pageIndex: 1, pageSize: 30 }
      console.log(this.type,'type...')
      if(this.type =='2'){
        getAddInfo(data1)
        .then(res => {
          this.tbdata = res.data.records
          // console.log('新增初始化')
        })
        .catch(err => {
          console.log(err)
        })
      }else if(this.type =='1' || this.type =='3')
        getAddInfo(data1)
        .then(res => {
          this.tbdata = res.data.records
          // console.log("产看修改初始化")
          if(res.code ==200){
            // 如果成功，就再次调用查看接口
            checkGrainInfo(this.id).then(res => {
            this.describe = JSON.parse(res.data.checkDescribe)

            //如果有异常项，就把异常项的值赋值给form数据源
            this.form.pestDensity = this.data.data.grainAbnormalDescribe.pestDensity
            this.form.pestOccurArea = this.data.data.grainAbnormalDescribe.occurArea
            this.form.pestOccurPosition = this.data.data.grainAbnormalDescribe.occurPosition
            this.form.pestType = this.data.data.grainAbnormalDescribe.pestType
            this.form.abnormalGrain = this.data.data.grainAbnormalDescribe.abnormalGrain
            this.form.abnormalWater = this.data.data.grainAbnormalDescribe.abnormalWater

            /* 遍历this.describe的key跟初始化时的每一项的fieldValue匹配，
            匹配成功则把时间跟choose赋值给数据源tbdata */

            for(const key in this.describe){
              for(let i =0;i<this.tbdata.length;i++){
                if(key ==this.tbdata[i].fieldValue){
                  this.tbdata[i].createTime = this.describe[key].time
                  this.tbdata[i].whether.radio = this.describe[key].choose
                }
              }
              // if(key ==this.)
            }
            }).catch(err =>{
            console.log(err)
          })
          }
        })
        .catch(err => {
          console.log(err)
        })
    },

    handelSave() {
      console.log(
        this.weekData[0].checkItem + "-------" + this.weekData[0].option.radio
      )
      // console.log(this.weekData)
    },
    saveFormData() {
      this.dialogFormVisible = false
    },
    saveForm() {
      this.dialogFormVisible2 = false
    },
    // 当表格当前行发生变化是触发
    handleCurrentChange() {},
    // 通过判断单选按钮的选择，弹出异常表单
    showClick(index, val) {
      let time = getDateTimeNow()
      this.tbdata[index].createTime = time
      // 动态的把当前检查项作为对象名称保存到checkDescribe
      this.data3.checkDescribe[this.tbdata[index].fieldValue] = {
        choose: this.tbdata[index].whether.radio,
        time: this.tbdata[index].createTime
      }
      var tb = this.tbdata
      for (let i = 0; i < tb.length; i++) {
        if (
          tb[i].whether.radio == null ||
          tb[i].whether.radio == "" ||
          tb[i].whether.radio == undefined
        ) {
          this.flag = false
        } else {
          this.flag = true
        }
      }
      /*       if (!(val.whether.radio == '' || val.whether.radio==undefined ||val.whether.radio ==null)){
        this.flag = true
      }
      else{
        this.flag = false
      } */

      // console.log(val.whether.radio)
      // 通过判断radio值是否为1，控制异常项弹出框
      if (val.whether.radio == 1) {
        if (val.fieldValue == "pest_abnormal") {
          this.dialogFormVisible = true
        }
        if (val.fieldValue == "water_abnormal") {
          this.dialogFormVisible1 = true
        }
        if (val.fieldValue == "grain_abnormal") {
          // console.log("进了粮情异常表单")
          this.dialogFormVisible2 = true
        }
      }
    },
    // 暂存或者保存
    saveInfo() {
      this.data3.grainAbnormalDescribe = this.form
      this.data3.checkDescribe = JSON.stringify(this.data3.checkDescribe)
      console.log( this.data3.anomalousStatus)
      //判断一下三个异常项是否被选择，部位空改变异常状态anomalousStatus
      if(
        this.data3.grainAbnormalDescribe == ''
        || this.data3.grainAbnormalDescribe ==null
        || this.data3.grainAbnormalDescribe ==undefined
        ){
        this.data3.anomalousStatus = '0'
      }else{
        this.data3.anomalousStatus = '1'
      }
      console.log(this.data3.anomalousStatus)
      if(this.type=='2'){
      addInfo(this.data3)
        .then(res => {
          console.log(res)
          this.$message({
          message: '恭喜你，新增成功了！',
          type: 'success'
        })
          this.$router.push({
            path: "/reservesManagement/grainCheck/newGrain"
          })
        })
        .catch(err => {
          console.log(err)
        })
      }else if(this.type == '1'|| this.type =='3'){
        editGrainInfo(this.data3).then(res =>{
          console.log(res)
          this.$message({
          message: '恭喜你，修改成功了！',
          type: 'success'
        })
          this.$router.push({
            path: "/reservesManagement/grainCheck/allGrain"
        })
        }).catch(err =>{
          console.log(err)
        })
      }
    },
    // 取消按钮
    cancel() {
      this.$router.push({
        path: "/grainCheck/addNewGrain"
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.header {
  margin-bottom: 20px;
}
.btns {
  text-align: right;
  margin-top: 20px;
}
#spike {
  color:#008000;
  display: flex;
  margin-right: 118px;
  margin-top: 18px;
  margin-bottom: 9px;
}
#spike:hover {
  color:008000;
  text-decoration: none;
}
</style>
