<template>
  <div class="key-dm-wrapper">
    <Tabs v-model="activeTab" @on-click="handleTabChange">
      <!-- 人员权限配置 -->
      <TabPane label="人员权限配置" name="permissionConfig">
        <Table border :loading="loading.permissionConfig" :columns="permissionConfigColumns" :data="tables.permissionConfig">
          <template slot="action" slot-scope="{ row }">
            <Button size="small" type="primary" @click="openUserConfigModal(row)">配置人员</Button>
          </template>
        </Table>
      </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 type="primary" class="mr10" @click="handleReset('leaveType')">重置</Button>
              <Button type="primary" @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 type="primary" class="mr10" @click="handleReset('materialCategory')">重置</Button>
              <Button type="primary" @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 type="primary" class="mr10" @click="handleReset('material')">重置</Button>
              <Button type="primary" class="mr10" @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="importShow" title="物料导入" width="360">
      <Row type="flex" justify="center" align="middle">
        <Col span="10">
          <div style="text-align: center;">
            <Upload
               action="#"
              :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>
        <Row :gutter="16">
          <Col span="24">
            <FormItem label="供应商" prop="supplier_name">
              <Input v-model="modals.material.form.supplier_name" placeholder="请输入供应商" 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="userConfigModal.visible" title="人员权限配置" width="800" :mask-closable="false">
      <div style="margin-bottom: 16px;">
        <span style="font-weight: bold;">权限：</span>{{ userConfigModal.permissionName }}
      </div>
      <div style="margin-bottom: 16px;">
        <span style="font-weight: bold;">已配置人员：</span>
        <div style="margin-top: 8px;">
          <Tag v-for="user in userConfigModal.selectedUsers" :key="user.user_id" closable @on-close="removeUser(user)">
            {{ user.user_name }}
          </Tag>
        </div>
      </div>
      <div slot="footer">
        <Button @click="userConfigModal.visible = false">取消</Button>
        <Button type="primary" @click="addUsers">添加人员</Button>
        <Button type="primary" :loading="userConfigModal.saving" @click="saveUserConfig">保存</Button>
      </div>
    </Modal>

    <!-- 人员选择器 -->
    <UserMultiSelector
      v-model="userSelectorVisible"
      @on-ok="handleUserSelectorOk"
      @cancel="userSelectorVisible = false" />

  </div>
</template>

<script>
import {
  getLeaveTypeList,
  saveLeaveType,
  deleteLeaveType,
  getMaterialCategoryList,
  saveMaterialCategory,
  deleteMaterialCategory,
  getMaterialList,
  saveMaterial,
  deleteMaterial,
  importMaterial,
  getPermissionConfigList,
  savePermissionUsers,
  getUserDmPermissionList
} from '@/api/key-dm'
import axios from 'axios'
import UserMultiSelector from '@/view/key-person/key_dm_user/userMultiSelector.vue'

