<template>
  <!-- 保温箱管理 -->
  <div class="home">
    <actionBar :operateList="operateList" :formList="formList" :ruleForm="searchRuleForm" @openModel="openModel"
      @searchProtocol="searchProtocol"></actionBar>
    <div class="card_content">
      <!-- 表单 -->
      <tables :tableList="tableList" :tableData="tableData" @buttonData="buttonData"></tables>
      <!-- 分页 -->
      <div v-if="Total">
        <pagination :total="Total" :currentPage="Pagination.PageIndex" @changeSize="changeSize"
          @changeCurrent="changeCurrent">
        </pagination>
      </div>
    </div>
    <el-dialog :title="staffTitle" :visible.sync="staffDialogVisible" width="600px" :close-on-click-modal="false"
      @close="closeDialog">
      <forms ref="childRules" :formNewList="formRuleList" :ruleForm="ruleForm" labelWidth="110px"
        @handleScroll="handleScroll" @remoteMethod="remoteMethod"></forms>
      <span slot="footer" class="dialog-footer" v-if="operationType != 'logs'">
        <el-button plain @click="staffDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="confirmLoading" @click="handleAdd">确 定</el-button>
      </span>
    </el-dialog>
    <div class="management_card">
      <el-dialog :visible.sync="importDialogVisible" width="600px" :close-on-click-modal="false" @close="closeDialogil">
        <div class="card_import">
          <div class="card_incubat">
            <forms ref="incubatorRules" labelPosition="left" :formNewList="stateRuleList" :ruleForm="stateRuleForm"
              labelWidth="110px"></forms>
          </div>
          <div class="card_search_input">
            <div class="title_search">名称：</div>
            <el-input v-model="nameTitle" placeholder="请输入内容" @input="incubatorInput"></el-input>
          </div>
          <!-- 表单 -->
          <tables ref="refIncubator" :tableList="incubatorList" :tableData="incubatorData"></tables>
          <!-- 分页 -->
          <div v-if="Total">
            <pagination :total="Total1" :currentPage="Paginationil.PageIndex" :pager-countnum="5"
              layout="sizes, prev, pager, next" @changeSize="changeSizeil" @changeCurrent="changeCurrentil">
            </pagination>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button plain @click="importDialogVisible = false">取 消</el-button>
          <el-button type="primary" :loading="incubatorLoading" @click="incubatorAdd">导 入</el-button>
        </span>
      </el-dialog>
    </div>

    <el-dialog top="5vh" :visible.sync="dialogVisible" width="80%" @close="temperatureClose">
      <template slot="title">
        <div class="pciker_time" style="display: flex;align-items: center;">
          <span style="margin-right: 10px;font-size: 20px;color: #fff;">温湿度记录</span>
          <el-date-picker v-model="timeQuantum" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange"
            :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
            align="center" @change="timeChange">
          </el-date-picker>
        </div>
      </template>
      <thermography ref="thermo" :waybillNo="waybillNo" :timeData="timeQuantum"></thermography>
    </el-dialog>
    <!-- <centerControl ref="control"></centerControl> -->
  </div>
</template>

