<template>
  <div class="supervision-doc-number-manage">
    <div class="supervision-doc-content-container">
      <!-- 左侧分类树 -->
      <div class="category-tree">
        <el-input
          v-model="filterText"
          style="width: 80%"
          placeholder="输入关键字进行过滤"
          clearable
          prefix-icon="el-icon-search"
        ></el-input>
        <el-tree
          ref="typeTree"
          :data="categoryData"
          node-key="id"
          default-expand-all
          :props="{
            label: 'documentName',
            value: 'id',
          }"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          @node-click="handleNodeClick"
        ></el-tree>
      </div>

      <!-- 右侧内容区域 -->
      <div class="right-content">
        <!-- 搜索区域 -->
        <div class="search-plane">
          <el-form :inline="true" size="small">
            <!-- 文号名称输入框 -->
            <el-form-item label="文号名称:">
              <el-input
                v-model="searchForm.whName"
                placeholder="请输入"
                clearable
              ></el-input>
            </el-form-item>

            <!-- 搜索和重置按钮 -->
            <el-form-item>
              <el-button
                icon="el-icon-search"
                type="primary"
                @click="handleSearch"
              >
                搜索
              </el-button>
              <el-button
                plain
                type="primary"
                icon="el-icon-refresh"
                @click="handleReset"
              >
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 操作按钮区域 -->
        <div class="operation-bar">
          <el-button
            plain
            type="success"
            icon="el-icon-circle-plus"
            @click="handleAdd"
          >
            添加
          </el-button>
          <el-button
            plain
            type="danger"
            icon="el-icon-delete"
            :disabled="selectedRows.length === 0"
            @click="handleDelete"
          >
            删除
          </el-button>
        </div>

        <!-- 数据表格  -->
        <CostAuditTable
          ref="costAuditTable"
          :table-data="tableData"
          :columns="columns"
          :show-selection="true"
          :show-index="true"
          :show-pagination="true"
          :show-action-column="true"
          :pagination="{
            currentPage: currentPage,
            pageSize: pageSize,
            total: total,
          }"
          @selection-change="handleSelectionChange"
          @pagination-change="handlePaginationChange"
        >
          <template #updateTime="{ row }">
            <div>
              {{ row.updateTime ? row.updateTime.split(' ')[0] : '' }}
            </div>
            <div>
              {{ row.updateTime ? row.updateTime.split(' ')[1] : '' }}
            </div>
          </template>
        </CostAuditTable>

        <!-- 添加/修改弹窗  -->
        <el-dialog
          :title="dialogTitle"
          :visible.sync="dialogVisible"
          width="65%"
          :close-on-click-modal="false"
        >
          <!-- 弹窗内容保持不变 -->
          <div class="dialog-content">
            <el-form
              ref="docForm"
              :model="formData"
              :rules="formRules"
              label-width="120px"
              size="small"
              :disabled="dialogVisible == '详情'"
            >
              <el-row :gutter="20">
                <el-col :span="12">
                  <!-- 适用区域 -->
                  <el-form-item label="适用区域:" prop="areaCode" required>
                    <el-cascader
                      v-model="formData.areaCode"
                      style="width: 100%"
                      :options="districtTree"
                      :props="districtTreeCascaderProps"
                      :show-all-levels="false"
                      clearable
                    ></el-cascader>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="文号分类:" prop="whType" required>
                    <el-select v-model="formData.whType" style="width: 100%">
                      <el-option
                        v-for="item in whTypeOptions"
                        :key="item.id"
                        :label="item.documentName"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <!-- 文号名称 -->
                  <el-form-item label="文号名称:" prop="whName" required>
                    <el-input
                      v-model="formData.whName"
                      v-pinyin-abbreviation="{
                        target: 'formData.alias',
                      }"
                      placeholder="请输入"
                      maxlength="50"
                      show-word-limit
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <!-- 文号别名 -->
                  <el-form-item label="文号别名:" prop="alias" required>
                    <el-input
                      v-model="formData.alias"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="文号前缀:" prop="prefixText" required>
                    <el-input
                      v-model="formData.prefixText"
                      placeholder="请输入文号前缀，例如：晋"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="年号:" prop="year" required>
                    <el-input
                      v-model="formData.year"
                      placeholder="请输入年号，例如：2025"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item
                    label="当前流水号值:"
                    prop="currentValue"
                    required
                  >
                    <el-input
                      v-model="formData.currentValue"
                      placeholder="请输入当前流水号值"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <!-- 文号规则 -->
                  <el-form-item label="文号规则:" prop="rulePattern" required>
                    <el-input
                      v-model="formData.rulePattern"
                      placeholder="请输入"
                      show-word-limit
                    ></el-input>
                    例如: {文号前缀}成审 {年份} {当前流水号值}号
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <!-- : incremental-递增, daily-每天生成, monthly-每月生成, yearly-每年生成-->
                  <el-form-item label="生成类型:" prop="generateType" required>
                    <el-radio-group v-model="formData.generateType">
                      <el-radio
                        v-for="item in dictData['whGenerateType']"
                        :key="item.id"
                        :label="item.key"
                      >
                        {{ item.name }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <!-- 文号长度 -->
                  <el-form-item label="文号长度:" prop="serialLength">
                    <el-input
                      v-model.number="formData.serialLength"
                      placeholder="请输入"
                      type="number"
                      min="1"
                      max="20"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <!-- 初始值 -->
                  <el-form-item label="初始值:" prop="initialValue">
                    <el-input
                      v-model.number="formData.initialValue"
                      placeholder="请输入"
                      type="number"
                      min="0"
                      show-word-limit
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- 步长 -->
              <!-- <el-row :gutter="20">
    <el-col :span="12">
      <el-form-item label="步长:" prop="step">
        <el-input
          v-model.number="formData.step"
          placeholder="请输入"
          type="number"
          min="1"
        ></el-input>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <div class="step-desc">
        <p>
          这个增加值表示文号部分(NO)的增加值，如2015102700001，步长为1，则文号部分的增加值为00001。
        </p>
      </div>
    </el-col>
  </el-row> -->
            </el-form>
          </div>

          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="handleSave">确认</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
  import {
    getData,
    addEntity,
    updateEntity,
    deleteById,
    batchDelete,
    getDetail,
  } from '@/api/auditDocNoManage'
  import { getWhCateList } from '@/api/auditReviewDocManage.js'
  import { dictMixin, regionMixin } from '@/mixins/useDict'
  import CostAuditTable from '@/components/costAudit/CostAuditTable.vue'

  export default {
    name: 'SupervisionDocNumberManage',
    components: {
      CostAuditTable,
    },
    mixins: [dictMixin, regionMixin],
    data() {
      return {
        dictData: {
          whGenerateType: [],
        },
        filterText: '',
        isExpand: true,
        // 搜索表单数据
        searchForm: {
          whName: '',
          whType: '',
        },
        // 分类树数据 - 增加更多分类 使用字典
        categoryData: [
          {
            documentName: '文号分类',
            children: [],
          },
        ],
        // 表格数据
        tableData: [],
        // 当前页码
        currentPage: 1,
        // 每页显示条数
        pageSize: 50,
        // 总记录数
        total: 0,
        // 选中的行数据
        selectedRows: [],
        // 选中的分类
        selectedCategories: [],
        // 弹窗相关
        dialogVisible: false,
        dialogTitle: '',
        isEdit: false,
        // 详情弹窗相关
        detailVisible: false,
        detailData: {},
        // 表单数据 - 完整结构
        formData: {
          whName: '',
          alias: '',
          currentValue: '',
          rulePattern: '{prefixText}成审 {year} {currentValue}号',
          generateType: '',
          serialLength: 5,
          initialValue: 1,
          // step: 1,
          areaCode: [],
          whType: '',
        },
        // 表单验证规则
        formRules: {
          whName: [
            { required: true, message: '请输入文号名称', trigger: 'blur' },
            { max: 50, message: '文号名称不能超过50个字符', trigger: 'blur' },
          ],
          alias: [
            { required: true, message: '请输入文号别名', trigger: 'blur' },
          ],
          currentValue: [
            { required: true, message: '请输入当前流水号值', trigger: 'blur' },
          ],
          rulePattern: [
            { required: true, message: '请输入文号规则', trigger: 'blur' },
          ],
          generateType: [
            { required: true, message: '请选择生成类型', trigger: 'change' },
          ],
          serialLength: [
            { required: true, message: '请输入文号长度', trigger: 'blur' },
          ],
          initialValue: [
            { required: true, message: '请输入初始值', trigger: 'blur' },
          ],
          // step: [{ required: true, message: '请输入步长', trigger: 'blur' }],
          areaCode: [
            { required: true, message: '请选择适用区域', trigger: 'change' },
          ],
        },
        whTypeOptions: [],
        // 表格列配置
        columns: [
          {
            prop: 'whType',
            label: '文号分类',
            showOverflowTooltip: true,
            align: 'center',
            formatter: (row) => {
              let documentName =
                this.whTypeOptions.find((item) => item.id == row.whType)
                  ?.documentName || '-'
              return documentName
            },
          },
          {
            prop: 'whName',
            label: '文号名称',
            showOverflowTooltip: true,
            align: 'center',
          },
          {
            prop: 'areaCode',
            label: '适用区域',
            showOverflowTooltip: true,
            align: 'center',
            formatter: (row) => this.regionNameMap[row.areaCode] || '-',
          },
          {
            prop: 'generateType',
            label: '生成类型',
            showOverflowTooltip: true,
            align: 'center',
            width: 120,
            formatter: (row) =>
              this.getDictName('whGenerateType', row.generateType),
          },
          {
            prop: 'createBy',
            label: '创建人',
            showOverflowTooltip: true,
            align: 'center',
            width: 120,
          },
          {
            prop: 'updateTime',
            label: '最后更新时间',
            showOverflowTooltip: true,
            align: 'center',
            width: 120,
            slotName: 'updateTime',
          },
          {
            prop: 'action',
            label: '操作',
            align: 'center',
            width: 200,
            actions: [
              {
                name: 'detail',
                label: '详情',
                type: 'text',
                size: 'mini',
                onClick: this.handleDetail,
              },
              {
                name: 'edit',
                label: '修改',
                type: 'text',
                size: 'mini',
                onClick: this.handleEdit,
              },
              {
                name: 'delete',
                label: '删除',
                type: 'text',
                size: 'mini',
                className: 'delete-btn',
                onClick: this.handleDeleteRow,
              },
            ],
          },
        ],
      }
    },
    watch: {
      // 添加对filterText的监听，当它变化时触发树的过滤
      filterText(val) {
        if (this.$refs.typeTree) {
          this.$refs.typeTree.filter(val)
        }
      },
    },
    mounted() {
      // 加载分类数据
      this.getCategoryData()
      // 页面加载时获取数据
      this.getTableData()
    },
    methods: {
      async getCategoryData() {
        try {
          const res = await getWhCateList()
          this.categoryData[0].children = res.value || []
          this.whTypeOptions = res.value
        } catch (error) {
          console.error('获取分类数据失败:', error)
        }
      },
      // 节点点击事件处理
      handleNodeClick(data) {
        // 如果点击的是子节点，直接使用其dictValue
        // 如果点击的是父节点，不进行筛选
        if (!data.children) {
          this.selectedCategories = [data.id]
          this.searchForm.whType = data.id
          // 重置分页并重新获取数据
          this.currentPage = 1
          this.getTableData()
        }
      },
      // 过滤树节点
      filterNode(value, data) {
        if (!value) return true
        const searchValue = value.toLowerCase()
        const dictLabelMatch =
          data.documentName &&
          data.documentName.toLowerCase().includes(searchValue)
        return dictLabelMatch
      },
      // 获取表格数据
      async getTableData() {
        try {
          const params = {
            pageSize: this.pageSize,
            page: this.currentPage,
            ...this.searchForm,
          }
          const response = await getData(params)
          this.tableData = response.value.records || []
          this.total = response.value.total || 0
          this.fetchRegionNames(this.tableData, 'areaCode')
        } catch (error) {
          console.error('获取数据失败:', error)
        }
      },

      // 搜索按钮点击事件
      handleSearch() {
        this.currentPage = 1
        this.getTableData()
      },

      // 重置按钮点击事件
      handleReset() {
        this.searchForm = {
          whName: '',
        }
        this.selectedCategories = []
        this.currentPage = 1
        this.getTableData()
      },

      // 添加按钮点击事件
      handleAdd() {
        this.isEdit = false
        this.dialogTitle = '添加文号'
        this.formData = {
          whName: '',
          alias: '',
          currentValue: '',
          rulePattern: '{prefixText}成审 {year} {currentValue}号',
          generateType: '',
          serialLength: 5,
          initialValue: 1,
          // step: 1,
          areaCode: [],
          whType: this.searchForm.whType,
        }
        // 清空表单验证
        this.$nextTick(() => {
          this.$refs.docForm.clearValidate()
        })
        this.dialogVisible = true
      },

      // 修改按钮点击事件
      handleEdit(row) {
        this.isEdit = true
        this.dialogTitle = '修改文号'
        getDetail({ id: row.id }).then((res) => {
          this.formData = {
            ...res.value,
            areaCode: [
              res.value.province,
              ...(row.areaLevel >= 1 ? [res.value.city] : []),
              ...(row.areaLevel === 2 ? [res.value.areaCode] : []),
            ].filter(Boolean),
            whType: Number(res.value.whType),
            rulePattern: '{prefixText}成审 {year} {currentValue}号',
          }

          // 清空表单验证
          this.$nextTick(() => {
            this.$refs.docForm.clearValidate()
          })
          this.dialogVisible = true
        })
      },

      // 保存按钮点击事件 - 添加错误提示
      async handleSave() {
        this.$refs.docForm.validate(async (valid) => {
          if (valid) {
            let data = {
              ...this.formData,
              areaCode:
                this.formData.areaCode[this.formData.areaCode.length - 1],
              areaLevel: this.formData.areaCode.length - 1,
            }
            try {
              if (this.isEdit) {
                // 处理修改逻辑
                await updateEntity(data)
                this.$message.success('修改成功')
              } else {
                // 处理添加逻辑
                await addEntity(data)
                this.$message.success('添加成功')
              }
              this.dialogVisible = false
              // 重新获取数据
              this.getTableData()
            } catch (error) {
              console.error('保存失败:', error)
              // this.$message.error('保存失败，请重试')
            }
          } else {
            this.$message.error('请填写表单数据')
          }
        })
      },

      // 删除按钮点击事件
      async handleDelete() {
        if (this.selectedRows.length === 0) {
          this.$message.warning('请先选择要删除的记录')
          return
        }
        this.$confirm('确定要删除选中的记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            try {
              // 获取选中行的ID列表
              const ids = this.selectedRows.map((row) => row.id)
              // 调用批量删除API
              const response = await batchDelete(ids)
              this.$message.success('删除成功')
              // 重新获取数据
              this.getTableData()
              this.selectedRows = []
            } catch (error) {
              console.error('删除失败:', error)
            }
          })
          .catch(() => {
            this.$message.info('已取消删除')
          })
      },

      // 选中行变化事件
      handleSelectionChange(val) {
        this.selectedRows = val
      },

      // 分类树选中变化事件 - 用于筛选表格数据
      handleCategoryChange(checkedKeys, halfCheckedKeys) {
        this.selectedCategories = checkedKeys
        // 重置分页
        this.currentPage = 1
        // 重新获取数据
        this.getTableData()
      },

      // 详情按钮点击事件 - 打开详情弹窗
      handleDetail(row) {
        getDetail({ id: row.id }).then((res) => {
          this.formData = {
            ...res.value,
            areaCode: [
              res.value.province,
              ...(row.areaLevel >= 1 ? [res.value.city] : []),
              ...(row.areaLevel === 2 ? [res.value.areaCode] : []),
            ].filter(Boolean),
            whType: Number(res.value.whType),
          }

          // 清空表单验证
          this.$nextTick(() => {
            this.$refs.docForm.clearValidate()
          })
          this.dialogVisible = true
          this.dialogVisible = true
          this.dialogTitle = '详情'
        })
      },

      // 单个删除按钮点击事件
      async handleDeleteRow(row) {
        this.$confirm('确定要删除该记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            try {
              // 调用单个删除API
              const response = await deleteById({ id: row.id })
              this.$message.success('删除成功')
              // 重新获取数据
              this.getTableData()
            } catch (error) {
              console.error('删除失败:', error)
            }
          })
          .catch(() => {
            this.$message.info('已取消删除')
          })
      },

      // 分页变化事件处理
      handlePaginationChange({ currentPage, pageSize }) {
        this.currentPage = currentPage
        this.pageSize = pageSize
        this.getTableData()
      },
    },
  }
</script>

<style scoped lang="scss">
  @import '@/styles/costAudit.scss';
  /* 内容容器 - 包含左侧分类树和右侧内容 */
  .supervision-doc-number-manage {
    width: 100%;
    padding: 20px;
  }
  .supervision-doc-content-container {
    display: flex;
  }

  /* 左侧分类树样式 */
  .category-tree {
    width: 240px;
    flex-shrink: 0;
    border: 1px solid #dbd8d8;
    padding: 10px;
    height: calc(100vh - 260px);
    overflow-y: auto;
  }

  /* 右侧内容区域  */
  .right-content {
    width: 80%;
    margin-left: 20px;
    /* 确保在小屏幕上有足够空间 */
    min-width: 0;
  }

  /* 弹窗内容区域样式 */
  .dialog-content {
    max-height: 500px;
    overflow-y: auto;
  }

  /* 详情弹窗描述项样式 */
  .el-descriptions__label {
    font-weight: bold;
  }
</style>
