<!--
 * @Descripttion: (基础资料/库位信息表/bas_bin)
 * @version: (1.0)
 * @Author: (admin)
 * @Date: (2023-04-12)
 * @LastEditors: (admin)
 * @LastEditTime: (2023-04-12)
-->
<template>
  <div>
    <el-form :model="queryParams" label-position="right" inline ref="queryRef" v-show="showSearch" @submit.prevent
      size="large">
      <el-row>
        <el-form-item label="库区" prop="regionId">
          <el-select v-model="queryParams.regionId" placeholder="请选择" clearable>
            <el-option v-for="dict in regionList" :key="dict.regionId" :label="dict.regionName" :value="dict.regionId">
              <span v-if="dict.regionName">{{ dict.regionName }}</span>
              <span v-else>（编码：{{ dict.regionCode }}）</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库位编码" prop="binId">
          <el-input v-model="queryParams.binId" placeholder="请输入库位编码" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="库位.排" prop="binRow">
          <el-input-number v-model="queryParams.binRow" @keyup.enter="handleQuery" :min="0" />
        </el-form-item>
        <el-form-item label="库位.列" prop="binColumn">
          <el-input-number v-model="queryParams.binColumn" @keyup.enter="handleQuery" :min="0" />
        </el-form-item>
        <el-form-item label="库位.层" prop="binLayer">
          <el-input-number v-model="queryParams.binLayer" @keyup.enter="handleQuery" :min="0" />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="库位类型" prop="binType">
          <el-select v-model="queryParams.binType" placeholder="请选择" clearable style="width:120px" @change="handleQuery">
            <el-option v-for="dict in options.binTypeOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue">
              <dict-tag :options="options.binTypeOptions" :value="dict.dictValue" />
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="使用标识" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择" clearable style="width:120px" @change="handleQuery">
            <el-option v-for="dict in options.statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue">
              <dict-tag :options="options.statusOptions" :value="dict.dictValue" />
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
          <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
        </el-form-item>
      </el-row>

    </el-form>
    <!-- 工具区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" v-hasPermi="['business:basbin:add']" plain icon="plus" @click="handleAdd">
          {{ $t('btn.add') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" :disabled="single" v-hasPermi="['business:basbin:edit']" plain icon="edit"
          @click="handleUpdate">
          {{ $t('btn.edit') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" :disabled="multiple" v-hasPermi="['business:basbin:delete']" plain icon="delete"
          @click="handleDelete">
          {{ $t('btn.delete') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="Printer">打印</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport"
          v-hasPermi="['business:basbin:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['business:basbin:export']">
          {{ $t('btn.export') }}
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <!-- 数据区域 -->
    <el-table :data="dataList" v-loading="loading" ref="table" highlight-current-row @sort-change="sortChange"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column prop="binId" label="ID" align="center" v-if="columns.showColumn('binId')" />
      <!-- <el-table-column prop="regionId" label="库区编码" align="center" :show-overflow-tooltip="true"
        v-if="columns.showColumn('regionId')" /> -->
      <el-table-column prop="regionName" label="库区" align="center" :show-overflow-tooltip="true"
        v-if="columns.showColumn('regionName')">
        <template #default="scope">
          <span v-if="scope.row.regionName">{{ scope.row.regionName }}</span>
          <span v-else>编码：{{ scope.row.regionCode }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="binCode" label="库位编码" align="center" :show-overflow-tooltip="true"
        v-if="columns.showColumn('binCode')" />
      <el-table-column prop="binName" label="库位名称" align="center" :show-overflow-tooltip="true"
        v-if="columns.showColumn('binName')" />
      <el-table-column prop="binType" label="库位类型" align="center" v-if="columns.showColumn('binType')">
        <template #default="scope">
          <dict-tag :options="options.binTypeOptions" :value="scope.row.binType" />
        </template>
      </el-table-column>
      <el-table-column prop="binRow" label="排" align="center" v-if="columns.showColumn('binRow')" />
      <el-table-column prop="binColumn" label="列" align="center" v-if="columns.showColumn('binColumn')" />
      <el-table-column prop="binLayer" label="层" align="center" v-if="columns.showColumn('binLayer')" />
      <el-table-column prop="describe" label="描述" align="center" :show-overflow-tooltip="true"
        v-if="columns.showColumn('describe')" />
      <el-table-column prop="visible" label="显示状态" align="center" width="80" v-if="columns.showColumn('visible')">
        <template #default="scope">
          <dict-tag :options="options.visibleOptions" :value="scope.row.visible" />
        </template>
      </el-table-column>
      <el-table-column prop="status" label="使用状态" align="center" width="80" v-if="columns.showColumn('status')">
        <template #default="scope">
          <dict-tag :options="options.statusOptions" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column prop="createBy" label="创建人" align="center" v-if="columns.showColumn('createBy')" />
      <el-table-column prop="createTime" label="创建时间" align="center" width="160"
        v-if="columns.showColumn('createTime')" />
      <el-table-column prop="updateBy" label="更新人" align="center" v-if="columns.showColumn('updateBy')" />
      <el-table-column prop="updateTime" label="更新时间" align="center" width="160"
        v-if="columns.showColumn('updateTime')" />
      <el-table-column prop="remark" label="备注" align="center" :show-overflow-tooltip="true"
        v-if="columns.showColumn('remark')" />
      <el-table-column label="操作" align="center" width="160">
        <template #default="scope">
          <el-button v-hasPermi="['business:basbin:edit']" type="success" plain icon="edit" title="编辑"
            @click="handleUpdate(scope.row)"></el-button>
          <el-button v-hasPermi="['business:basbin:delete']" type="danger" plain icon="delete" title="删除"
            @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination class="mt10" background :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改基础资料/库位信息表对话框 -->
    <el-dialog :title="title" :lock-scroll="false" v-model="open">
      <el-form ref="formRef" :model="form" :rules="rules" size="large" label-width="100">
        <el-row :gutter="20">
          <el-col :lg="12">
            <el-row :gutter="20">
              <el-col>
                <el-form-item label="库位编码" prop="binCode">
                  <el-input v-model="form.binCode" placeholder="请输入库位编码" />
                </el-form-item>
              </el-col>

              <el-col>
                <el-form-item label="库位名称" prop="binName">
                  <el-input v-model="form.binName" placeholder="请输入库位名称" />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="库区" prop="regionId">
                  <el-select v-model="form.regionId" placeholder="请选择" clearable>
                    <el-option v-for="dict in regionList" :key="dict.regionId" :label="dict.regionName"
                      :value="dict.regionId">
                      <span v-if="dict.regionName">{{ dict.regionName }}</span>
                      <span v-else>（编码：{{ dict.regionCode }}）</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="库位类型" prop="binType">
                  <el-select v-model="form.binType" placeholder="请选择库位类型">
                    <el-option v-for="dict in options.binTypeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                      :value="dict.dictValue">
                      <dict-tag :options="options.binTypeOptions" :value="dict.dictValue" />
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :lg="12">
            <el-row :gutter="20">
              <el-col>
                <el-form-item label="库位所在排" prop="binRow">
                  <el-input-number v-model="form.binRow" placeholder="请输入" />
                </el-form-item>
              </el-col>

              <el-col>
                <el-form-item label="库位所在列" prop="binColumn">
                  <el-input-number v-model="form.binColumn" placeholder="请输入" />
                </el-form-item>
              </el-col>

              <el-col>
                <el-form-item label="库位所在层" prop="binLayer">
                  <el-input-number v-model="form.binLayer" placeholder="请输入" />
                </el-form-item>
              </el-col>

              <el-col>
                <el-form-item label="显示状态" prop="visible">
                  <el-radio-group v-model="form.visible">
                    <el-radio-button v-for="item in options.visibleOptions" :key="item.dictValue"
                      :label="item.dictValue">{{
                        item.dictLabel }}</el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>

              <el-col>
                <el-form-item label="使用状态" prop="status">
                  <el-radio-group v-model="form.status">
                    <el-radio-button v-for="item in options.statusOptions" :key="item.dictValue"
                      :label="item.dictValue">{{
                        item.dictLabel }}</el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>

            </el-row>
          </el-col>
          <el-col :lg="24">
            <el-form-item label="描述" prop="describe">
              <el-input type="textarea" v-model="form.describe" placeholder="请输入描述" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer v-if="opertype != 3">
        <el-button text @click="cancel">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="submitForm">{{ $t('btn.submit') }}</el-button>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload name="file" ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <!-- <div class="el-upload__tip">
                  <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
                </div> -->
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="upload.open = false">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="submitFileForm">{{ $t('btn.submit') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="basbin">
import {
  listBasBin, addBasBin, delBasBin, updateBasBin, getBasBin, exportBasBin,

}
  from '@/api/business/basbin.js'

import { listBasRegion } from '@/api/business/basregion';

import { formatDate } from '@vueuse/shared'

import { getToken } from "@/utils/auth";

const { proxy } = getCurrentInstance()

// 选中binId数组数组
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const loading = ref(false)
const showSearch = ref(true)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  sort: '',
  sortType: 'asc',
  regionId: undefined,
  regionName: undefined,
  binRow: undefined,
  binColumn: undefined,
  binLayer: undefined,
  binType: undefined,
  status: undefined,
})
const columns = ref([
  { visible: false, prop: 'binId', label: 'ID' },
  { visible: true, prop: 'binCode', label: '库位编码' },
  { visible: true, prop: 'binName', label: '库位名称' },
  { visible: true, prop: 'binType', label: '库位类型' },
  { visible: true, prop: 'regionName', label: '库区' },
  { visible: true, prop: 'binRow', label: '排' },
  { visible: true, prop: 'binColumn', label: '列' },
  { visible: true, prop: 'binLayer', label: '层' },
  { visible: false, prop: 'describe', label: '描述' },
  { visible: true, prop: 'visible', label: '显示状态' },
  { visible: true, prop: 'status', label: '使用状态' },
  { visible: false, prop: 'remark', label: '备注' },
  { visible: true, prop: 'createBy', label: '创建人' },
  { visible: true, prop: 'createTime', label: '创建时间' },
  { visible: true, prop: 'updateBy', label: '更新人' },
  { visible: true, prop: 'updateTime', label: '更新时间' },
])
const total = ref(0)
const dataList = ref([])
const regionList = ref([])
const queryRef = ref()
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])

/*** 导入参数 */
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/business/basbin/importData'
})

function getList() {
  loading.value = true
  listBasBin(queryParams).then(res => {
    const { code, data } = res
    if (code == 200) {
      dataList.value = data.result
      total.value = data.totalNum
      loading.value = false
    }
  })
}

function getRegion() {
  const regionQuery = reactive({
    pageNum: 1,
    //获取所有的库区，这里限制获取前100个，应该可以获取全部
    pageSize: 100,
  })
  listBasRegion(regionQuery).then(res => {
    const { code, data } = res
    if (code == 200) {
      regionList.value = data.result
    }
  })
}
// 查询
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置查询操作
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.binId);
  single.value = selection.length != 1
  multiple.value = !selection.length;
}

// 自定义排序
function sortChange(column) {
  var sort = undefined
  var sortType = undefined

  if (column.prop != null && column.order != null) {
    sort = column.prop
    sortType = column.order

  }
  queryParams.sort = sort
  queryParams.sortType = sortType
  handleQuery()
}

/*************** form操作 ***************/
const formRef = ref()
const title = ref("")
// 操作类型 1、add 2、edit 3、view
const opertype = ref(0)
const open = ref(false)
const state = reactive({
  form: {},
  rules: {
    binId: [{ required: true, message: "库位Id 系统主键不能为空", trigger: "blur", type: "number" }],
    binCode: [{ required: true, message: "库区编码不能为空", trigger: "blur" }],
    binType: [{ required: true, message: "库位类型（S存储库位，P拣选库位，V虚拟库位）不能为空", trigger: "change" }],
    regionId: [{ required: true, message: "库区编码不能为空", trigger: "blur" }],
    binRow: [{ required: true, message: "库位所在排不能为空", trigger: "blur", type: "number" }],
    binColumn: [{ required: true, message: "库位所在列不能为空", trigger: "blur", type: "number" }],
    binLayer: [{ required: true, message: "库位所在层不能为空", trigger: "blur", type: "number" }],
    visible: [{ required: true, message: "显示状态（0显示，1隐藏）不能为空", trigger: "blur" }],
    status: [{ required: true, message: "使用状态（0正常，1使用）不能为空", trigger: "blur" }],
  },
  options: {
    statusOptions: [],// 状态数据字典
    visibleOptions: [],// 显示数据字典
    binTypeOptions: [],// 库位类型字典
  }
})

const { form, rules, options } = toRefs(state)

var dictParams = [
  { dictType: 'sys_normal_disable', columnName: 'statusOptions' },
  { dictType: 'sys_show_hide', columnName: 'visibleOptions' },
  { dictType: 'my_bin_type', columnName: 'binTypeOptions' },
]
proxy.getDicts(dictParams).then((response) => {
  response.data.forEach((element) => {
    state.options[element.columnName] = element.list
  })
})

// 关闭dialog
function cancel() {
  open.value = false
  reset()
}
// 重置表单
function reset() {
  form.value = {
    binCode: undefined,
    binName: undefined,
    binType: undefined,
    regionId: undefined,
    binRow: undefined,
    binColumn: undefined,
    binLayer: undefined,
    describe: undefined,
    visible: "0",
    status: "0",
    // createBy: undefined,
    // createTime: undefined,
    // updateBy: undefined,
    // updateTime: undefined,
    remark: undefined,
  };
  proxy.resetForm("formRef")
}

// 添加按钮操作
function handleAdd() {
  reset();
  open.value = true
  title.value = '添加'
  opertype.value = 1
}

// 修改按钮操作
function handleUpdate(row) {
  reset()
  const id = row.binId || ids.value
  getBasBin(id).then((res) => {
    const { code, data } = res
    if (code == 200) {
      open.value = true
      title.value = "修改数据"
      opertype.value = 2

      form.value = {
        ...data,
      }
    }
  })
}

// 添加&修改 表单提交
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if (form.value.binId != undefined && opertype.value === 2) {
        updateBasBin(form.value).then((res) => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
          .catch(() => { })
      } else {
        addBasBin(form.value).then((res) => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
          .catch(() => { })
      }
    }
  })
}

// 删除按钮操作
function handleDelete(row) {
  const Ids = row.binId || ids.value

  proxy
    .$confirm('是否确认删除参数编号为"' + Ids + '"的数据项？')
    .then(function () {
      return delBasBin(Ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    })
    .catch(() => { })
}
// 导入按钮操作
function handleImport() {
  upload.title = '库位导入'
  upload.open = true
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs['uploadRef'].clearFiles()
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  })
  getList()
}
// 下载导入模板
function importTemplate() {
  proxy.download('/business/basbin/importTemplate', '库位数据导入模板')
}
// 提交上传文件
function submitFileForm() {
  proxy.$refs['uploadRef'].submit()
}
// 导出按钮操作
function handleExport() {
  proxy
    .$confirm('是否确认导出所有库位信息?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(function () {
      return exportBasBin(queryParams.value)
    })
    .then((response) => {
      proxy.download(response.data.path)
    })
}


handleQuery()
getRegion()

</script>