<script>
  import {
    getIceRaft,
  } from '@/api/freezer'
  import {
    getCoolerBox,
    addCoolerBox,
    putCoolerBox,
    delCoolerBox,
    getDevice,
    addCoolerBoxImport
  } from '@/api/incubator'
  import {
    getTemperature
  } from '@/api/waybill'
  import actionBar from '@/components/actionBar'
  import tables from '@/components/tables'
  import pagination from '@/components/pagination'
  import forms from '@/components/forms'
  import thermography from '@/components/thermography'
  // import centerControl from '@/components/centerControl'
  import {
    formRules,
    employee,
    incubator,
    historyRecord,
  } from "./incubator.js";
  import {
    startStatus,
    iceraftStatus
  } from '@/assets/js/blockSort'
  export default {
    name: 'IncubatorManagement',
    components: {
      actionBar,
      tables,
      pagination,
      forms,
      thermography,
      // centerControl
    },
    data() {
      return {
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        timeQuantum: [this.getTime(new Date(new Date().toLocaleDateString())), this.getTime(new Date())],

        operateList: [{
            type: 'add',
            title: '添加保温箱',
            icon: 'el-icon-plus',
          }, {
            type: 'import',
            title: '冷链平台导入',
            icon: 'el-icon-upload',
          },
          // {
          //   type: 'screen',
          //   title: '中控大屏',
          //   icon: 'el-icon-position',
          //   colour: 'success'
          // },
        ],
        formList: [{
          type: 'input',
          label: '名称',
          field: 'name',
          placeholder: '名称',
        }, {
          type: 'input',
          label: 'SN',
          field: 'sn',
          placeholder: 'SN',
        }, {
          type: 'select',
          label: '状态',
          field: 'status',
          placeholder: '请选择状态',
          options: iceraftStatus(),
        }],
        searchRuleForm: {
          name: '',
          sn: '',
          status: '',
        },
        searchValue: {},
        Pagination: {
          PageIndex: 1,
          PageSize: 10,
        },
        Total: 0,
        tableData: [],
        operationType: '',
        tableList: [],
        staffTitle: '添加',
        staffDialogVisible: false,
        formRuleList: [],
        ruleForm: {
          name: '',
          sn: '',
          status: '2',
        },
        confirmLoading: false,
        selectingData: {},
        importDialogVisible: false,
        incubatorList: incubator(),
        incubatorData: [],
        Total1: 0,
        Paginationil: {
          PageIndex: 1,
          PageSize: 10,
        },
        stateRuleData: [{
          field: 'cold_temperatures',
          label: '预冷温度(℃)',
          placeholder: '请输入预冷温度(℃)',
          type: 'input',
          colWidth: 24,
          rules: [{
            required: true,
            message: '请输入预冷温度(℃)',
            trigger: 'blur'
          }]
        }, {
          field: 'cold_spots',
          label: '预冷地点',
          placeholder: '请输入预冷地点',
          type: 'input',
          colWidth: 24,
          rules: [{
            required: true,
            message: '请输入预冷地点',
            trigger: 'blur'
          }]
        }, {
          field: 'status',
          label: '状态',
          placeholder: '状态',
          type: 'radio',
          colWidth: 24,
          rules: [{
            required: true,
            message: '选择状态',
            trigger: 'change'
          }],
          options: startStatus()
        }],
        stateRuleList: [],
        stateRuleForm: {
          status: '2',
        },
        nameTitle: '',
        incubatorLoading: false,

        timer: null, //定时器名称
        dialogVisible: false,
        waybillNo: '',
        iceTracingVisible: false,
        value1: '',
        // 历史记录
        historyList: historyRecord(),
        historyData: [],
        historyTotal: 0,
        historyPagination: {
          PageIndex: 1,
          PageSize: 10,
        },
        userList: {},

        icePagination: {
          PageIndex: 1,
          PageSize: 10,
        },
        iceTotal: 0,
        staffName: '',
        limitNo: true,
      }
    },
    beforeDestroy() {
      clearInterval(this.timer); // 清除定时器
      this.timer = null;
    },
    mounted() {
      const arr = localStorage.getItem('userList')
      this.userList = JSON.parse(arr)
      if (this.userList.dept.isCoolerReleaseCold) {
        const dataList = formRules();
        this.formRuleList = dataList;
        this.stateRuleList = this.stateRuleData
        this.tableList = employee()
      } else {
        const dataList = formRules();
        const tablearr = employee();
        this.formRuleList = removePointById(dataList, ['cold_spots', 'iceBinding', 'for_cold_cooler_time',
          'cold_temperatures'
        ])
        this.stateRuleList = removePointById(this.stateRuleData, ['cold_spots', 'iceBinding', 'for_cold_cooler_time',
          'cold_temperatures'
        ])
        this.tableList = removePointById(tablearr, ['cold_spots', 'iceBinding', 'for_cold_cooler_time',
          'cold_temperatures'
        ])
      }

      function removePointById(arr1, arr2) {
        for (let i = 0; i < arr2.length; i++) {
          for (let j = 0; j < arr1.length; j++) {
            if (arr2[i] == arr1[j].field) {
              let indexs = arr1.indexOf(arr1[j]);
              arr1.splice(indexs, 1);
            }
          }
        }
        return arr1
      }
      this.getList()
    },
    methods: {
      download() {
        getTemperature().then(response => {
          if (response.fileName) {
            this.pdfDialogVisible = false
            //fileName = decodeURIComponent(filename);//对filename进行转码
            let fileName = decodeURI(response.fileName);
            if (window.navigator.msSaveOrOpenBlob) {
              navigator.msSaveBlob(new Blob([response.data]), fileName);
            } else {
              let url = window.URL.createObjectURL(new Blob([response.data]));
              let link = document.createElement('a');
              link.style.display = 'none';
              link.href = url;
              link.setAttribute('download', fileName);
              document.body.appendChild(link);
              link.click();
            }
          } else {
            this.$message.error('未获取到文件名');
          }
        })
      },
      getTime(time) {
        var date = new Date(time)
        var y = date.getFullYear()
        var m = date.getMonth() + 1
        m = m < 10 ? '0' + m : m
        var d = date.getDate()
        d = d < 10 ? '0' + d : d
        var h = date.getHours()
        h = h < 10 ? '0' + h : h
        var minute = date.getMinutes()
        minute = minute < 10 ? '0' + minute : minute
        var s = date.getSeconds()
        s = s < 10 ? '0' + s : s
        return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + s
      },
      // 搜索
      searchProtocol(value) {
        this.searchValue = value
        this.getList()
      },
      // 获取保温箱列表
      getList() {
        var params = {
          page: this.Pagination.PageIndex,
          pageSize: this.Pagination.PageSize,
          showTemp: true,
          ...this.searchValue
        }
        getCoolerBox(params).then(res => {
          if (res.code == 200) {
            this.tableData = res.data.list
            this.Total = res.data.count
            this.timer = setTimeout(() => {
              this.getList();
              clearInterval(this.timer); // 清除定时器
              this.timer = null;
            }, 60000)
          }
        })
      },
      // 选项赋值
      optionMatching(value, field) {
        this.formRuleList.forEach((item, index) => {
          if (item.field == field) {
            item.options = value
          }
        })
      },
      // 弹窗表单添加
      handleAdd() {
        let flag = this.$refs['childRules'].validateForm();
        if (flag) {
          if (this.operationType == 'add') {
            this.confirmLoading = true
            var params = {
              ...this.ruleForm
            }
            params.for_cold_cooler_time = Number(this.ruleForm.for_cold_cooler_time)
            addCoolerBox(params).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.getList()
                this.staffDialogVisible = false
              }
              this.confirmLoading = false
            }).catch(() => {
              this.confirmLoading = false
            })
          } else if (this.operationType == 'edit') {
            this.confirmLoading = true
            var params = {
              id: this.selectingData.id,
              name: this.ruleForm.name,
              sn: this.ruleForm.sn,
              status: this.ruleForm.status,
              cold_spots: this.ruleForm.cold_spots,
              cold_temperatures: this.ruleForm.cold_temperatures,
              for_cold_cooler_time: Number(this.ruleForm.for_cold_cooler_time),
            }
            console.log(params, 23)
            putCoolerBox(params).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.getList()
              }
              this.staffDialogVisible = false
              this.confirmLoading = false
            }).catch(() => {
              this.confirmLoading = false
            })
          }
        } else {
          this.$message.error('表单信息不完整，请继续填写完整');
        }
      },
      buttonData(row, type) {
        this.selectingData = row
        this.operationType = type
        if (type == 'edit') {
          this.staffTitle = '编辑'
          this.staffDialogVisible = true
          if (this.userList.dept.isCoolerReleaseCold) {
            this.obtainIceRaft()
          }
          setTimeout(() => {
            this.$nextTick(() => {
              this.ruleForm = JSON.parse(JSON.stringify(row))
            })
          })
        } else if (type == 'del') {
          this.deleteUser(row.id)
        } else if (type == 'logs') {
          this.staffTitle = '详情'
          this.staffDialogVisible = true
          this.formRuleList.forEach((item, index) => {
            item.disabled = true
          })
          this.ruleForm = JSON.parse(JSON.stringify(row))
        } else if (type == 'record') {
          this.dialogVisible = true
          this.waybillNo = row.sn
          this.$nextTick(() => {
            this.$refs.thermo.getProbe()
          })
        } else if (type == 'ascend') {
          this.iceTracingVisible = true
        }
      },
      // 选择时间
      timeChange() {
        this.$nextTick(() => {
          this.$refs.thermo.getTemperature()
        })
      },
      openModel(type) {
        if (type == 'add') {
          this.staffTitle = '添加'
          this.staffDialogVisible = true
          this.operationType = type
          if (this.userList.dept.isCoolerReleaseCold) {
            this.obtainIceRaft()
          }
        } else if (type == 'import') {
          this.importDialogVisible = true
          this.getDeviceList()
        } else if (type == 'screen') {
          // this.$refs.control.controlVisible = true
          // this.$nextTick(() => {
          //   setTimeout(() => {
          //     this.$refs.control.keyUpSearch()
          //     this.$refs.control.getList()
          //   }, 100)
          // })
        }
      },
      // 触底事件
      handleScroll() {
        if (this.limitNo) {
          this.obtainIceRaft()
        }
      },
      // 搜索
      remoteMethod(value, type) {
        this.resetSelect(type)
        this.staffName = value
        this.obtainIceRaft()
      },
      // 重置选择冰排
      resetSelect(type) {
        this.formRuleList.forEach(item => {
          if (item.field == type) {
            item.options = []
          }
        })
        this.icePagination.PageIndex = 1
        this.limitNo = true
        this.staffName = ''
      },
      // 获取冰排列表
      obtainIceRaft() {
        var params = {
          page: this.icePagination.PageIndex,
          pageSize: 10,
          code: this.staffName,
        }
        getIceRaft(params).then(res => {
          if (res.code == 200) {
            let arr = res.data.list
            let arrList = []
            arr.forEach(item1 => {
              var arrData = {
                label: null,
                value: null,
              }
              arrData.label = item1.code
              arrData.value = item1.code
              // arrData.value = item1.id
              arrList.push(arrData)
            })
            if (this.limitNo == true) {
              this.formRuleList.forEach(item => {
                if (item.field == 'iceBinding') {
                  item.options = item.options.concat(arrList);
                  let some = [];
                  item.options.forEach(el => {
                    if (!some.some(e => e.value == el.value)) {
                      some.push(el)
                    }
                  })
                  item.options = some
                }
              })
            }
            if (arrList.length >= 10) {
              this.icePagination.PageIndex = ++this.icePagination.PageIndex;
            } else {
              // 已经没数据了 不需要增加数据
              this.limitNo = false;
            }
          }
        })
      },
      // 获取设备列表
      getDeviceList() {
        var params = {
          page: this.Paginationil.PageIndex,
          pageSize: this.Paginationil.PageSize,
          name: this.nameTitle,
        }
        getDevice(params).then(res => {
          if (res.code == 200) {
            this.incubatorData = res.data.list
            this.Total1 = res.data.count
          }
        })
      },
      // 搜索保温箱
      incubatorInput(value) {
        this.nameTitle = value
        this.getDeviceList()
      },
      // 批量导入保温箱
      incubatorAdd() {
        const arrID = this.$refs.refIncubator.waybillIds
        let arr1 = []
        arrID.forEach(item => {
          let arr2 = {
            sn: item.T_sn,
            name: item.T_devName,
          }
          arr1.push(arr2)
        })
        let flag = this.$refs['incubatorRules'].validateForm();
        if (flag) {
          if (arr1.length > 0) {
            this.incubatorLoading = true
            let params = {
              list: arr1,
              ...this.stateRuleForm,
            }
            addCoolerBoxImport(params).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.getList()
                this.importDialogVisible = false
              }
              this.incubatorLoading = false
            }).catch(() => {
              this.incubatorLoading = false
            })
          } else {
            this.$message.warning('请选择需要导入的保温箱');
          }
        } else {
          this.$message.error('表单信息不完整，请继续填写完整');
        }
      },
      // 删除保温箱
      deleteUser(id) {
        this.$confirm('此操作将永久删除该保温箱, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delCoolerBox({
            id: id,
          }).then(res => {
            if (res.code == 200) {
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              const precisePage = Math.ceil((this.Total - 1) / this.Pagination.PageSize)
              this.Pagination.PageIndex = this.Pagination.PageIndex > precisePage ? precisePage : this
                .Pagination.PageIndex
              this.Pagination.PageIndex = this.Pagination.PageIndex < 1 ? 1 : this.Pagination.PageIndex
              this.getList()
            }
          })
        }).catch(() => {});
      },
      changeSize(val) {
        this.Pagination.PageSize = val
        this.getList()
      },
      changeCurrent(val) {
        this.Pagination.PageIndex = val
        this.getList()
      },
      changeSizeil(val) {
        this.Paginationil.PageSize = val
        this.getDeviceList()
      },
      changeCurrentil(val) {
        this.Paginationil.PageIndex = val
        this.getDeviceList()
      },
      // 清空表单
      closeDialog() {
        this.formRuleList.forEach((item, index) => {
          item.disabled = false
        })
        this.ruleForm = {}
        this.$refs.childRules.resetCheck();
      },
      // 关闭温湿度记录
      temperatureClose() {
        this.timeQuantum = [this.getTime(new Date(new Date().toLocaleDateString())), this.getTime(new Date())]
      },
      closeDialogil() {
        this.$refs.incubatorRules.resetCheck();
        this.$refs.refIncubator.clearSelected();
      }
    }
  }
</script>

<style lang="scss" scoped>
  .card_check_title {
    display: flex;
    align-items: center;
  }

  .icon_import {
    margin-right: 5px;
    font-size: 20px;
  }

  .card_import {
    margin-top: 15px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    border-radius: 10px;
  }

  .management_card ::v-deep .el-dialog__body {
    padding: 0px 20px !important;
  }

  .card_incubat {
    padding-left: 15px;
    padding-right: 15px;
    border-bottom: 1px solid #EBEEF5;
    padding-top: 15px;
    margin-bottom: 15px;
  }

  .card_search_input {
    display: flex;
    align-items: center;
    padding: 15px 20px 15px 20px;
    border-bottom: 1px solid #EBEEF5;
  }

  .title_search {
    flex: none;
    margin-right: 5px;
  }
</style>
