<template>
  <!-- 冰排管理 -->
  <div class="home">
    <actionBar :operateList="operateList" :formList="formList" :ruleForm="searchRuleForm" @openModel="openModel"
      @searchProtocol="searchProtocol"></actionBar>
    <div class="card_content">
      <!-- 表单 -->
      <tables ref="refWaybill" :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" :iceBank="true" :iceTracing="iceTracing" :formNewList="formRuleList" :ruleForm="ruleForm"
        labelWidth="100px" @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>
</template>

<script>
  import {
    getIceRaft,
    addIceRaft,
    putIceRaft,
    delIceRaft,
    bindCoolerBox
  } from '@/api/freezer'
  import {
    getCoolerBox
  } from '@/api/incubator.js'
  import actionBar from '@/components/actionBar'
  import tables from '@/components/tables'
  import pagination from '@/components/pagination'
  import forms from '@/components/forms'
  import {
    formRules,
    formRulesCold,
    employee,
    employeeCold,
    bindingIncubator
  } from "./freezer.js";
  import {
    iceraftStatus
  } from '@/assets/js/blockSort'
  export default {
    name: 'IceManagement',
    components: {
      actionBar,
      tables,
      pagination,
      forms
    },
    data() {
      return {
        operateList: [{
          type: 'add',
          title: '添加',
          icon: 'el-icon-plus',
        }, {
          type: 'binding',
          title: '绑定冰排',
          icon: 'el-icon-link',
        }],
        formList: [{
          type: 'input',
          label: '编号',
          field: 'code',
          placeholder: '请输入编号',
        }, {
          type: 'select',
          label: '状态',
          field: 'status',
          placeholder: '请选择状态',
          options: iceraftStatus(),
        }],
        searchRuleForm: {
          code: '',
          status: '',
        },
        searchValue: {},
        Pagination: {
          PageIndex: 1,
          PageSize: 10,
        },
        Total: 0,
        tableData: [],
        operationType: '',
        tableList: [],
        staffTitle: '添加',
        staffDialogVisible: false,
        formRuleList: [],
        ruleForm: {
          code: '',
          status: null,
          freezeClaim: [],
          coolerBoxId: [],
          label: '',
          suitableForCold: null,
          forColdTime: null,
          iceColdAddress: '',
          sort: null,
        },
        confirmLoading: false,
        selectingData: {},
        iceTracing: true,
        // 是否释冷
        iceColdFlag: false,
        userList: {},
        staffName: '',
        page: 1,
        limitNoil: true,
        iceCode: [],
      }
    },
    mounted() {
      const arr = localStorage.getItem('userList')
      this.userList = JSON.parse(arr)
      if (this.userList.dept) {
        this.iceColdFlag = this.userList.dept.isIceReleaseCold
      }
      if (this.iceColdFlag) {
        this.tableList = employeeCold()
        this.formRuleList = formRulesCold()
      } else {
        this.tableList = employee()
        this.formRuleList = formRules()
      }
      this.getList()
    },
    methods: {
      // 搜索
      searchProtocol(value) {
        this.Pagination.PageIndex = 1
        this.searchValue = value
        this.getList()
      },
      // 获取列表
      getList() {
        var params = {
          page: this.Pagination.PageIndex,
          pageSize: this.Pagination.PageSize,
          ...this.searchValue
        }
        getIceRaft(params).then(res => {
          if (res.code == 200) {
            this.tableData = res.data.list
            this.Total = res.data.count
          }
        })
      },
      // 弹窗表单添加
      handleAdd() {
        let flag = this.$refs['childRules'].validateForm();
        if (flag) {
          var turnNum = function(nums) {
            let arrNum = nums
            let arr2 = []
            arrNum.forEach(item => {
              var arr1 = item.split('小时')
              arr2.push(Number(arr1[0]))
            })
            return arr2;
          }
          if (this.operationType == 'add') {
            this.confirmLoading = true
            let arr = []
            arr.push(this.ruleForm.code)
            var params = {
              codeList: arr,
              status: this.ruleForm.status,
              freezeClaim: turnNum(this.ruleForm.freezeClaim),
              label: this.ruleForm.label,
              suitableForCold: Number(this.ruleForm.suitableForCold),
              forColdTime: Number(this.ruleForm.forColdTime),
              iceColdAddress: this.ruleForm.iceColdAddress,
              sort: Number(this.ruleForm.sort),
            }
            addIceRaft(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,
              code: this.ruleForm.code,
              status: this.ruleForm.status,
              freezeClaim: turnNum(this.ruleForm.freezeClaim),
              label: this.ruleForm.label,
              suitableForCold: Number(this.ruleForm.suitableForCold),
              forColdTime: Number(this.ruleForm.forColdTime),
              iceColdAddress: this.ruleForm.iceColdAddress,
              sort: Number(this.ruleForm.sort),
            }
            putIceRaft(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 == 'binding') {
            var params = {
              code: this.iceCode,
              coolerBoxId: Number(this.ruleForm.coolerBoxId),
            }
            bindCoolerBox(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 (this.iceColdFlag) {
          this.formRuleList = formRulesCold()
        } else {
          this.formRuleList = formRules()
        }
        if (type == 'edit') {
          this.iceTracing = false
          this.staffTitle = '编辑'
          this.staffDialogVisible = true
          setTimeout(() => {
            this.$nextTick(() => {
              this.ruleForm.code = row.code
              this.ruleForm.status = row.status
              this.ruleForm.freezeClaim = row.freezeClaim.map(String);
              this.ruleForm.label = row.label
              this.ruleForm.suitableForCold = row.suitableForCold
              this.ruleForm.iceColdAddress = row.iceColdAddress
              this.ruleForm.forColdTime = row.forColdTime
              this.ruleForm.sort = row.sort
            })
          })
        } else if (type == 'logs') {
          this.iceTracing = false
          this.staffTitle = '详情'
          this.staffDialogVisible = true
          setTimeout(() => {
            this.$nextTick(() => {
              this.ruleForm.code = row.code
              this.ruleForm.status = row.status
              this.ruleForm.freezeClaim = row.freezeClaim
              this.ruleForm.label = row.label
              this.ruleForm.suitableForColdTime = row.suitableForColdTime
            })
          })
          this.formRuleList.forEach((item, index) => {
            item.disabled = true
          })
        } else if (type == 'del') {
          this.deleteUser(row.id)
        }
      },
      openModel(type) {
        this.operationType = type
        if (type == 'add') {
          this.iceTracing = true
          this.staffTitle = '添加'
          this.staffDialogVisible = true
          if (this.iceColdFlag) {
            this.formRuleList = formRulesCold()
          } else {
            this.formRuleList = formRules()
          }
        } else if (type == 'binding') {
          const arrID = this.$refs.refWaybill.waybillIds
          let arrList = []
          arrID.forEach(item => {
            arrList.push(item.code)
          })
          this.iceCode = arrList
          if (arrList.length != 0) {
            this.ruleForm.coolerBoxId = []
            this.staffDialogVisible = true
            this.staffTitle = '绑定保温箱'
            this.formRuleList = bindingIncubator()
            this.getIncubator()
          } else {
            this.$message({
              message: '请先选择需要批量操作的冰排',
              type: 'warning'
            });
          }
        }
      },
      handleScroll() {
        if (this.limitNoil) {
          this.getIncubator()
        }
      },
      remoteMethod(value) {
        this.formRuleList.forEach(item => {
          if (item.type == 'searchSelect') {
            item.options = []
          }
        })
        this.page = 1
        this.limitNoil = true
        this.staffName = value
        this.getIncubator()
      },
      // 获取保温箱列表
      getIncubator() {
        let params = {
          page: this.page,
          pageSize: 10,
          status: '2',
          name: this.staffName,
        }
        getCoolerBox(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.name
              arrData.value = item1.id
              arrList.push(arrData)
            })
            if (this.limitNoil == true) {
              this.formRuleList.forEach(item => {
                if (item.type == 'searchSelect') {
                  item.options = item.options.concat(arrList)
                }
              })
              // this.thermostat.options = this.thermostat.options.concat(arrList)
            }
            if (arrList.length >= 10) {
              this.page = ++this.page;
            } else {
              // 已经没数据了 不需要增加数据
              this.limitNoil = false;
            }
          }
        })
      },
      // 删除冰排
      deleteUser(id) {
        this.$confirm('此操作将永久删除该冰排, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delIceRaft({
            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()
      },
      // 清空表单
      closeDialog() {
        this.$refs.childRules.resetCheck();
      }
    },
  }
</script>

<style>
</style>
