<template>
  <!-- 业绩库页面：引用TableModel组件 -->
  <el-card class="tool-container">
    <!-- 返回按钮 -->
    <div class="back-container">
      <el-button type="default" size="small" @click="handleBack" class="back-btn">
        返回
      </el-button>
    </div>
    <div class="table-container">
      <TableModel
        :formLabel="formLabel"
        :columnsList="columnsList"
        :request-api="listPerformance"
        :sendParams="{ enterpriseId: enterpriseId }"
        :showOperation="true"
        :showRightTools="false"
        ref="performanceTableRef"
      >
        <!-- 表格标题插槽 -->
        <template slot="tableTitle">
          <h3>业绩库列表</h3>
        </template>
        <!-- 表格顶部操作按钮插槽（新增按钮） -->
        <template slot="tableActions">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="handleAdd"
            v-hasPermi="['enterpriseLibrary:performance:add']"
            class="add-btn"
          >
            新增业绩
          </el-button>
        </template>
        <!-- 合同金额格式化插槽（适配金额保留2位小数） -->
        <template slot="contractAmount" slot-scope="{ data }">
          <span>{{ formatCurrency(data.contractAmount) }}</span>
        </template>
        <!-- 操作列插槽（查看/编辑/删除） -->
        <template slot="handle" slot-scope="{ data }">
          <el-button
            size="mini"
            type="text"
            @click="handleView(data)"
            v-hasPermi="['enterpriseLibrary:performance:detail']"
            class="action-btn"
          >
            查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleEdit(data)"
            v-hasPermi="['enterpriseLibrary:performance:edit']"
            class="action-btn"
            style="color: #EAA819;"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(data)"
            v-hasPermi="['enterpriseLibrary:performance:del']"
            class="action-btn"
            style="color: #DB3E29;"
          >
            删除
          </el-button>
        </template>
      </TableModel>
    </div>
  </el-card>
</template>

<script>
// 导入TableModel组件、配置文件、工具函数和接口
import TableModel from '@/components/TableModel2'
import { formLabel, columnsList } from './config'
import { encryptWithSM4, decryptWithSM4 } from '@/utils/sm'
import { listPerformance, delPerformance } from "@/api/enterpriseLibrary/performance/performance";
import { listAPI } from "@/api/enterpriseLibrary/personnel/personnel";

