<template>
  <div v-if="visible">
    <!-- 干物质调节-配方选择 -->
    <el-dialog :fullscreen="dialogFull" :destroy-on-close="true" :visible.sync="visible" :close-on-click-modal="false" append-to-body :before-close="closeDialog" width="35%">
      <template slot="title">
        <div class="avue-crud__dialog__header">
          <span class="el-dialog__title">
            <span style="display:inline-block;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px" />
            干物质调节-配方选择
          </span>
          <div class="avue-crud__dialog__menu" @click="dialogFull? dialogFull=false: dialogFull=true">
            <svg-icon v-if="dialogFull" icon-class="exit-fullscreen" />
            <svg-icon v-else icon-class="fullscreen" />
          </div>
        </div>
      </template>
      <div style="min-height:200px;justify-content:center;align-items:center;display:flex;">
        <div>
          <span style="margin-right: 10px;">请选择栏舍配方:</span>
          <el-select v-model="temp.ftid" filterable class="filter-item">
            <el-option v-for="item in balconicFormulaList" :key="item.id" :label="item.tname" :value="item.id" />
          </el-select>
        </div>
      </div>
      <div slot="footer" class="dialog-footer" style="bottom: 10px;">
        <el-button class="cancelClose" @click="closeDialog()">取消</el-button>
        <el-button class="save" @click="handleNextSamplingSelection()">下一步</el-button>
      </div>
    </el-dialog>

    <!-- 干物质调节—采样选择 -->
    <el-dialog :fullscreen="dialogFull" :visible.sync="samplingSelection.dialogFormVisible" append-to-body :close-on-click-modal="false" :before-close="closeDialog" width="80%">
      <template slot="title">
        <div class="avue-crud__dialog__header">
          <span class="el-dialog__title">
            <span style="display:inline-block;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px" />
            {{ textMap[samplingSelection.dialogStatus] }}
          </span>
          <div class="avue-crud__dialog__menu" @click="dialogFull? dialogFull=false: dialogFull=true">
            <svg-icon v-if="dialogFull" icon-class="exit-fullscreen" />
            <svg-icon v-else icon-class="fullscreen" />
          </div>
        </div>
      </template>
      <div class="dialogMinHeight">
        <div class="search filter-item">
          <el-select v-model="samplingSelection.getdataListParm.parammaps.date" filterable placeholder="日期" class="filter-item" style="width: 150px;">
            <el-option v-for="item in samplingSelection.dateList" :key="item.id" :label="item.date" :value="item.date" />
          </el-select>
          <el-select v-model="samplingSelection.getdataListParm.parammaps.barid" filterable placeholder="栏舍名称" class="filter-item" style="width: 120px;" clearable>
            <el-option v-for="item in samplingSelection.houseNameList" :key="item.id" :label="item.bname" :value="item.id" />
          </el-select>
          <el-select v-model="samplingSelection.getdataListParm.parammaps.times" filterable placeholder="班次" class="filter-item" style="width: 120px;" clearable>
            <el-option v-for="item in samplingSelection.frequencyList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-button class="successBorder" @click="form_search">查询</el-button>
        </div>
        <div class="table" style="margin-top: 10px;">
          <el-table
            :key="samplingSelection.tableKey"
            v-loading="samplingSelection.listLoading"
            element-loading-text="给我一点时间"
            :data="samplingSelection.list"
            border
            fit
            highlight-current-row
            style="width: 100%;"
            :row-style="rowStyle"
            :cell-style="cellStyle"
            class="elTable table-fixed"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" align="center" width="50" />
            <el-table-column label="序号" align="center" type="index" width="50px" />
            <el-table-column label="栏舍名称" prop="barname" min-width="110px" align="center" />
            <el-table-column label="班次" prop="times" min-width="110px" align="center" />
            <el-table-column label="鲜样重量（g）" prop="freshweight" min-width="110px" align="center" />
            <el-table-column label="烘干重量（g）" prop="dryweight" min-width="110px" align="center" />
            <el-table-column label="理论干物质" prop="thoweight" min-width="110px" align="center" />
            <el-table-column label="实际干物质" prop="actweight" min-width="110px" align="center" />
            <el-table-column label="操作人" prop="emp" min-width="110px" align="center" />
            <el-table-column label="操作日期" prop="operatetime" min-width="110px" align="center" />
          </el-table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer" style="bottom: 10px;">
        <el-button class="cancelClose" @click="closeDialog();">取消</el-button>
        <el-button class="save" @click="samplingSelection.dialogFormVisible=false; samplingSelection.frequencyList = []">上一步</el-button>
        <el-button class="save" @click="handleNextChangeDetails()">下一步</el-button>
      </div>
    </el-dialog>

    <!-- 干物质调节-变化详情 -->
    <el-dialog :fullscreen="dialogFull" :visible.sync="changeDetails.dialogFormVisible" append-to-body :close-on-click-modal="false" :before-close="closeDialog" width="80%">
      <template slot="title">
        <div class="avue-crud__dialog__header">
          <span class="el-dialog__title">
            <span style="display:inline-block;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px" />
            {{ textMap[changeDetails.dialogStatus] }}
          </span>
          <div class="avue-crud__dialog__menu" @click="dialogFull? dialogFull=false: dialogFull=true">
            <svg-icon v-if="dialogFull" icon-class="exit-fullscreen" />
            <svg-icon v-else icon-class="fullscreen" />
          </div>
        </div>
      </template>
      <div class="dialogMinHeight">
        <div class="table">
          <el-table
            :key="changeDetails.tableKey"
            v-loading="changeDetails.listLoading"
            element-loading-text="给我一点时间"
            :data="changeDetails.list"
            border
            fit
            highlight-current-row
            style="width: 100%;"
            :row-style="rowStyle"
            :cell-style="cellStyle"
            class="elTable table-fixed"
            :span-method="objectSpanMethod"
          >
            <el-table-column label="栏舍" prop="barname" min-width="70px" align="center" class-name="small-padding fixed-width" fixed="left" />
            <el-table-column label="班次" prop="times" min-width="70px" align="center" class-name="small-padding fixed-width" fixed="left" />
            <el-table-column label="调节前班次重量" prop="weight" min-width="70px" align="center" />
            <el-table-column label="调节后班次重量" prop="weightafter" min-width="100px" align="center" />
            <el-table-column label="调节前理论干物质量" prop="ftweight" min-width="70px" align="center" />
            <el-table-column label="调节后理论干物质量" prop="ftweightafter" min-width="90px" align="center" />
            <el-table-column label="调节前采样干物质量" prop="cyweight" min-width="70px" align="center" />
            <el-table-column label="调节后采样干物质量" prop="cyweightafter" min-width="90px" align="center" />
            <el-table-column label="调节前日投喂量" prop="totalweight" min-width="70px" align="center" />
            <el-table-column label="调节后日投喂量" prop="totalweightafter" min-width="100px" align="center" />
          </el-table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer" style="bottom: 10px;">
        <el-button class="cancelClose" @click="closeDialog();">取消</el-button>
        <el-button class="save" @click="changeDetails.dialogFormVisible=false;samplingSelection.frequencyList = []">上一步</el-button>
        <el-button class="save" @click="handleNextLast()">下一步</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { GetDataByName, GetDataByNames, ExecDataByConfig } from '@/api/common'
