<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">
        <select-tree
          v-model="selectedCompanyList"
          :raw-data="deptList"
          placeholder="请选择销售"
          :parentSelectable="true"
          :multiple="true"
          component-width="300px"
          :max-display-tags="3"
          :check-strictly="false"
          :return-leaf-only="false"
          @change="handleMultiChange"
        ></select-tree>
      </el-form-item>
      <el-form-item label="销售" prop="nickName" v-if="queryParams.companyId">
        <el-select v-model="queryParams.companyUserId" remote
                   placeholder="请选择"
                   filterable clearable
                   style="width: 100%;"
                   @keyup.enter.native="handleQuery"
                   @change="handleCompanyUserId"
        >
          <el-option
            v-for="dict in companyUserList"
            :key="`${dict.nickName} - ${dict.userName}`"
            :label="`${dict.nickName} - ${dict.userName}`"
            :value="dict.userId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="AppKey" prop="appKey">
        <div style="display: flex; align-items: center;">
          <tree-select
            v-model="selectedAppKey"
            :options="appKeyOptions"
            :normalizer="normalizer"
            :disable-branch-nodes="false"
            placeholder="请选择 AppKey"      style="width: 300px;"
            @input="handleAppKeyChange"
          />
        </div>
      </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">
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fastGpt:fastgptEventLogTotal:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="fastgptEventLogTotalList" :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="roleName" />
      <el-table-column label="时间" align="center" prop="statTime" />
      <el-table-column
        v-for="dict in sortedTypeOptions"
        :key="dict.dictValue"
        :label="dict.dictLabel"
        align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.typeCountMap ? scope.row.typeCountMap[dict.dictValue] : '' }}</span>
          <span v-if="dict.dictValue !== '11'"
                :style="{ fontSize: '12px', marginLeft: '5px',
          color: getPercentageColor((scope.row.typeCountMap[dict.dictValue] / scope.row.typeCountMap[2]) * 100) }">
      ({{ ((scope.row.typeCountMap[dict.dictValue] / scope.row.typeCountMap[2]) * 100).toFixed(2) }}%)
    </span>
        </template>
      </el-table-column>
      <!-- 新增金额列 -->
      <el-table-column label="金额" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.typeCountMap && scope.row.typeCountMap['11'] ? (scope.row.typeCountMap['11'] / 100000).toFixed(4) : '0.0000' }}</span>
        </template>
      </el-table-column>
    </el-table>

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

<script>
import { listFastgptEventLogTotal, getFastgptEventLogTotal, delFastgptEventLogTotal, addFastgptEventLogTotal, updateFastgptEventLogTotal, exportFastgptEventLogTotal, getFastGptRoleAppKeyList} from "@/api/fastGpt/fastgptEventLogTotal";
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'



export default {
  name: "FastgptEventLogTotal",
  components: {SelectTree,TreeSelect},
  data() {
    return {
      createTime:null,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      selectedCompanyList: [],
      deptList: [],
      companyUserList: [],
      selectedAppKey: null,
      selectedAppKeyLabel: '',
      appKeyOptions: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // ai事件埋点统计表格数据
      fastgptEventLogTotalList: [],
      // 弹出层标题
      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.getDicts("sys_fastgpt_event_log_type").then(response => {
      this.typeOptions = response.data;
    });

    getDeptData().then(response => {
      this.deptList = response.data;
    });
    getFastGptRoleAppKeyList().then(res => {
      this.appKeyOptions = res.data.map(item => ({
        id: `p_${item.roleId}`,
        label: item.roleName,
        children: (item.roleList || []).map(child => ({
          id: `c_${child.roleId}`,
          label: child.roleName,
          parentId: `p_${item.roleId}`, // 记录父节点 ID
          parentLabel: item.roleName,   // 记录父节点 label
          disabled: true
        }))
      }));
    });

  },
  // 在 data() 中添加一个新的计算属性或方法来处理排序后的 typeOptions
  computed: {
    sortedTypeOptions() {
      if (!this.typeOptions || this.typeOptions.length === 0) return [];

      // 将 dictValue 为 '11' 的选项过滤出来并放到最后
      const normalOptions = this.typeOptions.filter(option => option.dictValue !== '11');
      const lastOption = this.typeOptions.find(option => option.dictValue === '11');

      if (lastOption) {
        return [...normalOptions, lastOption];
      }
      return normalOptions;
    }
  },

  methods: {
    /** 查询ai事件埋点统计列表 */
    getList() {
      this.loading = true;
      if(this.selectedCompanyList != null && this.selectedCompanyList.length > 0) {
        this.queryParams.userIds = this.selectedCompanyList;
      }else {
        this.queryParams.userIds = [];
      }

      listFastgptEventLogTotal(this.queryParams).then(response => {
        console.log(response)
        this.fastgptEventLogTotalList = response.data.list;
        this.total = response.data.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(){
      console.log(this.createTime);
      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;
      }
      console.log(this.queryParams.beginTime);
      console.log(this.queryParams.endTime);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    handleMultiChange(e){

    },
    handleCompanyUserId(val){
      if(val == null || val === '') {
        this.queryParams.companyUserId = null;
        this.queryParams.userIds = [];
      }
      console.log(val);
    },
    // 表单重置
    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;
      console.log(this.selectedAppKey)
      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>
