<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公司名称" prop="companyId" >
        <el-select v-model="queryParams.companyId" placeholder="请选择所属公司" filterable size="small">
          <el-option v-for="(option, index) in companyList" :key="index" :value="option.dictValue" :label="option.dictLabel"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="createTime" size="small" style="width: 220px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"  @change="changeTime"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="fastGptPushTokenTotalList" :row-class-name="() => 'fixed-bottom-row'"
              @selection-change="handleSelectionChange" :max-height="600">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="公司名称" align="center" prop="companyName" />
      <el-table-column label="部门名称" align="center" prop="deptName" >
        <template slot-scope="scope">
          <!-- 简化判断逻辑，同时处理 null/undefined/空字符串 等所有空值情况 -->
          <div>{{ scope.row.deptName || '--' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="token消耗" align="center" prop="count" />
      <el-table-column label="时间" align="center" prop="statTime" />
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listFastgptEventLogTotal, exportFastgptEventLogTotal, getFastGptRoleAppKeyList} from "@/api/fastGpt/fastgptEventLogTotal";
import { getFastGptPushTokenTotal,getFastGptPushTokenDeptTotal} from "@/api/fastGpt/fastgptPushTokenTotal";
import SelectTree from "@/components/TreeSelect/index.vue";
import {getDeptData} from "@/api/system/employeeStats";
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {allList} from "@/api/company/company";
import Template from '../../his/complaint/template.vue';
export default {
  name: "FastgptEventLogTotal",
  components: {SelectTree,TreeSelect},
  data() {
    return {
      createTime:null,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      selectedCompanyList: [],
      companyList:[],
      deptList: [],
      companyUserList: [],
      selectedAppKey: null,
      selectedAppKeyLabel: '',
      appKeyOptions: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // token统计表格数据
      fastGptPushTokenTotalList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      typeCountMap: null,
      // 日志类型字典
      typeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleId: null,
        count: null,
        type: null,
        companyId: null,
        companyUserId: null,
        qwUserId: null,
        typeCountMap: null,
        beginTime:null,
        endTime:null,
        appKey:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getAllCompany();

  },

  methods: {
    getAllCompany() {
      allList().then(response => {
        this.companyList = response.rows;
        this.companyList.push({dictLabel: "无",
          dictValue: "0"})
      });
    },
    /** 查询ai事件埋点统计列表 */
    getList() {
      this.loading = true;

      getFastGptPushTokenDeptTotal(this.queryParams).then(response => {
        this.fastGptPushTokenTotalList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    normalizer(node) {
      return {
        id: node.id,
        label: node.label,
        children: node.children,
        disabled: node.disabled
      }
    },
    handleAppKeyChange(value) {
      const node = this.findNodeById(this.appKeyOptions, value);
      if (!node) {
        this.selectedAppKeyLabel = '';
        return;
      }

      // 如果是子节点，则找父节点 label
      if (node.parentLabel) {
        this.queryParams.appKey = node.parentLabel;
        this.selectedAppKeyLabel = node.parentLabel;
        this.selectedAppKey = this.selectedAppKeyLabel;
      } else {
        this.queryParams.appKey = node.label;
        this.selectedAppKeyLabel = node.label;
        this.selectedAppKey = this.selectedAppKeyLabel;
      }
    },
    findNodeById(nodes, id) {
      for (const node of nodes) {
        if (node.id === id) return node;
        if (node.children) {
          const found = this.findNodeById(node.children, id);
          if (found) return found;
        }
      }
      return null;
    },
    changeTime(){
      if(this.createTime!=null){
        this.queryParams.beginTime=this.createTime[0];
        this.queryParams.endTime=this.createTime[1];
      }else{
        this.queryParams.beginTime=null;
        this.queryParams.endTime=null;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        roleId: null,
        count: null,
        type: null,
        companyId: null,
        companyUserId: null,
        qwUserId: null,
        statTime: null
      };
      this.resetForm("form");
    },
    getPercentageColor(percentage) {
      // HSL模式从黄色(60度)渐变到红色(0度)
      const percent = Math.min(100, Math.max(0, parseFloat(percentage)));

      // 调整色相范围：从深黄色（40°）渐变到红色（0°）
      const hue = 40 - 40 * (percent / 100); // 初始 hue=40（深黄），终点 hue=0（红）

      // 提高饱和度（100%），亮度保持 50%（鲜艳但不刺眼）
      return `hsl(${hue}, 100%, 50%)`;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if(this.selectedAppKey === null || typeof this.selectedAppKey === 'undefined'){
        this.queryParams.appKey = null;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.selectedAppKey = null;
      this.selectedAppKeyLabel = '';
      this.selectedCompanyList = [];
      this.queryParams.appKey = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;

      if(this.selectedCompanyList != null && this.selectedCompanyList.length > 0) {
        this.queryParams.userIds = this.selectedCompanyList;
      }else {
        this.queryParams.userIds = [];
      }
      this.$confirm('是否确认导出所有ai事件埋点统计数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportFastgptEventLogTotal(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
