<template>
  <div class="key-dm-wrapper">
    <Tabs v-model="activeTab" @on-click="handleTabChange">
      <!-- 人员分类管理 -->
      <TabPane label="人员分类管理" name="userCategory">
        <div class="search-div">
          <Row type="flex" :gutter="16">
            <Col span="6">
              <span>分类名称：</span>
              <Input v-model="filters.userCategory.catgory_name" placeholder="请输入" style="width: 70%" />
            </Col>
            <Col span="12" class="text-right">
              <Button type="primary" class="mr10" @click="handleSearch('userCategory')">搜索</Button>
              <Button class="mr10" @click="handleReset('userCategory')">重置</Button>
              <Button type="success" @click="openAddModal('userCategory')">新增</Button>
            </Col>
          </Row>
        </div>
        <Table border :loading="loading.userCategory" :columns="userCategoryColumns" :data="tables.userCategory">
          <template slot="action" slot-scope="{ row }">
            <Button size="small" type="primary" class="mr5" @click="openEditModal('userCategory', row)">修改</Button>
            <Button size="small" type="warning" class="mr5" @click="openPermissionModal(row)">权限配置</Button>
            <Poptip confirm title="确认删除？" transfer @on-ok="handleDelete('userCategory', row)">
              <Button size="small" type="error">删除</Button>
            </Poptip>
          </template>
        </Table>
        <Page
          class="page_style"
          :total="pagers.userCategory.totalRecord"
          :current="pagers.userCategory.pageNo"
          :page-size="pagers.userCategory.pageSize"
          show-total
          show-sizer
          @on-change="pageChange('userCategory', $event)"
          @on-page-size-change="sizeChange('userCategory', $event)"
        />
      </TabPane>

      <!-- 假种管理 -->
      <TabPane label="假种管理" name="leaveType">
        <div class="search-div">
          <Row type="flex" :gutter="16">
            <Col span="6">
              <span>类型名称：</span>
              <Input v-model="filters.leaveType.type_name" placeholder="请输入" style="width: 70%" />
            </Col>
            <Col span="6">
              <span>类型编码：</span>
              <Input v-model="filters.leaveType.type_code" placeholder="请输入" style="width: 70%" />
            </Col>
            <Col span="12" class="text-right">
              <Button type="primary" class="mr10" @click="handleSearch('leaveType')">搜索</Button>
              <Button class="mr10" @click="handleReset('leaveType')">重置</Button>
              <Button type="success" @click="openAddModal('leaveType')">新增</Button>
            </Col>
          </Row>
        </div>
        <Table border :loading="loading.leaveType" :columns="leaveTypeColumns" :data="tables.leaveType">
          <template slot="action" slot-scope="{ row }">
            <Button size="small" type="primary" class="mr5" @click="openEditModal('leaveType', row)">修改</Button>
            <Poptip confirm title="确认删除？" transfer @on-ok="handleDelete('leaveType', row)">
              <Button size="small" type="error">删除</Button>
            </Poptip>
          </template>
        </Table>
        <Page
          class="page_style"
          :total="pagers.leaveType.totalRecord"
          :current="pagers.leaveType.pageNo"
          :page-size="pagers.leaveType.pageSize"
          show-total
          show-sizer
          @on-change="pageChange('leaveType', $event)"
          @on-page-size-change="sizeChange('leaveType', $event)"
        />
      </TabPane>

      <!-- 办公用品分类管理 -->
      <TabPane label="办公用品分类管理" name="materialCategory">
        <div class="search-div">
          <Row type="flex" :gutter="16">
            <Col span="6">
              <span>分类名称：</span>
              <Input v-model="filters.materialCategory.category_Name" placeholder="请输入" style="width: 70%" />
            </Col>
            <Col span="6">
              <span>分类编码：</span>
              <Input v-model="filters.materialCategory.category_Code" placeholder="请输入" style="width: 70%" />
            </Col>
            <Col span="12" class="text-right">
              <Button type="primary" class="mr10" @click="handleSearch('materialCategory')">搜索</Button>
              <Button class="mr10" @click="handleReset('materialCategory')">重置</Button>
              <Button type="success" @click="openAddModal('materialCategory')">新增</Button>
            </Col>
          </Row>
        </div>
        <Table border :loading="loading.materialCategory" :columns="materialCategoryColumns" :data="tables.materialCategory">
          <template slot="action" slot-scope="{ row }">
            <Button size="small" type="primary" class="mr5" @click="openEditModal('materialCategory', row)">修改</Button>
            <Poptip confirm title="确认删除？" transfer @on-ok="handleDelete('materialCategory', row)">
              <Button size="small" type="error">删除</Button>
            </Poptip>
          </template>
        </Table>
        <Page
          class="page_style"
          :total="pagers.materialCategory.totalRecord"
          :current="pagers.materialCategory.pageNo"
          :page-size="pagers.materialCategory.pageSize"
          show-total
          show-sizer
          @on-change="pageChange('materialCategory', $event)"
          @on-page-size-change="sizeChange('materialCategory', $event)"
        />
      </TabPane>

      <!-- 办公用品管理 -->
      <TabPane label="办公用品管理" name="material">
        <div class="search-div">
          <Row type="flex" :gutter="16">
            <Col span="6">
              <span>物料名称：</span>
              <Input v-model="filters.material.material_name" placeholder="请输入" style="width: 70%" />
            </Col>
            <Col span="6">
              <span>物料编码：</span>
              <Input v-model="filters.material.material_code" placeholder="请输入" style="width: 70%" />
            </Col>
            <Col span="6">
              <span>分类：</span>
              <Select v-model="filters.material.category_id" clearable style="width: 70%">
                <Option v-for="cat in materialCategoryOptions" :key="cat.id" :value="cat.id">{{ cat.category_Name }}</Option>
              </Select>
            </Col>
            <Col span="6" class="text-right">
              <Button type="primary" class="mr10" @click="handleSearch('material')">搜索</Button>
              <Button class="mr10" @click="handleReset('material')">重置</Button>
              <Button type="success" @click="openAddModal('material')">新增</Button>
              <Button type="primary" class="mr10" v-if="showImport()" @click="importShow = true">导入</Button>
            </Col>
          </Row>
        </div>
        <Table border :loading="loading.material" :columns="materialColumns" :data="tables.material">
          <template slot="action" slot-scope="{ row }">
            <Button size="small" type="primary" class="mr5" @click="openEditModal('material', row)">修改</Button>
            <Poptip confirm title="确认删除？" transfer @on-ok="handleDelete('material', row)">
              <Button size="small" type="error">删除</Button>
            </Poptip>
          </template>
        </Table>
        <Page
          class="page_style"
          :total="pagers.material.totalRecord"
          :current="pagers.material.pageNo"
          :page-size="pagers.material.pageSize"
          show-total
          show-sizer
          @on-change="pageChange('material', $event)"
          @on-page-size-change="sizeChange('material', $event)"
        />
      </TabPane>
    </Tabs>

    <!-- 人员分类管理弹窗 -->
    <Modal v-model="modals.userCategory.visible" :title="modals.userCategory.isEdit ? '修改人员分类' : '新增人员分类'" width="600" :mask-closable="false">
      <Form :label-width="120" :model="modals.userCategory.form" :rules="modals.userCategory.rules" ref="userCategoryForm">
        <FormItem label="分类名称" prop="catgory_name">
          <Input v-model="modals.userCategory.form.catgory_name" placeholder="请输入分类名称" />
        </FormItem>
        <FormItem label="描述" prop="remark">
          <Input type="textarea" :rows="3" v-model="modals.userCategory.form.remark" placeholder="请输入描述" />
        </FormItem>
        <FormItem label="排序号" prop="order_no">
          <InputNumber v-model="modals.userCategory.form.order_no" :min="0" style="width: 100%" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="modals.userCategory.visible = false">取消</Button>
        <Button type="primary" :loading="modals.userCategory.saving" @click="handleSave('userCategory')">保存</Button>
      </div>
    </Modal>
    <!-- 导入物料弹窗 -->
    <Modal v-model="importShow" title="物料导入" width="360">
      <Row type="flex" justify="center" align="middle">
        <Col span="10">
          <div style="text-align: center;">
            <Upload
              :show-upload-list="false"
              :before-upload="handleBeforeUpload"
              :format="['xls','xlsx']"
              accept=".xls,.xlsx"
              :max-size="4096">
              <Button icon="ios-cloud-upload-outline" type="primary" :loading="impBtnDisabled">导入</Button>
            </Upload>
          </div>
        </Col>
        <Col span="12">
          <div style="text-align: center;">
            <Button type="primary" @click="tplDownload" style="margin-right: 10px;">下载模板</Button>
          </div>
        </Col>
      </Row>
      <div slot="footer">
        <Button size="large" type="text" @click="importShow = false">关闭</Button>
      </div>
    </Modal>

    <!-- 假种管理弹窗 -->
    <Modal v-model="modals.leaveType.visible" :title="modals.leaveType.isEdit ? '修改请假类型' : '新增请假类型'" width="700" :mask-closable="false">
      <Form :label-width="120" :model="modals.leaveType.form" :rules="modals.leaveType.rules" ref="leaveTypeForm">
        <Row :gutter="16">
          <Col span="12">
            <FormItem label="类型编码" prop="type_code">
              <Input v-model="modals.leaveType.form.type_code" placeholder="请输入类型编码" />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="类型名称" prop="type_name">
              <Input v-model="modals.leaveType.form.type_name" placeholder="请输入类型名称" />
            </FormItem>
          </Col>
        </Row>
        <FormItem label="类型描述" prop="remark">
          <Input type="textarea" :rows="3" v-model="modals.leaveType.form.remark" placeholder="请输入类型描述" />
        </FormItem>
        <Row :gutter="16">
          <Col span="12">
            <FormItem label="基准天数" prop="base_days">
              <InputNumber v-model="modals.leaveType.form.base_days" :min="0" :precision="2" style="width: 100%" />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="年度上限" prop="max_days_per_year">
              <InputNumber v-model="modals.leaveType.form.max_days_per_year" :min="0" :precision="2" style="width: 100%" />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="12">
            <FormItem label="需要审批">
              <Select v-model="modals.leaveType.form.need_approval" style="width: 100%">
                <Option :value="1">需要</Option>
                <Option :value="0">不需要</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="排序号" prop="order_no">
              <InputNumber v-model="modals.leaveType.form.order_no" :min="0" style="width: 100%" />
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button @click="modals.leaveType.visible = false">取消</Button>
        <Button type="primary" :loading="modals.leaveType.saving" @click="handleSave('leaveType')">保存</Button>
      </div>
    </Modal>

    <!-- 办公用品分类管理弹窗 -->
    <Modal v-model="modals.materialCategory.visible" :title="modals.materialCategory.isEdit ? '修改办公用品分类' : '新增办公用品分类'" width="600" :mask-closable="false">
      <Form :label-width="120" :model="modals.materialCategory.form" :rules="modals.materialCategory.rules" ref="materialCategoryForm">
        <FormItem label="分类编码" prop="category_Code">
          <Input v-model="modals.materialCategory.form.category_Code" placeholder="请输入分类编码" />
        </FormItem>
        <FormItem label="分类名称" prop="category_Name">
          <Input v-model="modals.materialCategory.form.category_Name" placeholder="请输入分类名称" />
        </FormItem>
        <FormItem label="分类描述" prop="remark">
          <Input type="textarea" :rows="3" v-model="modals.materialCategory.form.remark" placeholder="请输入分类描述" />
        </FormItem>
        <FormItem label="排序号" prop="order_no">
          <InputNumber v-model="modals.materialCategory.form.order_no" :min="0" style="width: 100%" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="modals.materialCategory.visible = false">取消</Button>
        <Button type="primary" :loading="modals.materialCategory.saving" @click="handleSave('materialCategory')">保存</Button>
      </div>
    </Modal>

    <!-- 办公用品管理弹窗 -->
    <Modal v-model="modals.material.visible" :title="modals.material.isEdit ? '修改办公用品' : '新增办公用品'" width="800" :mask-closable="false">
      <Form :label-width="120" :model="modals.material.form" :rules="modals.material.rules" ref="materialForm">
        <Row :gutter="16">
          <Col span="12">
            <FormItem label="分类" prop="category_id">
              <Select v-model="modals.material.form.category_id" placeholder="请选择分类" style="width: 100%">
                <Option v-for="cat in materialCategoryOptions" :key="cat.id" :value="cat.id">{{ cat.category_Name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="物料编码" prop="material_code">
              <Input v-model="modals.material.form.material_code" placeholder="请输入物料编码" />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="12">
            <FormItem label="物料名称" prop="material_name">
              <Input v-model="modals.material.form.material_name" placeholder="请输入物料名称" />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="规格型号" prop="material_spec">
              <Input v-model="modals.material.form.material_spec" placeholder="请输入规格型号" />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="12">
            <FormItem label="单位" prop="unit">
              <Input v-model="modals.material.form.unit" placeholder="请输入单位" />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="单价" prop="unit_price">
              <InputNumber v-model="modals.material.form.unit_price" :min="0" :precision="4" style="width: 100%" />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="12">
            <FormItem label="存储位置" prop="storage_location">
              <Input v-model="modals.material.form.storage_location" placeholder="请输入存储位置" />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="物料状态" prop="status">
              <Select v-model="modals.material.form.status" style="width: 100%">
                <Option :value="0">报废</Option>
                <Option :value="1">使用</Option>
                <Option :value="2">待修</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="12">
            <FormItem label="最低库存" prop="min_stock">
              <InputNumber v-model="modals.material.form.min_stock" :min="0" :precision="4" style="width: 100%" />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="最高库存" prop="max_stock">
              <InputNumber v-model="modals.material.form.max_stock" :min="0" :precision="4" style="width: 100%" />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="12">
            <FormItem label="是否可领用" prop="can_borrow">
              <Select v-model="modals.material.form.can_borrow" style="width: 100%">
                <Option :value="0">消耗品</Option>
                <Option :value="1">可领用</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="排序号" prop="order_no">
              <InputNumber v-model="modals.material.form.order_no" :min="0" style="width: 100%" />
            </FormItem>
          </Col>
        </Row>
        <FormItem label="物料描述" prop="material_desc">
          <Input type="textarea" :rows="3" v-model="modals.material.form.material_desc" placeholder="请输入物料描述" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="modals.material.visible = false">取消</Button>
        <Button type="primary" :loading="modals.material.saving" @click="handleSave('material')">保存</Button>
      </div>
    </Modal>

    <!-- 权限配置弹窗 -->
    <Modal v-model="permissionModal.visible" title="权限配置" width="600" :mask-closable="false">
      <Form :label-width="120">
        <FormItem label="分类名称">
          <Input :value="permissionModal.categoryName" disabled />
        </FormItem>
        <FormItem label="权限配置">
          <Select v-model="permissionModal.selectedPermissions" multiple clearable filterable placeholder="请选择权限">
            <Option v-for="opt in permissionOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</Option>
          </Select>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="permissionModal.visible = false">取消</Button>
        <Button type="primary" :loading="permissionModal.saving" @click="savePermission">保存</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  getUserCategoryList,
  saveUserCategory,
  deleteUserCategory,
  getLeaveTypeList,
  saveLeaveType,
  deleteLeaveType,
  getMaterialCategoryList,
  saveMaterialCategory,
  deleteMaterialCategory,
  getMaterialList,
  saveMaterial,
  deleteMaterial,
  getUserCategoryPermissionList,
  saveUserCategoryPermission,
  importMaterial,
  materialTemplateDownload
} from '@/api/key-dm'
import { getDictList } from '@/api/common'

export default {
  name: 'key-dm-index',
  data () {
    return {
      activeTab: 'userCategory',
      filters: {
        userCategory: { catgory_name: '' },
        leaveType: { type_name: '', type_code: '' },
        materialCategory: { category_Name: '', category_Code: '' },
        material: { material_name: '', material_code: '', category_id: '' }
      },
      tables: {
        userCategory: [],
        leaveType: [],
        materialCategory: [],
        material: []
      },
      loading: {
        userCategory: false,
        leaveType: false,
        materialCategory: false,
        material: false
      },
      pagers: {
        userCategory: { pageNo: 1, pageSize: 10, totalRecord: 0 },
        leaveType: { pageNo: 1, pageSize: 10, totalRecord: 0 },
        materialCategory: { pageNo: 1, pageSize: 10, totalRecord: 0 },
        material: { pageNo: 1, pageSize: 10, totalRecord: 0 }
      },
      modals: {
        userCategory: {
          visible: false,
          isEdit: false,
          saving: false,
          form: {
            id: '',
            catgory_name: '',
            remark: '',
            order_no: 0
          },
          rules: {
            catgory_name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
          }
        },
        leaveType: {
          visible: false,
          isEdit: false,
          saving: false,
          form: {
            id: '',
            type_code: '',
            type_name: '',
            remark: '',
            base_days: 0,
            max_days_per_year: 0,
            need_approval: 1,
            order_no: 0
          },
          rules: {
            type_code: [{ required: true, message: '请输入类型编码', trigger: 'blur' }],
            type_name: [{ required: true, message: '请输入类型名称', trigger: 'blur' }]
          }
        },
        materialCategory: {
          visible: false,
          isEdit: false,
          saving: false,
          form: {
            id: '',
            category_Code: '',
            category_Name: '',
            remark: '',
            order_no: 0
          },
          rules: {
            category_Code: [{ required: true, message: '请输入分类编码', trigger: 'blur' }],
            category_Name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
          }
        },
        material: {
          visible: false,
          isEdit: false,
          saving: false,
          form: {
            id: '',
            category_id: '',
            material_code: '',
            material_name: '',
            material_spec: '',
            unit: '',
            unit_price: 0,
            storage_location: '',
            min_stock: 0,
            max_stock: 0,
            status: 1,
            can_borrow: 1,
            material_desc: '',
            order_no: 0
          },
          rules: {
            category_id: [{ required: true, message: '请选择分类', trigger: 'change' }],
            material_name: [{ required: true, message: '请输入物料名称', trigger: 'blur' }]
          }
        }
      },
      permissionModal: {
        visible: false,
        saving: false,
        categoryId: '',
        categoryName: '',
        selectedPermissions: []
      },
      importShow: false,
      impBtnDisabled: false,
      permissionOptions: [],
      materialCategoryOptions: [],
      userCategoryColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '分类名称', key: 'catgory_name', align: 'center' },
        { title: '描述', key: 'remark', align: 'center' },
        { title: '权限', key: 'permission_names', align: 'center', minWidth: 200 },
        { title: '排序号', key: 'order_no', align: 'center', width: 100 },
        { title: '操作', slot: 'action', align: 'center', width: 250, fixed: 'right' }
      ],
      leaveTypeColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '类型编码', key: 'type_code', align: 'center' },
        { title: '类型名称', key: 'type_name', align: 'center' },
        { title: '基准天数', key: 'base_days', align: 'center', width: 100 },
        { title: '需要审批', key: 'need_approval', align: 'center', width: 100, render: (h, { row }) => h('span', row.need_approval === 1 ? '需要' : '不需要') },
        { title: '排序号', key: 'order_no', align: 'center', width: 100 },
        { title: '操作', slot: 'action', align: 'center', width: 180, fixed: 'right' }
      ],
      materialCategoryColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '分类编码', key: 'category_Code', align: 'center' },
        { title: '分类名称', key: 'category_Name', align: 'center' },
        { title: '分类描述', key: 'remark', align: 'center' },
        { title: '排序号', key: 'order_no', align: 'center', width: 100 },
        { title: '操作', slot: 'action', align: 'center', width: 180, fixed: 'right' }
      ],
      materialColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '分类', key: 'category_name', align: 'center' },
        { title: '物料编码', key: 'material_code', align: 'center' },
        { title: '物料名称', key: 'material_name', align: 'center' },
        { title: '规格型号', key: 'material_spec', align: 'center' },
        { title: '单位', key: 'unit', align: 'center', width: 80 },
        { title: '单价', key: 'unit_price', align: 'center', width: 100 },
        { title: '物料状态',
          key: 'status',
          align: 'center',
          width: 100,
          render: (h, { row }) => {
            const statusMap = { 0: '报废', 1: '使用', 2: '待修' }
            return h('span', statusMap[row.status] || '-')
          } },
        { title: '操作', slot: 'action', align: 'center', width: 180, fixed: 'right' }
      ]
    }
  },
  created () {
    this.loadPermissionDict()
    this.loadMaterialCategoryOptions()
    this.fetchList(this.activeTab)
  },
  methods: {
    handleTabChange (name) {
      this.activeTab = name
      this.fetchList(name)
    },
    fetchList (tab) {
      const apiMap = {
        userCategory: getUserCategoryList,
        leaveType: getLeaveTypeList,
        materialCategory: getMaterialCategoryList,
        material: getMaterialList
      }
      const api = apiMap[tab]
      if (!api) return
      this.loading[tab] = true
      const payload = Object.assign({}, this.pagers[tab], this.filters[tab])
      api(payload).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          const data = ret.data.data || {}
          this.tables[tab] = data.results || []
          // 如果是人员分类，加载每行的权限名称并拼接显示
          if (tab === 'userCategory' && Array.isArray(this.tables[tab]) && this.tables[tab].length > 0) {
            const rows = this.tables[tab]
            // 并行查询每个分类的权限配置（可优化为批量接口）
            const promises = rows.map(r => {
              return getUserCategoryPermissionList({ category_id: r.id }).then(res => {
                let names = ''
                if (res.data && res.data.errcode === 0) {
                  const list = res.data.data || res.data.results || []
                  names = (Array.isArray(list) ? list.map(it => it.permission_name).filter(Boolean) : []).join(',')
                }
                // 确保响应式设置字段
                this.$set(r, 'permission_names', names)
                return r
              }).catch(() => {
                this.$set(r, 'permission_names', '')
                return r
              })
            })
            Promise.all(promises).then(() => { /* table updated */ })
          }
          this.pagers[tab].totalRecord = data.totalRecord || 0
        } else {
          this.$Notice.error({ title: '查询失败', desc: ret.data.errmsg || '请稍后重试' })
        }
      }).finally(() => { this.loading[tab] = false })
    },
    handleSearch (tab) {
      this.pagers[tab].pageNo = 1
      this.fetchList(tab)
    },
    handleReset (tab) {
      const resetMap = {
        userCategory: () => ({ catgory_name: '' }),
        leaveType: () => ({ type_name: '', type_code: '' }),
        materialCategory: () => ({ category_Name: '', category_Code: '' }),
        material: () => ({ material_name: '', material_code: '', category_id: '' })
      }
      this.filters[tab] = resetMap[tab]()
      this.pagers[tab].pageNo = 1
      this.fetchList(tab)
    },
    pageChange (tab, pageNo) {
      this.pagers[tab].pageNo = pageNo
      this.fetchList(tab)
    },
    sizeChange (tab, size) {
      this.pagers[tab].pageSize = size
      this.pagers[tab].pageNo = 1
      this.fetchList(tab)
    },
    openAddModal (tab) {
      const modal = this.modals[tab]
      modal.visible = true
      modal.isEdit = false
      this.$nextTick(() => {
        modal.form = this.getDefaultForm(tab)
      })
    },
    openEditModal (tab, row) {
      const modal = this.modals[tab]
      modal.visible = true
      modal.isEdit = true
      this.$nextTick(() => {
        modal.form = Object.assign({}, this.getDefaultForm(tab), row)
      })
    },
    getDefaultForm (tab) {
      const defaults = {
        userCategory: {
          id: '',
          catgory_name: '',
          remark: '',
          order_no: 0
        },
        leaveType: {
          id: '',
          type_code: '',
          type_name: '',
          remark: '',
          base_days: 0,
          max_days_per_year: 0,
          need_approval: 1,
          order_no: 0
        },
        materialCategory: {
          id: '',
          category_Code: '',
          category_Name: '',
          remark: '',
          order_no: 0
        },
        material: {
          id: '',
          category_id: '',
          material_code: '',
          material_name: '',
          material_spec: '',
          unit: '',
          unit_price: 0,
          storage_location: '',
          min_stock: 0,
          max_stock: 0,
          status: 1,
          can_borrow: 1,
          material_desc: '',
          order_no: 0
        }
      }
      return JSON.parse(JSON.stringify(defaults[tab]))
    },
    handleSave (tab) {
      const modal = this.modals[tab]
      const formRef = this.$refs[tab + 'Form']
      if (!formRef) return
      formRef.validate(valid => {
        if (!valid) return
        modal.saving = true
        const saveApiMap = {
          userCategory: saveUserCategory,
          leaveType: saveLeaveType,
          materialCategory: saveMaterialCategory,
          material: saveMaterial
        }
        const api = saveApiMap[tab]
        api(modal.form).then(ret => {
          if (ret.data && ret.data.errcode === 0) {
            this.$Message.success('保存成功')
            modal.visible = false
            this.fetchList(tab)
          } else {
            this.$Notice.error({ title: '保存失败', desc: ret.data.errmsg || '请稍后重试' })
          }
        }).finally(() => { modal.saving = false })
      })
    },
    handleDelete (tab, row) {
      const deleteApiMap = {
        userCategory: deleteUserCategory,
        leaveType: deleteLeaveType,
        materialCategory: deleteMaterialCategory,
        material: deleteMaterial
      }
      const api = deleteApiMap[tab]
      api({ id: row.id }).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.$Message.success('删除成功')
          this.fetchList(tab)
        } else {
          this.$Notice.error({ title: '删除失败', desc: ret.data.errmsg || '请稍后重试' })
        }
      })
    },
    openPermissionModal (row) {
      this.permissionModal.visible = true
      this.permissionModal.categoryId = row.id
      this.permissionModal.categoryName = row.catgory_name
      this.permissionModal.selectedPermissions = []
      // 加载已有权限
      getUserCategoryPermissionList({ category_id: row.id }).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          const list = ret.data.data || ret.data.results || []
          this.permissionModal.selectedPermissions = list.map(item => item.permission_mark).filter(Boolean)
        }
      })
    },
    savePermission () {
      if (!this.permissionModal.categoryId) {
        this.$Message.warning('分类ID不存在')
        return
      }
      this.permissionModal.saving = true
      const permissions = Array.isArray(this.permissionModal.selectedPermissions) ? this.permissionModal.selectedPermissions : []
      const permissionList = permissions.map(mark => {
        const opt = this.permissionOptions.find(p => p.value === mark)
        return {
          category_id: this.permissionModal.categoryId,
          permission_mark: mark,
          permission_name: opt ? opt.label : mark
        }
      })
      saveUserCategoryPermission({
        category_id: this.permissionModal.categoryId,
        permissions: permissionList
      }).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.$Message.success('保存成功')
          this.permissionModal.visible = false
          this.fetchList('userCategory')
        } else {
          this.$Notice.error({ title: '保存失败', desc: ret.data.errmsg || '请稍后重试' })
        }
      }).finally(() => { this.permissionModal.saving = false })
    },
    loadPermissionDict () {
      // 从字典获取权限选项，字典类型为 daily_manage_dict_permission
      getDictList({ type: 'daily_manage_dict_permission' }).then(res => {
        if (res.data && res.data.errcode === 0) {
          const results = res.data.data && res.data.data.results ? res.data.data.results : []
          this.permissionOptions = results.map(it => ({
            label: it.label || it.name || '',
            value: it.value || it.dictValue || ''
          })).filter(it => it.label && it.value)
        }
      })
    },
    loadMaterialCategoryOptions () {
      getMaterialCategoryList({ pageNo: 1, pageSize: 1000, params: {} }).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          const data = ret.data.data || {}
          console.log('getMaterialCategoryList', data)
          // this.materialCategoryOptions = data.results || []
          const raw = data.results || []
          // 规范化后端字段名，确保 id 字段为小写 id，以便 Select v-model 绑定正常工作
          this.materialCategoryOptions = Array.isArray(raw) ? raw.map(it => ({
            id: (it.Id || it.id || it.category_Code || '').toString(),
            category_Name: (it.category_Name || it.categoryName || it.category_Code || '')
          })) : []
        }
      })
    },
    tplDownload () {
      // 下载物料导入模板
      materialTemplateDownload({}).then(ret => {
        if (ret && ret.data && ret.data.errcode === 0) {
          // const data = ret.data.data
          // 如果后端直接返回文件流需要采用 axios blob 下载，这里假设返回 url 或 blob handled by backend
          // 简单提示或可实现下载逻辑
          this.$Notice.success({ title: '模板已准备，请在后台下载' })
        } else {
          this.$Notice.error({ title: '模板下载失败', desc: ret.data && ret.data.errmsg })
        }
      }).catch(() => {
        this.$Notice.error({ title: '模板下载失败' })
      })
    },
    handleBeforeUpload (file) {
      const fileExt = file.name.split('.').pop().toLocaleLowerCase()
      if (fileExt === 'xlsx' || fileExt === 'xls') {
        this.readFile(file)
      } else {
        this.$Notice.warning({
          title: '文件类型错误',
          desc: '文件：' + file.name + '不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。'
        })
      }
      return false
    },
    async readFile (file) {
      this.impBtnDisabled = true
      const formdata = new FormData()
      formdata.append('file', file)
      formdata.append('fileName', file.name)
      const ret = await importMaterial(formdata)

      if (ret && ret.data) {
        this.importShow = false
        this.impBtnDisabled = false
        const mobj = ret.data.data || {}
        let msg = '添加' + (mobj.insert || 0) + '条, 更新' + (mobj.update || 0) + '条'
        if (mobj.error) {
          msg += ', 缺少关键信息未能导入' + mobj.error + '条'
        }
        if (mobj.errInfo && mobj.errInfo !== '') {
          msg += ', 以下记录导入失败：' + mobj.errInfo
        }
        if (ret.data.errmsg && ret.data.errmsg !== 'success') {
          msg += ret.data.errmsg
        }
        if ((mobj.insert || 0) + (mobj.update || 0) > 0) {
          this.fetchList('material')
        }
        this.$Notice.success({
          title: '导入完成！',
          desc: msg
        })
      } else {
        this.impBtnDisabled = false
        this.$Notice.warning({
          title: '未导入数据！',
          desc: ret && ret.data && ret.data.errmsg
        })
      }
    },
    showImport () {
      // 简单权限控制：可根据需要替换
      const info = this.$store.state.user.otherUserInfo || {}
      const areaId = info.area_id || ''
      if (areaId && areaId.startsWith('2201')) return true
      return false
    }
  }
}
</script>

<style scoped>
.key-dm-wrapper {
  padding: 10px;
}
.search-div {
  border: 1px solid #dce1e7;
  padding: 15px;
  margin-bottom: 15px;
  background-color: #f8fbff;
}
.mr5 {
  margin-right: 5px;
}
.mr10 {
  margin-right: 10px;
}
.text-right {
  text-align: right;
}
.page_style {
  margin-top: 12px;
  text-align: right;
}
</style>
