<template>
  <!-- 分析标签组页面 -->
  <el-card class="analysis-label-container">

    <div class="back-container">
      <el-button type="default" size="small" @click="handleBack" class="back-btn">
        返回
      </el-button>
    </div>

    <!-- 数据列表：基于TableModel组件实现 -->
    <div class="table-container">
      <TableModel
        :formLabel="formLabel"
        :showOperation="true"
        :showRightTools="false"
        ref="analysisLabelTableRef"
        :columnsList="columnsList"
        :request-api="listAnalysisLabel"
      >
        <template slot="tableTitle">
          <h3>数据列表</h3>
        </template>
        <template slot="tableActions">
          <el-button
            @click="handleAdd"
            v-hasPermi="['template:analysisLabel:add']"
            class="add-btn"
          >
            <i class="el-icon-plus"></i> 新建标签组
          </el-button>
        </template>


        <!-- 状态开关 -->
        <template slot="useState" slot-scope="{ data }">
          <el-switch
            v-model="data.useState"
            :active-value="'0'"
            :inactive-value="'1'"
            @change="handleStateChange(data)"
          />
        </template>

        <!-- 操作按钮 -->
        <template slot="handle" slot-scope="{ data }">
          <el-button
            type="text"
            v-hasPermi="['template:analysisLabel:detail']"
            class="action-btn"
            style="color: #1F72EA;"
            @click="handleDetail(data)"
          >
          标签明细
          </el-button>
          <el-button
            type="text"
            v-hasPermi="['template:analysisLabel:edit']"
            class="action-btn"
            style="color: #EAA819;"
            @click="handleUpdate(data)"
          >
            编辑
          </el-button>
          <el-button
            type="text"
            v-hasPermi="['template:analysisLabel:del']"
            class="action-btn"
            style="color: #DB3E29;"
            @click="handleDelete(data)"
          >
            删除
          </el-button>
        </template>
      </TableModel>
    </div>

    <!-- 新增/编辑标签组抽屉（引入子组件） -->
    <AnalysisLabelForm
      v-if="drawerVisible"
      :visible="drawerVisible"
      :type="isAdd"
      :row-data="row"
      :industry-type-options="industryTypeOptions"
      @close="drawerVisible = false"
      @save-success="handleQuery"
    />
  </el-card>
</template>

<script>
import TableModel from '@/components/TableModel2'
import { columnsList, formLabel } from './config'
import AnalysisLabelForm from './components/AnalysisLabelForm.vue' // 引入表单组件
import {
  listAnalysisLabel,
  delAnalysisLabel,
  updateAnalysisLabel,
  countLabelItemRelateNum
} from '@/api/template/analysisLabel/analysisLabel'
// 引入加密工具（假设使用SM4加密）
import { encryptWithSM4 } from '@/utils/sm'

export default {
  name: 'AnalysisLabel',
  components: {
    TableModel,
    AnalysisLabelForm // 注册表单组件
  },
  data() {
    return {
      formLabel,
      columnsList,
      listAnalysisLabel,
      drawerVisible: false, // 抽屉显示控制
      isAdd: '', // 'add' 新增 / 'edit' 编辑
      row: {}, // 传递给子组件的行数据
      industryTypeOptions: [] // 行业类型选项（传递给子组件）
    }
  },

  created() {
    this.loadIndustryTypeDict()
  },

  methods: {

    handleBack() {
      const obj = {
        path: "/template",
      }
      this.$tab.closeOpenPage(obj)
    },

    // 加载行业类型字典
    loadIndustryTypeDict() {
      this.getDicts('industry_type').then(response => {
        const industryTypeOptions = response.data.map(item => ({
          label: item.dictLabel,
          value: item.dictLabel
        }))

        const industryTypeItem = this.formLabel.find(item => item.f_model === 'industryType')
        if (industryTypeItem) {
          industryTypeItem.f_selList = industryTypeOptions // 动态设置下拉选项
          this.industryTypeOptions = industryTypeOptions
        }
      }).catch(error => {
        console.error('加载行业类型字典失败：', error)
      })
    },

    // 新增标签组
    handleAdd() {
      this.isAdd = 'add'
      this.row = {}
      this.drawerVisible = true
    },

    // 编辑标签组
    handleUpdate(row) {
      this.isAdd = 'edit'
      this.row = { ...row }
      this.drawerVisible = true
    },

    // 查看标签明细 - 加密传递analysisLabelId参数
    handleDetail(data) {
      // 确保数据存在且包含analysisLabelId
      if (data && data.analysisLabelId) {
        // 对标签组ID进行加密后传递
        const encryptedId = encryptWithSM4(data.analysisLabelId.toString())
        this.$router.push({
          name: 'AnalysisLabelItem',
          query: {
            analysisLabelId: encryptedId  // 传递加密后的ID
          }
        })
      } else {
        this.$modal.msgError('获取标签组ID失败，请重试')
      }
    },

    // 切换状态 - 加密传递参数
    handleStateChange(row) {
      const originalState = row.useState
      // 对ID进行加密后传递给接口
      const params = {
        ...row,
        useState: row.useState,
        analysisLabelId: row.analysisLabelId
      }
      updateAnalysisLabel(params)
        .then(res => {
          if (res.code === 200) {
            this.$modal.msgSuccess('状态更新成功')
            this.handleQuery()
          } else {
            this.$modal.msgError(res.msg)
            row.useState = originalState
          }
        })
        .catch(() => {
          row.useState = originalState
        })
    },

    // 删除标签组 - 加密传递参数
    handleDelete(row) {
      this.$modal.confirm(`是否确认删除“${row.analysisLabelName}”？`)
        .then(() => {
          // 对ID进行加密后传递给删除接口
          delAnalysisLabel({
            analysisLabelId: encryptWithSM4(row.analysisLabelId.toString()) // 加密ID
          })
            .then(res => {
              if (res.code === 200) {
                this.$modal.msgSuccess('删除成功')
                this.handleQuery()
              } else {
                this.$modal.msgError(res.msg)
              }
            })
        })
    },

    // 刷新列表
    handleQuery() {
      this.$refs.analysisLabelTableRef.getTableList()
    }
  }
}
</script>

<style scoped lang="scss">

.back-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 20px;

  .back-btn {
    width: 98px;
    height: 36px;
    background: #FFFFFF;
    box-shadow: 0px 4px 8px 0px rgba(76, 76, 76, 0.2);
    border-radius: 4px;
    border: none;
    color: #666;
    font-size: 14px;
    transition: all 0.3s ease;

    &:hover {
      background: #f5f5f5;
      color: #409EFF;
      box-shadow: 0px 6px 12px 0px rgba(76, 76, 76, 0.3);
    }
  }
}

.analysis-label-container {
  height: calc(100vh - 84px);
  overflow: hidden;
  background: linear-gradient(180deg, #F1F6FF 20%, #E5EFFF 100%);
}

.add-btn {
  width: 121px;
  height: 36px;
  background: #1F72EA;
  box-shadow: 0px 4px 8px 0px rgba(51, 135, 255, 0.5);
  border-radius: 4px;
  border: none;
  color: #fff;
  font-size: 14px;
  transition: all 0.3s;
  margin-right: 10px;

  &:hover {
    background: #4A8BFF;
    box-shadow: 0px 6px 12px 0px rgba(51, 135, 255, 0.6);
  }
}

.action-btn {
  margin-right: 8px;

  &:last-child {
    margin-right: 0;
  }
}
</style>