export default {
  name: 'key-dm-index',
  components: { UserMultiSelector },
  data () {
    return {
      activeTab: 'permissionConfig',
      filters: {
        leaveType: { type_name: '', type_code: '' },
        materialCategory: { category_name: '', category_code: '' },
        material: { material_name: '', material_code: '', category_id: '' }
      },
      tables: {
        permissionConfig: [],
        leaveType: [],
        materialCategory: [],
        material: []
      },
      loading: {
        permissionConfig: false,
        leaveType: false,
        materialCategory: false,
        material: false
      },
      pagers: {
        permissionConfig: { 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: {
        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' }]
          }
        }
      },
      userConfigModal: {
        visible: false,
        saving: false,
        permissionCode: '',
        permissionName: '',
        selectedUsers: []
      },
      userSelectorVisible: false,
      importShow: false,
      impBtnDisabled: false,
      materialCategoryOptions: [],
      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', minwidth: 120, align: 'center' },
        { title: '物料编码', key: 'material_code', minwidth: 120, align: 'center' },
        { title: '物料名称', key: 'material_name', minwidth: 180, align: 'center' },
        { title: '规格型号', key: 'material_spec', minwidth: 100, align: 'center' },
        { title: '单位', key: 'unit', align: 'center', minwidth: 80 },
        { title: '单价', key: 'unit_price', align: 'center', minwidth: 100 },
        { title: '供应商', key: 'supplier_name', align: 'center', minwidth: 120 },
        { 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' }
      ],
      permissionConfigColumns: [
        { type: 'index', title: '序号', width: 60, align: 'center' },
        { title: '权限名称', key: 'permission_name', align: 'center', minWidth: 150 },
        { title: '配置人员', key: 'user_names', align: 'center', minWidth: 300 },
        { title: '操作', slot: 'action', align: 'center', width: 120, fixed: 'right' }
      ],
      power: {
        leave_approval: false, // 请假审核
        leave_view: false, // 请假查询（统计）
        supply_approval: false, // 用品申领审核
        supply_view: false // 用品查询（统计）
      }
    }
  },
  created () {
    this.loadMaterialCategoryOptions()
    this.loadPermissionConfig()
    this.fetchList(this.activeTab)
    this.getUserDmPermission()
  },
  methods: {
    getUserDmPermission () {
      getUserDmPermissionList({}).then(ret => {
        console.log('ret', ret)
        if (ret.data && ret.data.errcode === 0) {
          const data = ret.data.data || []
          for (let i = 0; i < data.length; i++) {
            var ele = data[i]
            if (this.power.hasOwnProperty(ele.code)) {
              this.power[ele.code] = true
            }
          }
        } else {
          this.$Notice.error({ title: '查询失败', desc: ret.data.errmsg || '请稍后重试' })
        }
      })
    },
    handleTabChange (name) {
      this.activeTab = name
      if (name === 'permissionConfig') {
        this.loadPermissionConfig()
      } else {
        this.fetchList(name)
      }
    },
    fetchList (tab) {
      const apiMap = {
        permissionConfig: () => Promise.resolve({ data: { errcode: 0, data: [] } }),
        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 || []
          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 = {
        permissionConfig: () => ({}),
        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 = {
        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 = {
          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)
            // 如果是办公用品分类管理操作成功，刷新分类选项
            if (tab === 'materialCategory') {
              this.loadMaterialCategoryOptions()
            }
          } else {
            this.$Notice.error({ title: '保存失败', desc: ret.data.errmsg || '请稍后重试' })
          }
        }).finally(() => { modal.saving = false })
      })
    },
    handleDelete (tab, row) {
      const deleteApiMap = {
        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)
          // 如果是办公用品分类管理删除成功，刷新分类选项
          if (tab === 'materialCategory') {
            this.loadMaterialCategoryOptions()
          }
        } else {
          this.$Notice.error({ title: '删除失败', desc: ret.data.errmsg || '请稍后重试' })
        }
      })
    },
    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 || '')
          })) : []
        }
      })
    },
    loadPermissionConfig () {
      // 从字典获取权限配置数据，并加载对应的用户配置
      this.loading.permissionConfig = true
      getPermissionConfigList().then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.tables.permissionConfig = ret.data.data || []
        } else {
          this.$Notice.error({ title: '加载失败', desc: ret.data && ret.data.errmsg })
        }
      }).finally(() => { this.loading.permissionConfig = false })
    },
    openUserConfigModal (row) {
      this.userConfigModal.visible = true
      this.userConfigModal.permissionCode = row.permission_code
      this.userConfigModal.permissionName = row.permission_name
      this.userConfigModal.selectedUsers = row.user_names ? (JSON.parse(row.users) || []) : []
      console.log('this.userConfigModal', this.userConfigModal)
    },
    addUsers () {
      this.userSelectorVisible = true
    },
    handleUserSelectorOk (selectedUsers) {
      // 将新选择的用户添加到已选用户列表中，避免重复
      const existingIds = this.userConfigModal.selectedUsers.map(u => u.user_id)
      const newUsers = selectedUsers.filter(u => !existingIds.includes(u.id)).map(u => ({
        user_id: u.id,
        user_name: u.name,
        gh: u.gh
      }))
      this.userConfigModal.selectedUsers = [...this.userConfigModal.selectedUsers, ...newUsers]
      this.userSelectorVisible = false
    },
    removeUser (user) {
      this.userConfigModal.selectedUsers = this.userConfigModal.selectedUsers.filter(u => u.user_id !== user.user_id)
    },
    saveUserConfig () {
      this.userConfigModal.saving = true
      const userIds = this.userConfigModal.selectedUsers.map(u => u.user_id)
      savePermissionUsers({
        permission_code: this.userConfigModal.permissionCode,
        user_ids: userIds
      }).then(ret => {
        if (ret.data && ret.data.errcode === 0) {
          this.$Message.success('保存成功')
          this.userConfigModal.visible = false
          this.loadPermissionConfig()
        } else {
          this.$Notice.error({ title: '保存失败', desc: ret.data && ret.data.errmsg })
        }
      }).finally(() => { this.userConfigModal.saving = false })
    },
    // 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: '模板下载失败' })
    //   })
    // },
    async tplDownload () {
      // 下载物料导入模板
      try {
        const response = await axios.post(
          '/api/ac/jilinsscgsdp/keyDmUserCategory/templateDownload',
          {},
          {
            responseType: 'blob'
          }
        )
        const url = window.URL.createObjectURL(new Blob([response.data]))
        // 创建隐藏的a标签并设置属性
        const link = document.createElement('a')
        link.href = url
        link.download = '办公用品导入模板.xlsx' // 自定义下载文件名和扩展名
        link.style.display = 'none'
        document.body.appendChild(link)
        // 触发点击下载
        link.click()
        // 清理
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      } catch (error) {
        console.error('下载失败:', error)
        // 可以在这里添加错误提示
      }
    },
    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;
  min-height: 80vh;
}
.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>
