<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="积分事由" prop="pointReason">
              <el-input v-model="queryParams.pointReason" placeholder="请输入积分事由" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="积分变动时间" prop="changeTime" style="width: 330px">
              <el-date-picker
                clearable
                v-model="queryParams.changeTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="8" v-if="type == 'log'">
                <el-button type="danger" @click="showTrend">积分趋势分析</el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table v-loading="loading" :data="extractLogList">
            <el-table-column label="序号" width="50px" type="index"></el-table-column>
            <el-table-column
              :label="label"
              :align="align || 'center'"
              :min-width="minWidth || '100px'"
              v-for="{ label, prop, align, minWidth } in headers"
              :key="prop"
            >
              <template #default="{ row }">
                <span v-if="prop == 'points'">{{ +row.points }}</span>
                <span v-else>{{ row[prop] || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="type == 'log'" label="操作" align="center" min-width="120px" fixed="right" class-name="small-padding fixed-width">
              <template #default="{ row }">
                <el-button link type="danger" @click="handleDel(row)">删除</el-button>
                <el-divider direction="vertical" />
                <el-button link type="success" @click="handleVerify(row)">校验</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="page.total > 0" :total="page.total" v-model:page="page.pageNum" v-model:limit="page.pageSize" @pagination="getList" />
          <div v-if="type?.includes('review')">
            <div class="model-title">积分复核</div>
            <div>
              <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="复核状态：" prop="checkStatus">
                  <el-radio-group v-if="type == 'review'" v-model="form.checkStatus" @change="changeReviewStatus">
                    <el-radio v-for="item in reviewOptions" :key="item.value" :label="item.value">
                      {{ item.label }}
                    </el-radio>
                  </el-radio-group>
                  <span v-else>{{ getStatus() }}</span>
                </el-form-item>
                <el-form-item label="复核理由：" prop="remark">
                  <el-input
                    v-if="type == 'review'"
                    v-model="form.remark"
                    type="textarea"
                    :rows="5"
                    resize="none"
                    placeholder="请输入复核理由"
                    maxlength="140"
                    show-word-limit
                  ></el-input>
                  <span v-else>{{ form.remark }}</span>
                </el-form-item>
              </el-form>
              <div style="flex: 1; text-align: right">
                <el-button @click="Cancel">返回</el-button>
                <el-button type="primary" v-if="type == 'review'" @click="confirmReview">确定</el-button>
              </div>
            </div>
          </div>
        </el-card>
        <el-dialog title="积分趋势分析" v-model="trendDialogVisible" width="800px" :before-close="closeDialog">
          <div class="text-right">
            <el-button-group>
              <el-button
                :type="`${activeTime == item.value ? 'primary' : ''}`"
                v-for="item in timeOptions"
                @click="changeTime(item.value)"
                >{{ item.label }}</el-button
              >
            </el-button-group>
          </div>

          <div class="trend-main mt-[10px]" v-loading="chartLoading" ref="trendMainRef"></div>
          <template #footer>
            <span>
              <el-button @click="closeDialog">关闭</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { getTableList, ReviewPoints, getReviewInfoById, deleteLog, getChartData } from '@/api/points/detail';
import * as echarts from 'echarts';
import { verifyHmac } from '@/api/project/maintain';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const id = computed(() => proxy?.$route.query.id);
const type = computed(() => proxy?.$route.query.type);
const extractLogList = ref<any[]>([]);
const loading = ref(true);
const showSearch = ref(true);

const route = useRoute();

const queryFormRef = ref<ElFormInstance>();

interface Header {
  label: string;
  prop: string;
  align?: 'center' | 'left' | 'right';
  minWidth?: string | number;
}
const headers = ref<Header[]>([
  {
    label: '编号',
    prop: 'id'
  },
  {
    label: '积分事由',
    prop: 'pointReason'
  },
  {
    label: '积分分值',
    prop: 'points'
  },
  {
    label: '积分变动时间',
    prop: 'updateTime'
  }
]);

const statusOptions = {
  0: '停用',
  1: '启用'
};
const page = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});
const queryParams = ref<any>({
  pointReason: '',
  changeTime: []
});