import { parseTime, handleTableSpan, handleObjectSpanMethod } from '@/utils/index.js'
import Cookies from 'js-cookie'
import { MessageBox } from 'element-ui'
export default {
  name: 'RevisePlan',
  components: {},
  props: {
    show: { type: Boolean, default: false }
  },
  data() {
    return {
      dialogFull: false,
      visible: this.show,
      dialogFormVisible: false,
      dialogStatus: '',
      balconicFormulaListParm: {
        name: 'getFTSWList',
        page: 1,
        offset: 1,
        pagecount: 0,
        returntype: 'Map',
        parammaps: {
          pastureid: Cookies.get('pastureid')
        }
      },
      balconicFormulaList: [],
      temp: {
        ftid: ''
      },

      samplingSelection: {
        dialogFormVisible: false,
        dialogStatus: '',
        dateList: [],
        getdateListParm: {
          name: 'getftdrydatelist',
          offset: 0,
          pagecount: 30,
          parammaps: { pastureid: Cookies.get('pastureid') }
        },
        requestParams: [
          { name: 'getBarListEnable', offset: 0, pagecount: 0, parammaps: { 'pastureid': Cookies.get('pastureid') }},
          { name: 'getSysoptEnable', offset: 0, pagecount: 0, parammaps: { 'pastureid': Cookies.get('pastureid'), 'inforname': 'times' }}
        ],
        houseNameList: [], // 栏舍名称
        frequencyList: [], // 班次
        getdataListParm: {
          name: 'getftdrycylist',
          page: 1,
          offset: 1,
          pagecount: 0,
          returntype: 'Map',
          parammaps: {
            pastureid: Cookies.get('pastureid'),
            ftid: '',
            date: '',
            barid: '',
            times: ''
          }
        },
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true
      },
      changeDetails: {
        dialogFormVisible: false,
        dialogStatus: '',
        getdataListParm: {
          name: 'getftdryafterlist',
          page: 1,
          offset: 1,
          pagecount: 0,
          returntype: 'Map',
          parammaps: {
            pastureid: Cookies.get('pastureid'),
            ftid: '',
            actweight: '',
            thoweight: ''
          }
        },
        tableKey: 1,
        list: [],
        total: 0,
        listLoading: true,
        spanObj: {},
        mergekeys: ['barname', 'ftweight', 'ftweightafter', 'cyweight', 'cyweightafter', 'totalweight', 'totalweightafter']
      },

      textMap: {
        samplingSelection: '干物质调节—采样选择',
        changeDetails: '干物质调节—变化详情'
      },
      selectionList: [],
      isokDisable: false,
      requestParam: {},
      rowStyle: { maxHeight: 30 + 'px', height: 30 + 'px' },
      cellStyle: { padding: 0 + 'px' }
    }
  },
  watch: {
    // 监听show,visible 随着show变化而变化
    show: {
      immediate: true,
      handler(show) {
        this.visible = show
      }
    }
  },
  created() {

  },
  methods: {
    restTemp() {
      this.temp.ftid = ''
    },
    getBalconicFormula() {
      GetDataByName(this.balconicFormulaListParm).then(response => {
        console.log('栏舍配方数据', response.data.list)
        if (response.data.list !== null) {
          this.balconicFormulaList = response.data.list
        } else {
          this.balconicFormulaList = []
        }
      })
    },
    closeDialog() {
      this.$emit('update:show', false) // 子组件更新弹框隐藏
      this.dialogFull = false
      this.samplingSelection.dialogFormVisible = false
      this.changeDetails.dialogFormVisible = false
      this.samplingSelection.frequencyList = []
    },
    handleNextSamplingSelection() {
      this.dialogFull = false
      if (this.temp.ftid !== '') {
        this.samplingSelection.dialogStatus = 'samplingSelection'
        this.samplingSelection.dialogFormVisible = true
        this.getSamplingDateList()
        this.getSamplingSelectionDownList()
      } else {
        this.$message({ type: 'error', message: '选择需调节配方', duration: 2000 })
      }
    },
    getSamplingSelectionDownList() {
      GetDataByNames(this.samplingSelection.requestParams).then(response => {
        this.samplingSelection.houseNameList = response.data.getBarListEnable.list
        if (response.data.getSysoptEnable.list !== null) {
          for (let i = 1; i <= response.data.getSysoptEnable.list[0].inforvalue; i++) {
            const obj = {}
            obj.id = String(i)
            if (i == 1) { obj.name = '第一班' } else if (i == 2) { obj.name = '第二班' } else if (i == 3) { obj.name = '第三班' } else if (i == 4) { obj.name = '第四班' }
            this.samplingSelection.frequencyList.push(obj)
          }
        } else {
          this.samplingSelection.frequencyList = []
        }
      })
    },
    getSamplingDateList() {
      this.samplingSelection.getdateListParm.parammaps.ftid = this.temp.ftid
      GetDataByName(this.samplingSelection.getdateListParm).then(response => {
        if (response.data.list !== null) {
          this.samplingSelection.dateList = response.data.list
          this.samplingSelection.getdataListParm.parammaps.date = response.data.list[0].date
        } else {
          this.samplingSelection.dateList = []
          this.samplingSelection.getdataListParm.parammaps.date = ''
        }
        this.getListSamplingSelection()
      })
    },
    form_search() {
      this.getListSamplingSelection()
    },
    handleSelectionChange(item) {
      this.selectionList = item
    },
    getListSamplingSelection() {
      this.samplingSelection.listLoading = true
      this.samplingSelection.getdataListParm.parammaps.ftid = this.temp.ftid
      GetDataByName(this.samplingSelection.getdataListParm).then(response => {
        console.log('table数据', response.data.list)
        if (response.data.list !== null) {
          this.samplingSelection.list = response.data.list
          this.samplingSelection.pageNum = response.data.pageNum
          this.samplingSelection.pageSize = response.data.pageSize
          this.samplingSelection.total = response.data.total
        } else {
          this.samplingSelection.list = []
        }
        setTimeout(() => {
          this.samplingSelection.listLoading = false
        }, 100)
      })
    },
    handleNextChangeDetails() {
      this.dialogFull = false
      if (this.selectionList.length == 1) {
        this.changeDetails.dialogStatus = 'changeDetails'
        this.changeDetails.dialogFormVisible = true
        this.getListChangeDetails()
      } else {
        if (this.selectionList.length == 0) {
          this.$message({ type: 'error', message: '请选择采样内容对应干物质比例调节', duration: 2000 })
        } else {
          this.$message({ type: 'error', message: '仅可选择一条采样内容进行调节', duration: 2000 })
        }
      }
    },
    // 干物质调节—变化详情
    getListChangeDetails() {
      this.changeDetails.listLoading = true
      this.changeDetails.getdataListParm.parammaps.ftid = this.temp.ftid
      this.changeDetails.getdataListParm.parammaps.actweight = this.selectionList[0].actweight
      this.changeDetails.getdataListParm.parammaps.thoweight = this.selectionList[0].thoweight
      console.log(this.changeDetails.getdataListParm.parammaps)
      GetDataByName(this.changeDetails.getdataListParm).then(response => {
        console.log('table数据', response.data.list)
        if (response.data.list !== null) {
          this.changeDetails.list = response.data.list
          this.changeDetails.pageNum = response.data.pageNum
          this.changeDetails.pageSize = response.data.pageSize
          this.changeDetails.total = response.data.total
          this.handleSpan()
        } else {
          this.changeDetails.list = []
        }
        setTimeout(() => {
          this.changeDetails.listLoading = false
        }, 100)
      })
    },
    handleSpan() {
      this.changeDetails.mergekeys.forEach(key => {
        this.changeDetails.spanObj[key] = []
        let position = 0
        this.changeDetails.list.forEach((item, index) => {
          if (index === 0) {
            this.changeDetails.spanObj[key].push(1)
            position = 0
          } else {
            if (key == 'ftweight' || key == 'ftweightafter' || key == 'cyweight' || key == 'cyweightafter' || key == 'totalweight' || key == 'totalweightafter') {
              if (this.changeDetails.list[index][key] === this.changeDetails.list[index - 1][key] && this.changeDetails.list[index]['barname'] === this.changeDetails.list[index - 1]['barname']) {
                this.changeDetails.spanObj[key][position] += 1
                this.changeDetails.spanObj[key].push(0)
              } else {
                this.changeDetails.spanObj[key].push(1)
                position = index
              }
            } else {
              if (this.changeDetails.list[index][key] === this.changeDetails.list[index - 1][key]) {
                this.changeDetails.spanObj[key][position] += 1
                this.changeDetails.spanObj[key].push(0)
              } else {
                this.changeDetails.spanObj[key].push(1)
                position = index
              }
            }
          }
        })
      })
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      for (let i = 0; i < this.changeDetails.mergekeys.length; i++) {
        if (column.property === this.changeDetails.mergekeys[i]) {
          const _row = this.changeDetails.spanObj[this.changeDetails.mergekeys[i]][rowIndex]
          const _col = _row > 0 ? 1 : 0
          return {
            rowspan: _row,
            colspan: _col
          }
        }
      }
    },
    handleNextLast() {
      MessageBox.confirm('是否确认进行当前干物质调节操作', '提示', {
        confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
        // beforeClose: (action, instance, done) => {
        //   console.log(action, instance, done)
        //   this.closeDialog()
        //   done()
        // }
      }).then(() => {
        var duplicateRemovalList = []
        for (let i = 0; i < this.changeDetails.list.length; i++) {
          for (var j = i + 1; j < this.changeDetails.list.length; j++) {
            if (this.changeDetails.list[i].id == this.changeDetails.list[j].id) {
              ++i
            }
          }
          duplicateRemovalList.push(this.changeDetails.list[i])
        }
        console.log(duplicateRemovalList, '=duplicateRemovalList')
        this.requestParam = {}
        this.requestParam.common = { 'returnmap': '0' }
        this.requestParam.data = []
        this.requestParam.data[0] = { 'name': 'saveFPFTdryChange', 'type': 'e', 'parammaps': {
          pastureid: Cookies.get('pastureid'),
          ftid: this.temp.ftid,
          actweight: this.selectionList[0].actweight,
          thoweight: this.selectionList[0].thoweight
        }}
        this.requestParam.data[1] = { 'name': 'insertSpotList', 'resultmaps': { 'list': duplicateRemovalList }}
        this.requestParam.data[1].children = []
        this.requestParam.data[1].children[0] = { 'name': 'updateLPPbyFPChange', 'type': 'e', 'parammaps': {
          pastureid: '@insertSpotList.pastureid',
          fpid: '@insertSpotList.id'
        }}
        ExecDataByConfig(this.requestParam).then(response => {
          console.log('新生成保存发送参数', this.requestParam)
          if (response.msg === 'fail') {
            this.$notify({ title: '保存失败', message: response.data, type: 'warning', duration: 2000 })
          } else {
            this.$notify({ title: '', message: '保存成功', type: 'success', duration: 2000 })
            this.closeDialog()
            this.$emit('getIsDisplay')
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