export default {
  name: 'Performance',
  components: { TableModel }, // 注册TableModel组件
  data() {
    return {
      formLabel,          // 导入查询表单配置
      columnsList,        // 导入表格列配置
      listPerformance,    // 导入列表查询接口
      enterpriseId: decryptWithSM4(this.$route.query.enterpriseId) || '0' // 解密企业ID
    }
  },
  created() {
    this.loadVoltageLevelDict()
    this.loadProjectManagers()
    this.loadProjcetTypeDict()
    // 初始化时给表格组件传递企业ID参数，并加载列表
    this.$nextTick(() => {
      if (this.$refs.performanceTableRef) {
        this.$refs.performanceTableRef.queryParams.enterpriseId = this.enterpriseId
        this.$refs.performanceTableRef.getTableList()
      }
    })
  },
  methods: {

    loadProjcetTypeDict() {
      // getDicts 的参数是字典类型编码：project_type
      this.getDicts('project_type').then(response => {
        const proTypeOptions = response.data.map(item => ({
          label: item.dictLabel,
          value: item.dictLabel
        }))
        const proTypeItem = this.formLabel.find(item => item.f_model === 'proType')
        if (proTypeItem) {
          proTypeItem.f_selList = proTypeOptions // 动态设置下拉选项
        }
      }).catch(error => {
        console.error('加载项目类型字典失败：', error)
      })
    },

    loadVoltageLevelDict() {
      this.getDicts('voltage_level').then(response => {
        const voltageOptions = response.data.map(item => ({
          label: item.dictLabel,
          value: item.dictLabel
        }))

        const voltageItem = this.formLabel.find(item => item.f_model === 'voltageLevel')
        if (voltageItem) {
          voltageItem.f_selList = voltageOptions // 动态设置下拉选项
        }
      }).catch(error => {
        console.error('加载电压等级字典失败：', error)
      })
    },

    loadProjectManagers() {
      const params = {
        enterpriseId: this.enterpriseId,
        personnelPosition: 'project_manager'
      };

      listAPI(params).then(response => {
        const projectManagerOptions = (response.rows || []).map(person => ({
          label: person.personnelName,
          value: person.personnelName
        }));

        const projectManagerItem = this.formLabel.find(item => item.f_model === 'projectManager');
        if (projectManagerItem) {
          projectManagerItem.f_selList = projectManagerOptions;
        }

        this.projectManager = projectManagerOptions;
      }).catch(error => {
        console.error('主组件获取项目经理列表失败：', error);
        this.projectManager = [];
        const projectManagerItem = this.formLabel.find(item => item.f_model === 'projectManager');
        if (projectManagerItem) {
          projectManagerItem.f_selList = [];
        }
      });
    },

    // 格式化金额：保留2位小数
    formatCurrency(amount) {
      if (!amount) return '0.00'
      return parseFloat(amount).toFixed(2)
    },
    // 新增业绩：跳转新增/编辑共用页面（type=add）
    handleAdd() {
      this.$router.push({
        name: "PerformanceForm",
        query: {
          type: encryptWithSM4('add'),
          id: encryptWithSM4(''),
          enterpriseId: encryptWithSM4(this.enterpriseId)
        },
        title: '新增业绩'
      })
    },
    // 查看业绩：跳转详情页
    handleView(data) {
      this.$router.push({
        name: "PerformanceDetail",
        query: {
          id: encryptWithSM4((data.performanceId ?? '').toString()),
          enterpriseId: encryptWithSM4(this.enterpriseId)
        },
        title: '业绩详情'
      })
    },
    // 编辑业绩：跳转新增/编辑共用页面（type=edit）
    handleEdit(data) {
      this.$router.push({
        name: "PerformanceForm", // 改为与新增共用同一页面组件
        query: {
          type: encryptWithSM4('edit'), // 传递操作类型为编辑
          id: encryptWithSM4((data.performanceId ?? '').toString()), // 传递业绩ID
          enterpriseId: encryptWithSM4(this.enterpriseId)
        },
        title: '编辑业绩'
      })
    },
    // 删除业绩：调用接口并刷新列表
    handleDelete(data) {
      this.$confirm(`确定要删除【${data.proName}】吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$modal.loading("正在删除，请稍候...")
        // 调用删除接口（传递业绩ID和企业ID）
        delPerformance({
          performanceId: data.performanceId,
          enterpriseId: this.enterpriseId
        }).then(res => {
          this.$modal.closeLoading()
          if (res.code === 200) {
            this.$modal.msgSuccess("删除成功")
            this.$refs.performanceTableRef.getTableList() // 重新加载表格
          } else {
            this.$modal.msgError(res.msg || "删除失败")
          }
        }).catch(error => {
          this.$modal.closeLoading()
          this.$modal.msgError(error.message || "删除失败")
        })
      })
    },
    // 返回上级页面
    handleBack() {
      const obj = {
        path: "/enterpriseKnowledge/index",
        query: {
          enterpriseId: encryptWithSM4(this.enterpriseId || '0')
        }
      }
      this.$tab.closeOpenPage(obj)
    }
  }
}
</script>

<style scoped lang="scss">
.tool-container {
  height: calc(100vh - 84px);
  overflow: auto;
  background: linear-gradient(180deg, #F1F6FF 20%, #E5EFFF 100%);
  padding: 20px;
}

::v-deep .table-card {
  height: calc(100vh - 240px) !important;
}


.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);
    }
  }
}

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

  &: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>