/** 查询expert列表 */
const getList = async () => {
  loading.value = true;
  let startDate = queryParams.value.changeTime[0] || '';
  let endDate = queryParams.value.changeTime[1] || '';
  const res = await getTableList({ ...queryParams.value, ...page.value, startDate, endDate, expertId: id.value });
  extractLogList.value = res.rows;
  page.value.total = res.total;
  loading.value = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  page.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const formRef = ref(null);
const reviewOptions = [
  {
    label: '认可',
    value: 2
  },
  {
    label: '冻结',
    value: 1
  }
];
const getStatus = () => {
  let item = reviewOptions.find((item) => item.value == form.value.checkStatus);
  return item?.label || '';
};
const form = ref({
  expertId: id.value,
  checkStatus: 2,
  remark: '同意'
});
const rules = {
  checkStatus: [{ required: type.value == 'review', message: '请选择审核状态', trigger: 'blur' }],
  remark: [
    {
      required: type.value == 'review',
      validator: (rule: any, value: any, callback: any) => {
        if (form.value.checkStatus == 0 && value == '') {
          return callback(new Error('冻结状态需要填写冻结理由'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};
const changeReviewStatus = () => {
  if (form.value.checkStatus == 2) {
    form.value.remark = '同意';
  } else {
    form.value.remark = '';
  }
};
const Cancel = () => {
  proxy?.$tab.closePage(proxy?.$route).then(() => {
    proxy?.$router.replace(type.value == 'log' ? '/points/expertPointManage' : '/points/review');
  });
};
const confirmReview = () => {
  formRef.value.validate(async (valid: any) => {
    if (!valid) return;
    ElMessageBox.confirm(`是否确定${form.value.checkStatus == 1 ? '冻结' : '认可'}该专家积分`, '系统提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        let params = {
          ...form.value,
          id: id.value
        };
        let res = await ReviewPoints(params);
        if (res.code != 200) {
          ElNotification({
            title: '提示',
            message: res.msg,
            type: 'error'
          });
          return;
        }
        ElNotification({
          title: '提示',
          message: '积分复核成功',
          type: 'success'
        });
        Cancel();
      })
      .catch(() => {});
  });
};
const getReviewInfo = async () => {
  let res = await getReviewInfoById(id.value);
  if (res.code != 200) {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
    return;
  }
  form.value = res.data;
};

const handleDel = async (row: any) => {
  let params = {
    id: row.id,
    expertId: id.value
  };
  ElMessageBox.confirm(`是否确定删除该积分记录？`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await deleteLog(params);
      if (res.code != 200) {
        ElNotification({
          title: '提示',
          message: res.msg,
          type: 'error'
        });
        return;
      }
      ElNotification({
        title: '提示',
        message: '删除成功',
        type: 'success'
      });
      await getList();
    })
    .catch(() => {});
};

const trendDialogVisible = ref(false);
const trendMainRef = ref(null);
const trendMainRefChart = shallowRef();
const activeTime = ref('seven');
const timeOptions = [
  {
    value: 'seven',
    label: '近7天'
  },
  {
    value: 'month',
    label: '近30天'
  },
  {
    value: 'halfYear',
    label: '近半年'
  }
];

const changeTime = (time) => {
  activeTime.value = time;
  getTrendData();
};
const chartLoading = ref(false);
const setTrendChart = (data, xData) => {
  trendMainRefChart.value = echarts.init(trendMainRef.value);
  trendMainRefChart.value.setOption({
    grid: {
      top: 60,
      left: 32,
      right: 32,
      bottom: 32,
      containLabel: true
    },
    tooltop: {
      trigger: 'axis'
    },
    legend: {
      show: true,
      textStyle: {
        color: '#fff'
      },
      itemHeight: 16,
      top: 16,
      right: 32,
      selected: false,
      data: ['积分分值']
    },
    xAxis: {
      data: xData,
      type: 'category',
      axisLabel: {
        color: '#a4aab5',
        fontSize: 12,
        fontWeight: 400
      },
      axisTick: {
        show: false
      },
      axisLine: {
        lineStyle: {
          color: '#1d314d'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        color: '#a4aab5',
        fontSize: 12,
        fontWeight: 700
      },
      axisLine: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: '#1d314d'
        }
      }
    },
    series: [
      {
        name: '积分分值',
        data: data,
        type: 'line'
        // ...barStyle
      }
    ]
  });
};
const getTrendData = async () => {
  chartLoading.value = true;
  const params = {
    dayKey: activeTime.value,
    expertId: id.value
  };
  let res = await getChartData(params);
  if (res.code != 200) {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
    return;
  }
  setTrendChart(res.data.pointY, res.data.dayX);
  chartLoading.value = false;
};
const showTrend = async () => {
  trendDialogVisible.value = true;
  activeTime.value = 'seven';
  await getTrendData();
};
const closeDialog = () => {
  trendDialogVisible.value = false;
};

/**hmac校验*/
function handleVerify(row: any) {
  verifyHmac({
    bizType: 'point',
    id: row.id,
    fields: []
  })
    .then(result => {
      if (result.match) {
        ElMessage.success('校验通过');
      } else {
        ElMessage.error(`校验失败，该信息被篡改`);
      }
    })
    .catch(err => {
      ElMessage.error('接口请求失败: ' + (err.response?.data?.msg || err.message));
    });
}


onActivated(() => {
  getList();
  if (type.value == 'reviewshow') {
    getReviewInfo();
  }
});
onMounted(() => {
  getList();
  if (type.value == 'reviewshow') {
    getReviewInfo();
  }
});
</script>
<style lang="scss" scoped>
.model-title {
  margin-bottom: 24px;
  font-size: 20px;
  font-weight: bold;
  margin-top: 20px;
}
.trend-main {
  height: 420px;
  background-color: #0c2139;
  border-radius: 6px;
}
</style>
