<template>
  <div class="supervision-content-container content-container">
    <div v-if="activeView === 'list'">
      <!-- 搜索表单 -->
      <div class="search-panel">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="监审类别:">
            <el-cascader
              v-model="searchForm.catalogId"
              :options="catalogListOptions"
              v-bind="props"
              style="width: 100%"
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item label="状态:">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              @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">
        <!-- v-region-permission="{
            category: 'financeSheetManage',
            action: 'add',
          }" -->
        <!-- v-region-permission="{
            category: 'financeSheetManage',
            action: 'add',
          }" -->
        <el-button
          plain
          type="success"
          icon="el-icon-circle-plus"
          @click="handleAdd"
        >
          添加
        </el-button>
        <!-- v-region-permission="{
            category: 'financeSheetManage',
            action: 'delete',
          }" -->
        <el-button
          plain
          type="danger"
          icon="el-icon-delete"
          :disabled="selectedRows.length === 0"
          @click="handleBatchDelete"
        >
          删除
        </el-button>
      </div>

      <!-- 表格 -->
      <div class="table-container">
        <CostAuditTable
          ref="costAuditTable"
          :table-data="tableData"
          :columns="tableColumns"
          :show-selection="true"
          :show-index="true"
          :show-pagination="true"
          :pagination="pagination"
          :loading="loading"
          :table-props="{
            defaultSort: { prop: 'createTime', order: 'descending' },
          }"
          @selection-change="handleSelectionChange"
          @pagination-change="handlePaginationChange"
        >
          <!-- :table-props="{
            defaultSort: { prop: 'createTime', order: 'descending' },
          }" -->
          <template #catalogId="{ row }">
            <span class="table-name-link">
              {{ getCatalogNames(row) }}
            </span>
          </template>
          <!-- 财务表名称自定义单元格 -->
          <template #surveyTemplateName="{ row }">
            <span class="table-name-link" @click="handleViewDetail(row)">
              {{ row.surveyTemplateName }}
            </span>
          </template>
          <!-- 创建时间自定义单元格 -->
          <template #createTime="{ row }">
            <div>{{ row.createTime ? row.createTime.split(' ')[0] : '-' }}</div>
            <div>{{ row.createTime ? row.createTime.split(' ')[1] : '-' }}</div>
          </template>
          <!-- 操作列 -->
          <template #action="{ row }">
            <!-- v-region-permission="{
                category: 'financeSheetManage',
                action: 'view',
              }" -->
            <el-button type="text" size="mini" @click="handleViewDetail(row)">
              详情
            </el-button>
            <!-- v-region-permission="{
                category: 'financeSheetManage',
                action: 'edit',
                targetData: row,
              }" -->
            <el-button type="text" size="mini" @click="handleEdit(row)">
              修改
            </el-button>
            <!-- v-region-permission="{
                category: 'financeSheetManage',
                action: 'delete',
                targetData: row,
              }" -->
            <el-button
              class="delete-btn"
              type="text"
              size="mini"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
            <!-- v-region-permission="{
                category: 'financeSheetManage',
                action: 'edit',
                targetData: row,
              }" -->
            <el-dropdown class="ml10" trigger="click">
              <el-button type="text" size="mini">
                更多
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <!-- v-region-permission="{
                    category: 'financeSheetManage',
                    action: 'edit',
                    targetData: row,
                  }" -->
                <el-dropdown-item
                  @click.native="handleDropdownCommand('infoMaintain', row)"
                >
                  内容维护
                </el-dropdown-item>
                <!-- v-region-permission="{
                    category: 'financeSheetManage',
                    action: 'edit',
                    targetData: row,
                  }" -->
                <el-dropdown-item
                  @click.native="handleDropdownCommand('status', row)"
                >
                  {{ row.status === '0' ? '停用' : '启用' }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </CostAuditTable>
      </div>
    </div>

    <div v-if="activeView === 'infoMaintain'">
      <InfoMaintain
        ref="infoMaintain"
        @back="activeView = $event"
      ></InfoMaintain>
    </div>
    <!-- 添加/修改弹窗 -->
    <CostAuditDialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="650px"
      :close-on-click-modal="false"
      :show-confirm-btn="dialogTitle !== '查看财务数据表'"
      :cancel-text="dialogTitle === '查看财务数据表' ? '关 闭' : '取 消'"
      :confirm-loading="submitLoading"
      @confirm="submitForm"
      @cancel="handleDialogCancel"
      @close="handleDialogClose"
    >
      <CostAuditForm
        ref="dataForm"
        form-type="dialog"
        :form-data="formData"
        :form-items="dialogFormItems"
        :rules="rules"
        :show-action-buttons="false"
        :label-width="'160px'"
        :form-props="{ disabled: dialogTitle === '查看财务数据表' }"
        @update:form-data="(val) => (formData = val)"
      >
        <template #catalogId>
          <el-cascader
            v-model="formData.catalogId"
            :options="catalogListOptions"
            v-bind="props"
            style="width: 100%"
            @change="handleCatalogChange"
          ></el-cascader>
        </template>
        <template #surveyTemplateName>
          <el-input
            v-model="formData.surveyTemplateName"
            v-pinyin-abbreviation="{
              target: 'formData.surveyTemplateNameYw',
            }"
            placeholder="请输入财务表名称"
            clearable
            maxlength="30"
            show-word-limit
          />
        </template>
        <template #surveyTemplateNameYw>
          <el-input
            v-model="formData.surveyTemplateNameYw"
            placeholder="请输入财务表英文名称"
            clearable
            maxlength="30"
            show-word-limit
          />
        </template>
        <template #templateType>
          <el-radio v-model="formData.templateType" label="1">单记录</el-radio>
          <el-radio v-model="formData.templateType" label="2">固定表</el-radio>
          <el-radio v-model="formData.templateType" label="3">动态表</el-radio>
        </template>
        <!-- <template #storageTable>
          <el-input
            v-model="formData.storageTable"
            placeholder="请输入财务表数据存储库表"
          />
        </template> -->
        <template #remarks>
          <el-input v-model="formData.remarks" type="textarea"
          placeholder="请输入说明,填写财务表的业务说明、填报指引等内容" type:
          rows='4' maxlength="500" show-word-limit />
        </template>
      </CostAuditForm>
    </CostAuditDialog>
  </div>
