<template>
  <div v-if="visible">
    <!--{{$t('message.msg87')}} -->
    <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;
              "
            />
            {{ $t('message.msg87') }}
          </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">{{ $t('message.msg88') }}</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()">{{
          $t('formulationEvaluation.cancel')
        }}</el-button>
        <el-button class="save" @click="handleNextSamplingSelection()">{{
          $t('message.msg96')
        }}</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="$t('InventoryManagement.rq')"
            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="$t('errorAnalysis.isHouseName')"
            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="$t('errorAnalysis.isTrainNumber')"
            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">{{
            $t('common.query')
          }}</el-button>
        </div>
        <div class="table" style="margin-top: 10px">
          <el-table
            :key="samplingSelection.tableKey"
            v-loading="samplingSelection.listLoading"
            :element-loading-text="$t('common.tableMsg')"
            :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="$t('formulationEvaluation.xh')"
              align="center"
              type="index"
              width="50px"
            />
            <el-table-column
              :label="$t('errorAnalysis.isHouseName')"
              prop="barname"
              min-width="110px"
              align="center"
            />
            <el-table-column
              :label="$t('errorAnalysis.isTrainNumber')"
              prop="times"
              min-width="110px"
              align="center"
            />
            <el-table-column
              :label="$t('message.msg89')"
              prop="freshweight"
              min-width="110px"
              align="center"
            />
            <el-table-column
              :label="$t('message.msg90')"
              prop="dryweight"
              min-width="110px"
              align="center"
            />
            <el-table-column
              :label="$t('message.msg91')"
              prop="thoweight"
              min-width="110px"
              align="center"
            />
            <el-table-column
              :label="$t('message.msg92')"
              prop="actweight"
              min-width="110px"
              align="center"
            />
            <el-table-column
              :label="$t('performance.czr')"
              prop="emp"
              min-width="110px"
              align="center"
            />
            <el-table-column
              :label="$t('message.msg93')"
              prop="operatetime"
              min-width="110px"
              align="center"
            />
          </el-table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer" style="bottom: 10px">
        <el-button @click="closeDialog()">{{
          $t('formulationEvaluation.cancel')
        }}</el-button>
        <el-button
          class="saves"
          @click="
            samplingSelection.dialogFormVisible = false
            samplingSelection.frequencyList = []
          "
          >{{ $t('message.msg95') }}</el-button
        >
        <el-button class="saves" @click="handleNextChangeDetails()">{{
          $t('message.msg96')
        }}</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="$t('common.tableMsg')"
            :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="$t('errorAnalysis.pen')"
              prop="barname"
              min-width="70px"
              align="center"
              class-name="small-padding fixed-width"
              fixed="left"
            />
            <el-table-column
              :label="$t('errorAnalysis.isTrainNumber')"
              prop="times"
              min-width="70px"
              align="center"
              class-name="small-padding fixed-width"
              fixed="left"
            />
            <el-table-column
              :label="$t('message.msg97')"
              prop="weight"
              min-width="70px"
              align="center"
            />
            <el-table-column
              :label="$t('message.msg98')"
              prop="weightafter"
              min-width="100px"
              align="center"
            />
            <el-table-column
              :label="$t('message.msg99')"
              prop="ftweight"
              min-width="70px"
              align="center"
            />
            <el-table-column
              :label="$t('message.msg100')"
              prop="ftweightafter"
              min-width="90px"
              align="center"
            />
            <el-table-column
              :label="$t('message.msg101')"
              prop="cyweight"
              min-width="70px"
              align="center"
            />
            <el-table-column
              :label="$t('message.msg102')"
              prop="cyweightafter"
              min-width="90px"
              align="center"
            />
            <el-table-column
              :label="$t('message.msg103')"
              prop="totalweight"
              min-width="70px"
              align="center"
            />
            <el-table-column
              :label="$t('message.msg104')"
              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()">{{
          $t('formulationEvaluation.cancel')
        }}</el-button>
        <el-button
          class="saves"
          @click="
            changeDetails.dialogFormVisible = false
            samplingSelection.frequencyList = []
          "
          >{{ $t('message.msg95') }}</el-button
        >
        <el-button @click="handleNextLast()" class="saves">{{
          $t('message.msg96')
        }}</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: this.$t('message.msg105'),
        changeDetails: this.$t('message.msg106')
      },
      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: this.$t('message.msg107'),
          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 = this.$t('message.shiftObj.1')
            } else if (i == 2) {
              obj.name = this.$t('message.shiftObj.2')
            } else if (i == 3) {
              obj.name = this.$t('message.shiftObj.3')
            } else if (i == 4) {
              obj.name = this.$t('message.shiftObj.4')
            } else if (i == 5) {
              obj.name = this.$t('message.shiftObj.5')
            } else if (i == 6) {
              obj.name = this.$t('message.shiftObj.6')
            }
            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: this.$t('message.msg108'),
            duration: 2000
          })
        } else {
          this.$message({
            type: 'error',
            message: this.$t('message.msg109'),
            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(this.$t('message.msg110'), this.$t('message.msg111'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        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: this.$t('driver.saveFail'),
              message: response.data,
              type: 'warning',
              duration: 2000
            })
          } else {
            this.$notify({
              title: '',
              message: this.$t('driver.saveSuccess'),
              type: 'success',
              duration: 2000
            })
            this.closeDialog()
            this.$emit('getIsDisplay')
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-button {
  padding: 12px 16px;
}
.saves {
  background: #009a69;
  border-color: #009a69;
  color: #fff;
}
</style>
