<template>
  <el-dialog v-model="visible" :title="t('qc.task.qcLog.title')" width="1200px" append-to-body @close="handleClose">
    <div class="mb-4">
      <el-form :inline="true" :model="queryParams" label-width="120px">
        <el-form-item :label="t('qc.task.qcLog.result')">
          <el-select v-model="queryParams.result" :placeholder="t('qc.task.qcLog.resultPlaceholder')" clearable style="width: 150px">
            <el-option :label="t('qc.task.qcLog.pass')" :value="1" />
            <el-option :label="t('qc.task.qcLog.reject')" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('qc.task.qcLog.executeTime')">
          <el-date-picker
            v-model="queryParams.executeTimeRange"
            type="daterange"
            :range-separator="t('qc.task.qcLog.rangeSeparator')"
            :start-placeholder="t('qc.task.qcLog.startDate')"
            :end-placeholder="t('qc.task.qcLog.endDate')"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">{{ t('qc.task.qcLog.search') }}</el-button>
          <el-button icon="Refresh" @click="handleReset">{{ t('qc.task.qcLog.reset') }}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table v-loading="loading" :data="logList" border max-height="500">
      <el-table-column prop="id" :label="t('qc.task.qcLog.index')" width="80" />
      <el-table-column prop="executeTime" :label="t('qc.task.qcLog.executeTime')" width="180" />
      <el-table-column :label="t('qc.task.qcLog.result')" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.result === 1" type="success">{{ t('qc.task.qcLog.pass') }}</el-tag>
          <el-tag v-else-if="scope.row.result === 2" type="danger">{{ t('qc.task.qcLog.reject') }}</el-tag>
          <el-tag v-else type="info">{{ t('qc.task.qcLog.unknown') }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="t('qc.task.qcLog.questionType')" width="120" show-overflow-tooltip>
        <template #default="scope">
          <dict-tag :options="qc_question_type" :value="scope.row.questionType" />
        </template>
      </el-table-column>
      <el-table-column prop="opinion" :label="t('qc.task.qcLog.opinion')" min-width="150" show-overflow-tooltip />
      <el-table-column prop="designatedDealer" :label="t('qc.task.qcLog.designatedDealer')" width="120" />
      <el-table-column :label="t('qc.task.qcLog.deadline')" width="120">
        <template #default="scope">
          {{ scope.row.deadline ? parseTime(scope.row.deadline, '{y}-{m}-{d}') : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="actualDealer" :label="t('qc.task.qcLog.actualDealer')" width="120" />
      <el-table-column prop="dealTime" :label="t('qc.task.qcLog.dealTime')" width="180" />
      <el-table-column prop="createBy" :label="t('qc.task.qcLog.createBy')" width="120" />
      <el-table-column prop="createTime" :label="t('qc.task.qcLog.createTime')" width="180" />
      <el-table-column :label="t('qc.task.qcLog.action')" width="220" align="center" fixed="right">
        <template #default="scope">
          <el-button
            v-if="scope.row.qcVersion"
            type="primary"
            icon="Download"
            style="padding: 0 5px; font-size: 10px; height: 24px"
            @click="handleDownloadQcVersion(scope.row)"
          >
            {{ t('qc.task.qcLog.downloadQcVersion') }}
          </el-button>
          <el-button
            v-if="scope.row.dealVersion"
            type="success"
            icon="Download"
            style="padding: 0 5px; font-size: 10px; height: 24px"
            @click="handleDownloadDealVersion(scope.row)"
          >
            {{ t('qc.task.qcLog.downloadDealVersion') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="mt-4">
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handlePagination"
      />
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, toRefs } from 'vue';
import { useI18n } from 'vue-i18n';
import { listTaskLogOnDetail } from '@/api/qc/task';
import { TaskLogVO } from '@/api/qc/task/types';
import { downloadDocumentFile } from '@/api/document/document';
import { ElMessage } from 'element-plus';

const { t } = useI18n();

interface Props {
  modelValue: boolean;
  detailId?: number;
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  detailId: undefined
});

const emit = defineEmits<Emits>();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { qc_question_type } = toRefs<any>(proxy?.useDict('qc_question_type'));

const visible = ref(false);
const loading = ref(false);
const logList = ref<TaskLogVO[]>([]);
const total = ref(0);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  detailId: undefined as number | undefined,
  result: undefined as number | undefined,
  executeTimeRange: [] as string[],
  params: {} as any
});

/** 获取审核记录列表 */
const fetchLogs = async () => {
  if (!queryParams.detailId) return;

  try {
    loading.value = true;

    // 处理时间范围参数
    const params: any = {};
    if (queryParams.executeTimeRange && queryParams.executeTimeRange.length === 2) {
      params.beginExecuteTime = queryParams.executeTimeRange[0];
      params.endExecuteTime = queryParams.executeTimeRange[1];
    }

    const requestParams = {
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      detailId: queryParams.detailId,
      result: queryParams.result,
      params: params
    };

    const res = await listTaskLogOnDetail(requestParams);
    if (res.code === 200) {
      logList.value = res.rows || [];
      total.value = res.total || 0;
    } else {
      proxy?.$modal.msgError(res.msg || t('qc.task.qcLog.getLogsFailed'));
    }
  } catch (error) {
    console.error('获取审核记录失败:', error);
    proxy?.$modal.msgError(t('qc.task.qcLog.getLogsFailed'));
  } finally {
    loading.value = false;
  }
};

/** 查询 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  fetchLogs();
};

/** 重置 */
const handleReset = () => {
  queryParams.result = undefined;
  queryParams.executeTimeRange = [];
  queryParams.pageNum = 1;
  fetchLogs();
};

/** 分页变化 */
const handlePagination = (pageNum: number, pageSize: number) => {
  queryParams.pageNum = pageNum;
  queryParams.pageSize = pageSize;
  fetchLogs();
};

/** 关闭弹窗 */
const handleClose = () => {
  emit('update:modelValue', false);
};

/** 下载质控版本 */
const handleDownloadQcVersion = async (row: TaskLogVO) => {
  if (!row.qcVersion) {
    ElMessage.warning(t('qc.task.qcLog.noQcVersion'));
    return;
  }
  try {
    await downloadDocumentFile(Number(row.qcVersion), `质控版本_${row.id}`);
  } catch (error) {
    console.error('下载质控版本失败:', error);
    ElMessage.error(t('qc.task.qcLog.downloadQcVersionFailed'));
  }
};

/** 下载处理版本 */
const handleDownloadDealVersion = async (row: TaskLogVO) => {
  if (!row.dealVersion) {
    ElMessage.warning(t('qc.task.qcLog.noDealVersion'));
    return;
  }
  try {
    await downloadDocumentFile(Number(row.dealVersion), `处理版本_${row.id}`);
  } catch (error) {
    console.error('下载处理版本失败:', error);
    ElMessage.error(t('qc.task.qcLog.downloadDealVersionFailed'));
  }
};

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  (newVal) => {
    visible.value = newVal;
    if (newVal && props.detailId) {
      // 重置查询参数
      queryParams.detailId = props.detailId;
      queryParams.pageNum = 1;
      queryParams.result = undefined;
      queryParams.executeTimeRange = [];
      queryParams.params = {};
      fetchLogs();
    }
  },
  { immediate: true }
);

// 监听 visible 变化
watch(visible, (newVal) => {
  if (!newVal) {
    emit('update:modelValue', false);
  }
});
</script>

<style scoped lang="scss">
// 可以添加自定义样式
</style>
