<template>
  <!-- 仓库管理 -->
  <div class="home">
    <actionBar :operateList="operateList" :formList="formList" :ruleForm="searchRuleForm" @openModel="openModel"
      @searchProtocol="searchProtocol"></actionBar>
    <div class="card_content">
      <!-- 表单 -->
      <tables :suspension="true" :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="100px"></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="500px" :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="100px"></forms>
          </div>
          <div class="card_search_input">
            <el-input v-model="nameTitle" placeholder="设备名称" @input="incubatorInput"></el-input>
          </div>
          <!-- 表单 -->
          <tables ref="refIncubator" :tableList="incubatorList" :tableData="incubatorData"></tables>
          <!-- 分页 -->
          <div v-if="Total1">
            <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>
  </div>
</template>

<script>
  import {
    getSysUserBind
  } from '@/api/user'
  import {
    getWarehouse,
    getWarehouseDetails,
    addWarehouse,
    putWarehouse,
    delWarehouse,
    importWarehouse
  } from '@/api/warehouse'
  import {
    getDevice
  } from '@/api/incubator'
  import actionBar from '@/components/actionBar'
  import tables from '@/components/tables'
  import pagination from '@/components/pagination'
  import forms from '@/components/forms'
  import {
    formRules,
    employee,
    incubator
  } from "./warehouse.js";
  import {
    startStatus,
  } from '@/assets/js/blockSort'
  export default {
    name: 'StoreManagement',
    components: {
      actionBar,
      tables,
      pagination,
      forms
    },
    data() {
      return {
        operateList: [{
          type: 'add',
          title: '添加仓库',
          icon: 'el-icon-plus',
        }, {
          type: 'import',
          title: '冷链平台导入',
          icon: 'el-icon-upload',
        }],
        formList: [{
          type: 'input',
          label: '名称/管理员名称',
          field: 'name',
          placeholder: '仓库名称/管理员名称',
        }, {
          type: 'input',
          label: 'SN',
          field: 'sn',
          placeholder: 'SN',
        }],
        searchRuleForm: {
          name: '',
          sn: '',
        },
        Pagination: {
          PageIndex: 1,
          PageSize: 10,
        },
        Total: 0,
        tableData: [],
        operationType: '',
        tableList: employee(),
        tableData: [],
        staffTitle: '添加',
        staffDialogVisible: false,
        formRuleList: [],
        ruleForm: {
          name: '',
          sn: '',
          address: '',
          status: '',
          userId: '',
        },
        confirmLoading: false,
        selectingData: {},

        importDialogVisible: false,
        incubatorList: incubator(),
        incubatorData: [],
        Total1: 0,
        Paginationil: {
          PageIndex: 1,
          PageSize: 10,
        },
        stateRuleList: [{
          field: 'status',
          label: '启用状态:',
          placeholder: '启用状态:',
          type: 'radio',
          colWidth: 24,
          rules: [{
            required: true,
            message: '选择启用状态:',
            trigger: 'change'
          }],
          options: startStatus()
        }],
        stateRuleForm: {
          status: '2',
        },
        nameTitle: '',
        incubatorLoading: false,
      }
    },
    mounted() {
      this.getDriver()
      const dataList = formRules();
      this.formRuleList = dataList;
      this.getList()
    },
    methods: {
      // 搜索
      searchProtocol(value) {
        this.searchValue = value
        this.getList()
      },
      // 获取订单列表
      getList() {
        var params = {
          page: this.Pagination.PageIndex,
          pageSize: this.Pagination.PageSize,
          ...this.searchValue
        }
        getWarehouse(params).then(res => {
          if (res.code == 200) {
            this.tableData = res.data.list
            this.Total = res.data.count
          }
        })
      },
      // 获取仓库管理员列表
      getDriver() {
        getSysUserBind({
          type: 2,
        }).then(res => {
          if (res.code == 200) {
            const arrList = []
            const arr = res.data.list
            arr.forEach((item, index) => {
              const commodity = {
                label: item.nickName,
                value: item.id,
                IsBind: item.IsBind,
              }
              arrList.push(commodity)
            })
            this.optionMatching(arrList, 'userId')
          }
        })
      },
      // 选项赋值
      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.userId = Number(params.userId)
            addWarehouse(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,
              address: this.ruleForm.address,
              name: this.ruleForm.name,
              sn: this.ruleForm.sn,
              status: this.ruleForm.status,
              userId: this.ruleForm.userId,
            }
            params.userId = Number(params.userId)
            putWarehouse(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
          setTimeout(() => {
            this.$nextTick(() => {
              this.ruleForm = JSON.parse(JSON.stringify(row))
              this.ruleForm.userId = String(row.userId)
            })
          })
        } 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))
          this.ruleForm.userId = row.user.nickName
        }
      },
      openModel(type) {
        if (type == 'add') {
          this.getDriver()
          this.staffTitle = '添加'
          this.staffDialogVisible = true
          this.operationType = type
        } else if (type == 'import') {
          this.importDialogVisible = true
          this.getDeviceList()
        }
      },
      // 获取设备列表
      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,
            }
            importWarehouse(params).then(res => {
              if (res.code == 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.getList()
                this.importDialogVisible = false
              }
              this.incubatorLoading = false
            })
          } else {
            this.$message.warning('请选择需要导入的保温箱');
          }
        } else {
          this.$message.error('表单信息不完整，请继续填写完整');
        }
      },
      // 删除仓库
      deleteUser(id) {
        this.$confirm('此操作将永久删除该仓库, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delWarehouse({
            id: id,
          }).then(res => {
            if (res.code == 200) {
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              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();
      },
      closeDialogil() {
        this.$refs.incubatorRules.resetCheck();
        this.$refs.refIncubator.clearSelected();
      }
    }
  }
</script>
