<template>
  <div>
    <en-table-layout :tableData="tableData.data" :loading="loading">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button size="mini" v-if="checkPermission(['stock:add'])" type="primary"
            @click="handleAddWarehouse">新增</el-button>
        </div>
        <div class="toolbar-search">
          <en-table-search @search="searchEvent" placeholder="请输入关键字搜索" />
        </div>
      </div>

      <template slot="table-columns">
        <el-table-column prop="name" label="仓库名称" />
        <el-table-column prop="dept_name" label="部门名称" />
        <el-table-column prop="sn" label="仓库编号" />
        <el-table-column prop="admin_name" label="管理员" />
        <el-table-column prop="description" label="仓库说明" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" v-if="checkPermission(['stock:edit'])"
              @click="handleEditWarehouse(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" v-if="checkPermission(['stock:del'])" type="danger"
              @click="handleDeleteWarehouse(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </template>

      <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[10, 20, 50, 100]"
        :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.data_total">
      </el-pagination>
    </en-table-layout>
    <el-dialog :title="stockForm.id ? '编辑仓库' : '添加仓库'" :visible.sync="dialogVisible" width="500px"
      @open="handleDialogOpen" :modal-append-to-body="false" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="stockForm" :rules="stockRules" ref="stockForm" label-width="120px">
        <el-form-item label="所属部门" prop="dept_id">
          <el-cascader v-model="stockForm.dept_id" :options="deptList" :props="{
            label: 'name',
            value: 'id',
            emitPath: false,
            checkStrictly: true
          }" clearable></el-cascader>
        </el-form-item>
        <el-form-item label="仓库编号" prop="sn">
          <el-input v-model="stockForm.sn" :minlength="2" :maxlength="20" clearable placeholder="请输入仓库编号"></el-input>
        </el-form-item>
        <el-form-item label="仓库名称" prop="name">
          <el-input v-model="stockForm.name" :minlength="2" :maxlength="20" clearable placeholder="请输入仓库名称"></el-input>
        </el-form-item>
        <el-form-item label="管理员" prop="admin_id">
          <el-select v-model="stockForm.admin_id">
            <el-option v-for="item in adminList" :key="item.id" :label="item.real_name" :value="item.id" />
          </el-select>
          <!-- <el-input v-model="stockForm.admin" :minlength="2" :maxlength="20" clearable placeholder="请输入管理员名称"></el-input> -->
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input v-model="stockForm.description" type="textarea" :autosize="{ minRows: 3, maxRows: 4 }"
            placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitWarehouseForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as API_BasicSetting from '@/api/basicSetting'
import * as API_Setting from '@/api/setting'
import * as API_Auth from '@/api/auth'
import { Foundation } from '~/ui-utils'
import { mapGetters } from 'vuex'
export default {
  name: 'warehouse',
  data() {
    return {
      deptList: [],
      adminList: [],
      // postList: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10
      },
      // 列表数据
      tableData: '',
      // 仓库表单
      stockForm: {},
      // 仓库表单 规则
      stockRules: {
        username: [
          this.MixinRequired('请输入管理员名称！'),
          { min: 2, max: 20, message: '长度在 2 到 20 个字符' },
          {
            validator: (rule, value, callback) => {
              if (value && !RegExp.userName.test(value)) {
                callback(new Error('只支持汉字、字母、数字、“-”、“_”的组合！'))
              } else {
                callback()
              }
            }
          }],
        password: [
          { required: true, message: '请输入管理员密码！', trigger: 'bulr' },
          {
            validator: (rule, value, callback) => {
              if (value && !RegExp.password.test(value)) {
                callback(new Error('密码应为6-20位数字、英文字母，或者特殊字符！'))
              } else {
                callback()
              }
            }
          }
        ],
        department: [this.MixinRequired('请输入所属部门！')],
        role_id: [{ required: true, message: '请选择所属角色！', trigger: 'change' }],
        face: [this.MixinRequired('请上传管理员头像！')]
      },
      // 仓库表单 dialog
      dialogVisible: false
    }
  },
  mounted() {
    this.GET_WarehouseList()
    this.GET_DeptList()
    // this.GET_StationAllList()
    this.GET_AdministratorList()
  },
  computed: {
    ...mapGetters(['user'])
  },
  methods: {
    /** 获取人员列表 */
    GET_AdministratorList() {
      API_Auth.getAdministratorList({
        page_no: 1,
        page_size: 9999,
        user_state: 0
      }).then(response => {
        this.adminList = response.data
      })
    },
    // /** 获取岗位 */
    // GET_StationAllList() {
    //   API_Setting.getStationAllList().then(response => {
    //     this.postList = response
    //   })
    // },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
      })
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_WarehouseList()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_WarehouseList()
    },

    /** 添加仓库 */
    handleAddWarehouse() {
      this.stockForm = {
        founder: 0,
        real_name: '',
        password: '',
        admin_id: this.user.uid
      }
      this.dialogVisible = true
    },

    /** 编辑仓库 */
    handleEditWarehouse(index, row) {
      this.stockForm = this.MixinClone(row)
      this.dialogVisible = true
    },

    /** 删除仓库 */
    handleDeleteWarehouse(index, row) {
      this.$confirm('确定要删除这个仓库吗？', '提示', { type: 'warning' }).then(() => {
        API_BasicSetting.deleteWarehouse(row.id).then(() => {
          this.$message.success('删除成功！')
          this.GET_WarehouseList()
        })
      }).catch(() => { })
    },
    /** dialog打开后重置form表单校验结果 */
    handleDialogOpen() {
      setTimeout(() => { this.$refs['stockForm'].clearValidate() })
    },

    /** 提交仓库表单 */
    submitWarehouseForm() {
      this.$refs['stockForm'].validate((valid) => {
        if (valid) {
          const { id } = this.stockForm
          const params = this.MixinClone(this.stockForm)
          if (!params.real_name) delete params.real_name
          params.role_id === '超级仓库' ? params.role_id = 0 : null
          delete params.admin_name
          if (id) {
            API_BasicSetting.editWarehouse(id, params).then(response => {
              this.dialogVisible = false
              this.$message.success('修改成功！')
              this.GET_WarehouseList()
            })
          } else {
            API_BasicSetting.addWarehouse(params).then(() => {
              this.dialogVisible = false
              this.$message.success('添加成功！')
              this.GET_WarehouseList()
            })
          }
        } else {
          this.$message.error('表单填写有误，请核对！')
          return false
        }
      })
    },

    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        keyword: data
      }
      this.params.page_no = 1
      this.GET_WarehouseList()
    },

    /** 获取仓库列表 */
    GET_WarehouseList() {
      this.loading = true
      API_BasicSetting.getWarehouseList(this.params).then(response => {
        this.loading = false
        this.tableData = response
      }).catch(() => { this.loading = false })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}
</style>