</template>

<script>
  import CostAuditTable from '@/components/costAudit/CostAuditTable.vue'
  import CostAuditForm from '@/components/costAudit/CostAuditForm.vue'
  import CostAuditDialog from '@/components/costAudit/CostAuditDialog.vue'
  import {
    getSurveyFdTemplate,
    addSurveyFdTemplate,
    delSurveyFdTemplateById,
    delSurveyFdTemplates,
    getSurveyFdList,
    editSurveyFdForm,
    changeSurveyFdStatus,
  } from '@/api/costSurveyFdTemplate'
  import { getCatalogDetail } from '@/api/catalogManage'
  import InfoMaintain from './infoMaintain.vue'
  import { catalogMixin, commonMixin } from '@/mixins/useDict'
  export default {
    name: 'FinanceSheetManage',
    components: {
      CostAuditTable,
      CostAuditForm,
      CostAuditDialog,
      InfoMaintain,
    },
    // 使用混入
    mixins: [catalogMixin, commonMixin],
    data() {
      return {
        activeView: 'list',
        // 搜索表单
        searchForm: {
          catalogId: '',
          contentType: '',
          status: '',
        },
        // 表格数据
        tableData: [],
        // 分页信息
        pagination: {
          currentPage: 1,
          pageSize: 50,
          total: 0,
        },
        // 加载状态
        loading: false,
        submitLoading: false,
        // 选中行
        selectedRows: [],
        // 弹窗相关
        dialogVisible: false,
        dialogTitle: '',
        isEdit: false,
        formData: {
          catalogId: '',
          contentType: '',
          surveyTemplateName: '',
          surveyTemplateNameYw: '',
          templateType: '1',
          storageTable: '',
          remarks: '',
        },
        CatalogNameMap: {},
        currentRow: null,
        // 表单验证规则
        rules: {
          catalogId: [
            { required: true, message: '请选择监审类别', trigger: 'change' },
          ],
          surveyTemplateName: [
            { required: true, message: '请输入财务表名称', trigger: 'blur' },
            { max: 50, message: '长度不能超过50个字符', trigger: 'blur' },
          ],
          surveyTemplateNameYw: [
            {
              required: true,
              message: '请输入财务表英文名称',
              trigger: 'blur',
            },
            { max: 30, message: '长度不能超过30个字符', trigger: 'blur' },
            {
              pattern: /^[a-zA-Z0-9_]+$/,
              message: '请输入字母或数字或下划线',
              trigger: 'blur',
            },
          ],
          storageTable: [
            {
              required: true,
              message: '请选择数据存储表名称',
              trigger: 'change',
            },
          ],
        },

        // -1草稿,0启用,1停用
        statusOptions: [
          { value: '-1', label: '草稿' },
          { value: '0', label: '启用' },
          { value: '1', label: '停用' },
        ],
        props: {
          filterable: true,
          placeholder: '请选择监审类别',
          style: 'width: 100%',
          showAllLevels: false,
          props: {
            multiple: false,
            children: 'children',
            checkStrictly: false,
            label: 'catalogName',
            value: 'id',
            emitPath: false,
          },
        },
      }
    },
    computed: {
      // 对话框表单项配置
      dialogFormItems() {
        return [
          {
            prop: 'catalogId',
            label: '监审类别:',
            type: 'cascader',
            slotName: 'catalogId',
            props: {
              placeholder: '请选择监审类别',
              style: { width: '100%' },
            },
            options: this.catalogIdOptions,
          },
          {
            prop: 'surveyTemplateName',
            label: '财务表名称:',
            type: 'input',
            props: {
              placeholder: '请输入财务表名称',
            },
            slotName: 'surveyTemplateName',
          },
          {
            prop: 'surveyTemplateNameYw',
            label: '财务表英文名称:',
            type: 'input',
            props: {
              placeholder: '请输入财务表英文名称',
            },
            slotName: 'surveyTemplateNameYw',
          },
          {
            prop: 'templateType',
            label: '表单样式:',
            slotName: 'templateType',
          },
          // {
          //   prop: 'storageTable',
          //   label: '财务表数据存储库表:',
          //   type: 'input',
          //   slotName: 'storageTable',
          // },
          {
            prop: 'remarks',
            label: '说明:',
            type: 'input',
            slotName: 'remarks',
            props: {
              type: 'textarea',
              rows: 4,
              maxlength: 200,
              placeholder: '请输入说明,填写财务表的业务说明、填报指引等内容',
            },
          },
        ]
      },

      // 表格列配置
      tableColumns() {
        return [
          {
            prop: 'catalogId',
            label: '监审类别',
            slotName: 'catalogId',
          },
          {
            prop: 'surveyTemplateName',
            label: '财务表名称',
            slotName: 'surveyTemplateName',
          },
          {
            prop: 'templateType',
            label: '模版类型',
            width: '100px',
            formatter: (row) => {
              return row.templateType == '1'
                ? '单记录'
                : row.templateType == '2'
                ? '固定表'
                : '动态表'
            },
          },
          // {
          //   prop: 'storageTable',
          //   label: '财务表数据存储表',
          // },
          {
            prop: 'status',
            label: '状态',
            width: '100px',
            formatter: (row) => {
              return row.status == '-1'
                ? '草稿'
                : row.status == '0'
                ? '启用'
                : '停用'
            },
          },
          {
            prop: 'createTime',
            label: '创建时间',
            slotName: 'createTime',
            width: '120px',
            sortable: true,
          },
          {
            prop: 'action',
            label: '操作',
            width: 240,
            align: 'center',
            fixed: 'right',
            slotName: 'action',
          },
        ]
      },
    },
    watch: {
      // 监听目录数据变化，数据加载完成后处理回显
      catalogListOptions: {
        handler(newVal) {
          if (newVal && newVal.length > 0) {
            // 数据加载完成后，重新处理value
            this.batchGetCatalogNames()
          }
        },
        immediate: true,
      },
    },
    mounted() {
      if (!this.$permission.isAdminOrProvince()) {
        this.tableColumns.splice(this.tableColumns.length - 1, 1)
      }
      // 初始加载数据
      this.handleSearch()
    },
    methods: {
      handleCatalogChange(val) {
        // 设置表单数据
        this.$set(this.formData, 'catalogId', val)
        console.log(this.formData.catalogId)
        this.$nextTick(() => {
          if (this.$refs.dataForm && this.$refs.dataForm.$refs.formRef) {
            this.$refs.dataForm.$refs.formRef.clearValidate('catalogId')
          }
        })
      },
      // 初始化表单选项
      initFormOptions() {
        // 将选项数据同步到表单配置中
        this.searchFormItems[0].options = this.catalogIdOptions
        this.searchFormItems[1].options = this.contentTypeOptions
        this.searchFormItems[2].options = this.statusOptions

        this.dialogFormItems[0].options = this.catalogIdOptions
        this.dialogFormItems[1].options = this.contentTypeOptions
        this.dialogFormItems[4].options = this.storageTableOptions
      },

      // 加载选择器数据
      loadOpts() {},

      // 搜索
      handleSearch() {
        this.loading = true

        const params = {
          catalogId: this.searchForm.catalogId,
          status: this.searchForm.status,
          page: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
        }
        getSurveyFdList(params)
          .then((res) => {
            if (res.rows.length > 0) {
              this.tableData = res.rows || []
              this.pagination.total = res.total || 0
            }
          })
          .catch((error) => {
            console.error('搜索失败:', error)
          })
          .finally(() => {
            this.loading = false
          })
      },

      // 重置
      handleReset() {
        this.searchForm = {
          catalogId: '',
          contentType: '',
          status: '',
        }
        this.pagination.currentPage = 1
        this.handleSearch()
      },

      // 添加
      handleAdd() {
        this.getstorageTableOpt()
        this.dialogTitle = '添加财务数据表'
        this.isEdit = false
        this.formData = {
          catalogId: '',
          contentType: '',
          surveyTemplateName: '',
          surveyTemplateNameYw: '',
          templateType: '1',
          storageTable: '',
          remarks: '',
        }
        this.dialogVisible = true
      },

      getstorageTableOpt() {
        // getstorageTableOptions().then((res) => {
        //   this.storageTableOptions = res.value
        //   this.dialogFormItems[4].options = res.value
        // })
      },
      getCatalogNames(row) {
        if (!row.catalogId) return ''
        return row.catalogId
          .split(',')
          .map((id) => {
            const trimId = id.trim()
            return this.CatalogNameMap[trimId] || '未知名称'
          })
          .join('，')
      },
      // 获取监审类别名称
      batchGetCatalogNames() {
        // 递归查找名称
        this.CatalogNameMap = {}
        this._recursiveCatalogMap(this.catalogListOptions)
      },

      // 递归遍历目录树并构建ID到名称的映射
      _recursiveCatalogMap(catalogs) {
        if (!Array.isArray(catalogs) || catalogs.length === 0) {
          return
        }
        catalogs.forEach((item) => {
          // 为当前目录项添加映射
          this.CatalogNameMap[item.id] = item.catalogName
          // 递归处理子目录
          if (item.children && Array.isArray(item.children)) {
            this._recursiveCatalogMap(item.children)
          }
        })
      },
      // 批量删除
      handleBatchDelete() {
        if (this.selectedRows.length === 0) {
          this.$message.warning('请先选择要删除的数据')
          return
        }
        this.$confirm(
          `确定要删除选中的 ${this.selectedRows.length} 条数据吗？`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(() => {
          const ids = this.selectedRows.map((row) => row.surveyTemplateId)
          this.loading = true
          delSurveyFdTemplates(ids)
            .then((res) => {
              if (res.code === 200) {
                this.$message.success('批量删除成功')
                this.selectedRows = []
                this.handleSearch()
              }
            })
            .catch((error) => {
              console.error('批量删除失败:', error)
            })
            .finally(() => {
              this.loading = false
            })
        })
      },

      // 表格选择变化
      handleSelectionChange(selection) {
        this.selectedRows = selection
      },

      // 查看详情
      handleViewDetail(row) {
        // 处理级联选择器多选回显数据
        // const result = this.formatRelatedItemsForDisplay({
        //   catalogId: {
        //     value: row.catalogId,
        //     options: this.catalogListOptions,
        //     id: 'id',
        //     parentId: 'parentId',
        //   },
        // })
        this.dialogVisible = true
        this.dialogTitle = `查看财务数据表`
        this.formData = {
          ...row,
          // catalogId: result.catalogId ? result.catalogId : [],
        }
      },

      // 修改
      handleEdit(row) {
        // 处理级联选择器多选回显数据
        // const result = this.formatRelatedItemsForDisplay({
        //   catalogId: {
        //     value: row.catalogId,
        //     options: this.catalogListOptions,
        //     id: 'id',
        //     parentId: 'parentId',
        //   },
        // })
        this.dialogTitle = '修改财务数据表'
        this.isEdit = true
        this.formData = {
          ...row,
          // catalogId: result.catalogId ? result.catalogId : [],
        }
        this.dialogVisible = true
      },

      // 删除
      handleDelete(row) {
        this.$confirm(
          `确定要删除 "${row.surveyTemplateName}" 吗？`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(() => {
          this.loading = true
          delSurveyFdTemplateById({ id: row.surveyTemplateId })
            .then((res) => {
              if (res.code === 200) {
                this.$message.success('删除成功')
                this.handleSearch()
              }
            })
            .catch((error) => {
              console.error('删除失败:', error)
            })
            .finally(() => {
              this.loading = false
            })
        })
      },

      // 下拉菜单命令处理
      handleDropdownCommand(command, row) {
        // infoMaintain
        switch (command) {
          case 'infoMaintain':
            // this.currentRow = row
            this.activeView = 'infoMaintain'
            this.$nextTick(() => {
              this.$refs.infoMaintain.getTemplateRow(row)
            })
            break
          case 'status':
            this.handleStatus(row)
            break

          default:
            break
        }
      },

      // 启动/停用状态
      handleStatus(row) {
        const action = row.status === '0' ? '停用' : '启用'
        this.$confirm(`确认要${action}该数据吗?`, '操作确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            changeSurveyFdStatus(row.surveyTemplateId)
              .then((res) => {
                if (res.code === 200) {
                  this.$message.success(`${action}成功`)
                  this.handleSearch()
                }
              })
              .catch(() => {})
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作',
            })
          })
      },

      // 分页变化处理
      handlePaginationChange({ currentPage, pageSize }) {
        this.pagination.currentPage = currentPage
        this.pagination.pageSize = pageSize
        this.handleSearch()
      },

      // 弹窗关闭处理
      handleDialogClose() {
        // 重置表单验证状态
        if (this.$refs.dataForm) {
          this.$refs.dataForm.$refs.formRef.resetFields()
        }
      },

      // 弹窗取消处理
      handleDialogCancel() {
        this.dialogVisible = false
      },

      // 提交表单
      submitForm() {
        if (this.dialogTitle === '查看财务数据表') {
          return
        }
        // 处理级联选择器多选数据
        // const resultData = this.extractLastLevelValues({
        //   catalogId: this.formData.catalogId,
        // })
        const data = {
          ...this.formData,
          // ...resultData,
        }

        this.$refs.dataForm
          .validate()
          .then(() => {
            this.submitLoading = true
            if (this.isEdit) {
              // 修改
              editSurveyFdForm(data)
                .then((res) => {
                  if (res.code === 200) {
                    this.$message.success('修改成功')
                    this.dialogVisible = false
                    this.handleSearch()
                  }
                })
                .catch((error) => {
                  console.error('修改失败:', error)
                })
                .finally(() => {
                  this.submitLoading = false
                })
            } else {
              addSurveyFdTemplate(data)
                .then((res) => {
                  if (res.code === 200) {
                    this.$message.success('添加成功')
                    this.dialogVisible = false
                    this.handleSearch()
                  }
                })
                .catch((error) => {
                  console.error('添加失败:', error)
                })
                .finally(() => {
                  this.submitLoading = false
                })
            }
          })
          .catch((error) => {
            console.error('表单验证失败:', error)
          })
      },
    },
  }
</script>

<style scoped lang="scss">
  @import '@/styles/costAudit.scss';
</style>
