<!--
 * @Descripttion: (库存管理/库存明细表/stk_balance_dtl)
 * @version: (1.0)
 * @Author: (admin)
 * @Date: (2023-04-27)
 * @LastEditors: (admin)
 * @LastEditTime: (2023-04-27)
-->
<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 @change="handleQuery">
            <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="binCode">
          <el-input v-model="queryParams.binCode" placeholder="请输入" class="z-el-input" clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="库存状态" prop="status">
          <!-- <el-select v-model="queryParams.status" placeholder="请选择" clearable style="width:160px" @change="handleQuery">
            <el-option v-for="dict in options.stkStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue">
              <dict-tag :options="options.stkStatusOptions" :value="dict.dictValue" />
            </el-option>
          </el-select> -->
          <el-radio-group v-model="queryParams.status" @change="handleQuery">
            <el-radio-button>全部</el-radio-button>
            <el-radio-button v-for="dict in options.stkStatusOptions" :label="dict.dictValue">
              {{ dict.dictLabel }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="关键件标识" prop="keyFlag">
          <!-- <el-select v-model="queryParams.keyFlag" placeholder="请选择" clearable style="width:120px" @change="handleQuery">
            <el-option v-for="dict in options.keyFlagOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue">
              <dict-tag :options="options.keyFlagOptions" :value="dict.dictValue" />
            </el-option>
          </el-select> -->
          <el-radio-group v-model="queryParams.keyFlag" @change="handleQuery">
            <el-radio-button>全部</el-radio-button>
            <el-radio-button v-for="dict in options.keyFlagOptions" :label="dict.dictValue">
              {{ dict.dictLabel }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="物料编码" prop="materialCode">
          <el-input v-model="queryParams.materialCode" placeholder="请输入" class="z-el-input" clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="queryParams.materialName" placeholder="请输入" class="z-el-input" clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="物料类型" prop="category">
          <!-- <el-select v-model="queryParams.category" placeholder="请选择" clearable style="width:120px">
            <el-option v-for="dict in options.materialTypeOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue">
              <template #default="scope">
                <dict-tag :options="options.materialTypeOptions" :value="scope.row.category" />
              </template>
            </el-option>
          </el-select> -->
          <el-radio-group v-model="queryParams.category" @change="handleQuery">
            <el-radio-button>全部</el-radio-button>
            <el-radio-button v-for="dict in options.materialTypeOptions" :label="dict.dictValue">
              {{ dict.dictLabel }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="规格型号 / 图号" prop="materialSpec">
          <el-input v-model="queryParams.materialSpec" placeholder="请输入" class="z-el-input" clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="生产令号" prop="bomNo">
          <el-input v-model="queryParams.bomNo" placeholder="请输入" class="z-el-input" clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="交验单号" prop="deliverNo">
          <el-input v-model="queryParams.deliverNo" placeholder="请输入" class="z-el-input" clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="BN / SN码" prop="bnSnCode">
          <el-input v-model="queryParams.bnSnCode" placeholder="请输入" class="z-el-input" clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <!-- <el-form-item label="创建人">
          <el-input v-model="queryParams.roleName" placeholder="请输入" class="z-el-input" clearable
            @keyup.enter="handleQuery" />
        </el-form-item> -->
        <el-form-item label="创建时间">
          <el-date-picker v-model="queryCreateTime" style="width: 400px" type="datetimerange" range-separator="-"
            @change="handleQuery" start-placeholder="开始时间" end-placeholder="结束时间"></el-date-picker>
        </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:stkbalancedtl: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:stkbalancedtl: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:stkbalancedtl: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:stkbalancedtl: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="balanceId" label="ID" align="center" v-if="columns.showColumn('balanceId')" />
      <el-table-column prop="regionName" label="所在库区" align="center" 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" v-if="columns.showColumn('binCode')">
        <!-- <template #default="scope">
          <span v-if="scope.row.binCode">{{ scope.row.binCode }}</span>
          <span v-else>编码：{{ scope.row.binCode }}</span>
        </template> -->
      </el-table-column>
      <el-table-column prop="deliverNo" label="交验单号" align="center" :show-overflow-tooltip="true"
        v-if="columns.showColumn('deliverNo')" />
      <el-table-column prop="bomNo" label="生产令号" align="center" :show-overflow-tooltip="true"
        v-if="columns.showColumn('bomNo')" />
      <el-table-column prop="materialCode" label="物料编码" align="center" :show-overflow-tooltip="true"
        v-if="columns.showColumn('materialCode')" />
      <el-table-column prop="materialName" label="物料名称" align="center" :show-overflow-tooltip="true"
        v-if="columns.showColumn('materialName')" />
      <el-table-column prop="materialSpec" label="规格型号 / 图号" align="center" :show-overflow-tooltip="true"
        v-if="columns.showColumn('materialSpec')" />
      <el-table-column prop="category" label="物料类型" align="center" :show-overflow-tooltip="true"
        v-if="columns.showColumn('category')">
        <template #default="scope">
          <dict-tag :options="options.materialTypeOptions" :value="scope.row.category" />
        </template>
      </el-table-column>
      <el-table-column prop="balanceQty" label="库存数量" align="center" v-if="columns.showColumn('balanceQty')" />
      <el-table-column prop="bnSnCode" label="BN / SN码" align="center" :show-overflow-tooltip="true"
        v-if="columns.showColumn('bnSnCode')" />
      <el-table-column prop="keyFlag" label="关键件" align="center" v-if="columns.showColumn('keyFlag')">
        <template #default="scope">
          <el-icon v-if="scope.row.keyFlag" size="large" color="red">
            <StarFilled />
          </el-icon>
          <el-icon v-else />
        </template>
      </el-table-column>
      <el-table-column prop="status" label="库存状态" align="center" v-if="columns.showColumn('status')">
        <template #default="scope">
          <dict-tag :options="options.stkStatusOptions" :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:stkbalancedtl:edit']" type="success" plain icon="edit" title="编辑"
            @click="handleUpdate(scope.row)"></el-button>
          <el-button v-hasPermi="['business:stkbalancedtl: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" label-width="100px">
        <el-row :gutter="20">

          <el-col :lg="12" v-if="opertype != 1">
            <el-form-item label="ID" prop="balanceId">
              <el-input-number v-model.number="form.balanceId" controls-position="right" placeholder="请输入ID"
                :disabled="true" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="库区ID" prop="regionId">
              <el-input v-model="form.regionId" placeholder="请输入库区ID" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="库位ID" prop="binId">
              <el-input v-model="form.binId" placeholder="请输入库位ID" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="交验单号" prop="deliverNo">
              <el-input v-model="form.deliverNo" placeholder="请输入交验单号" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="生产令号" prop="bomNo">
              <el-input v-model="form.bomNo" placeholder="请输入生产令号" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="物料编码" prop="materialCode">
              <el-input v-model="form.materialCode" placeholder="请输入物料编码" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="form.materialName" placeholder="请输入物料名称" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="规格型号/图号" prop="materialSpec">
              <el-input v-model="form.materialSpec" placeholder="请输入规格型号/图号" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="物料类型" prop="category">
              <el-input v-model="form.category" placeholder="请输入物料类型" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="关键件标识" prop="keyFlag">
              <el-input v-model="form.keyFlag" placeholder="请输入关键件标识" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="BN/SN码" prop="bnSnCode">
              <el-input v-model="form.bnSnCode" placeholder="请输入BN/SN码" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="库存数量" prop="balanceQty">
              <el-input v-model="form.balanceQty" placeholder="请输入库存数量" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="库存状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="item in  options.statusOptions" :key="item.dictValue"
                  :label="parseInt(item.dictValue)">{{ item.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="创建者" prop="createBy">
              <el-input v-model="form.createBy" placeholder="请输入创建者" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker v-model="form.createTime" type="datetime" :teleported="false"
                placeholder="选择日期时间"></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="更新者" prop="updateBy">
              <el-input v-model="form.updateBy" placeholder="请输入更新者" />
            </el-form-item>
          </el-col>

          <el-col :lg="12">
            <el-form-item label="更新时间" prop="updateTime">
              <el-date-picker v-model="form.updateTime" type="datetime" :teleported="false"
                placeholder="选择日期时间"></el-date-picker>
            </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>

  </div>
</template>

<script setup name="stkbalancedtl">
import {
  listStkBalanceDtl, addStkBalanceDtl, delStkBalanceDtl, updateStkBalanceDtl, getStkBalanceDtl,

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

import { listBasRegion } from '@/api/business/basregion';
const { proxy } = getCurrentInstance()
// 选中balanceId数组数组
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const loading = ref(false)
const showSearch = ref(true)
const queryCreateTime = ref([])
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  sort: '',
  sortType: 'asc',
})
const columns = ref([
  { visible: false, prop: 'balanceId', label: 'ID' },
  { visible: true, prop: 'regionName', label: '所在库区' },
  { visible: true, prop: 'binCode', label: '所在库位' },
  { visible: false, prop: 'deliverNo', label: '交验单号' },
  { visible: false, prop: 'bomNo', label: '生产令号' },
  { visible: true, prop: 'category', label: '物料类型' },
  { visible: true, prop: 'materialCode', label: '物料编码' },
  { visible: true, prop: 'materialName', label: '物料名称' },
  { visible: true, prop: 'materialSpec', label: '规格型号/图号' },
  { visible: true, prop: 'balanceQty', label: '库存数量' },
  { visible: true, prop: 'bnSnCode', label: 'BN/SN码' },
  { visible: true, prop: 'keyFlag', label: '关键件' },
  { visible: true, prop: 'status', label: '库存状态' },
  { visible: true, prop: 'createBy', label: '创建人' },
  { visible: true, prop: 'createTime', label: '创建时间' },
  { visible: false, prop: 'updateBy', label: '更新人' },
  { visible: false, prop: 'updateTime', label: '更新时间' },
  { visible: false, prop: 'remark', 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)])


function getList() {
  loading.value = true
  listStkBalanceDtl(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
  if (queryCreateTime.value != null) {
    queryParams.beginTime = queryCreateTime.value[0]
    queryParams.endTime = queryCreateTime.value[1]
    // console.log(queryParams)
  }
  else {
    queryParams.beginTime = undefined
    queryParams.endTime = undefined
  }
  getList()
}

// 重置查询操作
function resetQuery() {
  queryCreateTime.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.balanceId);
  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: {
    regionId: [{ required: true, message: "库区ID不能为空", trigger: "blur", type: "number" }],
    binId: [{ required: true, message: "库位ID不能为空", trigger: "blur", type: "number" }],
    materialCode: [{ required: true, message: "物料编码不能为空", trigger: "blur" }],
    materialName: [{ required: true, message: "物料名称不能为空", trigger: "blur" }],
    materialSpec: [{ required: true, message: "规格型号/图号不能为空", trigger: "blur" }],
    category: [{ required: true, message: "物料类型不能为空", trigger: "blur" }],
    keyFlag: [{ required: true, message: "关键件标识不能为空", trigger: "blur" }],
    bnSnCode: [{ required: true, message: "BN/SN码不能为空", trigger: "blur" }],
    balanceQty: [{ required: true, message: "库存数量不能为空", trigger: "blur", type: "number" }],
    status: [{ required: true, message: "库存状态不能为空", trigger: "blur", type: "number" }],
  },
  options: {
    // 库存状态（0初始创建，33盘点入库占用，55在库，77盘点出库占用，99出库完成） 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
    stkStatusOptions: [],
    keyFlagOptions: [], // 关键件标识字典
    operationResultOptions: [],// 操作结果字典
    materialTypeOptions: [],// 物料类型字典
  }
})

const { form, rules, options } = toRefs(state)
var dictParams = [
  { dictType: 'my_key_flag', columnName: 'keyFlagOptions' },
  { dictType: 'my_operation_result', columnName: 'operationResultOptions' },
  { dictType: 'my_material_type', columnName: 'materialTypeOptions' },
  { dictType: 'my_stk_status', columnName: 'stkStatusOptions' },
]
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 = {
    balanceId: undefined,
    regionId: undefined,
    binId: undefined,
    deliverNo: undefined,
    bomNo: undefined,
    materialCode: undefined,
    materialName: undefined,
    materialSpec: undefined,
    category: undefined,
    keyFlag: undefined,
    bnSnCode: undefined,
    balanceQty: undefined,
    status: undefined,
    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.balanceId || ids.value
  getStkBalanceDtl(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.balanceId != undefined && opertype.value === 2) {
        updateStkBalanceDtl(form.value).then((res) => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
          .catch(() => { })
      } else {
        addStkBalanceDtl(form.value).then((res) => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
          .catch(() => { })
      }
    }
  })
}

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

  proxy
    .$confirm('是否确认删除参数编号为"' + Ids + '"的数据项？')
    .then(function () {
      return delStkBalanceDtl(Ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    })
    .catch(() => { })
}

handleQuery()
getRegion()
</script>
