<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" :rules="rules" label-position="left" label-width="130px">
            <el-row>
              <el-form-item label="业务号码" prop="businessNumber">
                <el-input v-model="queryParams.businessNumber" placeholder="请输入业务号码" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="归属系统" prop="fromSystem">
                <el-select v-model="queryParams.fromSystem" placeholder="请输入归属系统">
                  <el-option v-for="dict in sys_from_system" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="归属模块" prop="fromModule">
                <el-select v-model="queryParams.fromModule" placeholder="请输入归属模块">
                  <el-option v-for="dict in print_module" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="模版编码" prop="templateCode">
                <el-select v-model="queryParams.templateCode" placeholder="请输入模版编码" clearable @change="selectTemp">
                  <template #header>
                    <el-input v-model="likeName" placeholder="可根据模版名称模糊查询" @input="filterByTemplateName" />
                  </template>
                  <el-option
                    v-for="dict in filteredList"
                    :key="dict.templateCode"
                    :label="dict.templateName + '-v' + dict.version"
                    :value="dict.templateCode + '&' + dict.version"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="打印时间" prop="dateRange">
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  format="YYYY-MM-DD"
                  :default-time="[
                    new Date(2000, 1, 1, 0, 0, 0),
                    new Date(2000, 1, 1, 23, 59, 59)
                  ]"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>
            </el-row>
            <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>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="templatePrintLogList">
        <el-table-column label="业务号码" align="center" prop="businessNumber" />
        <el-table-column label="模版名称" align="center" prop="templateName" />
        <el-table-column label="打印模板版本号" align="center" prop="versionNumber" />
        <el-table-column label="归属系统" align="center" prop="fromSystem" >
          <template #default="scope">
            <dict-tag :options="sys_from_system" :value="scope.row.fromSystem" />
          </template>
        </el-table-column>
        <el-table-column label="打印时间" align="center" prop="printTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.printTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button v-hasPermi="['print:templatePrintLog:view']" link type="primary" icon="View" @click="handleLook(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

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

<script setup name="TemplatePrintLog" lang="ts">
import { listTemplatePrintLog } from '@/api/print/log/tempLog';
import { TemplatePrintLogVO, TemplatePrintLogQuery, TemplatePrintLogForm } from '@/api/print/log/tempLogtypes';
import { queryTemplateList } from '@/api/print/template';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { print_module } = toRefs<any>(proxy?.useDict('print_module'));
const { sys_from_system } = toRefs<any>(proxy?.useDict('sys_from_system'));

const templatePrintLogList = ref<TemplatePrintLogVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const templatePrintLogFormRef = ref<ElFormInstance>();
const templateList = ref<any[]>([]);
const filteredList = ref<any[]>([]);
const likeName = ref('');

const initFormData: TemplatePrintLogForm = {
  printId: undefined,
  businessNumber: undefined,
  templateCode: undefined,
  versionNumber: undefined,
  fromSystem: undefined,
  printTime: undefined,
  messageLogId: undefined,
  printAttachmentUrl: undefined,
  ossId: undefined,
  printCompleteTime: undefined
};
const data = reactive<PageData<TemplatePrintLogForm, TemplatePrintLogQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    businessNumber: undefined,
    templateCode: undefined,
    versionNumber: undefined,
    fromSystem: undefined,
    printTime: undefined,
    messageLogId: undefined,
    printAttachmentUrl: undefined,
    ossId: undefined,
    printCompleteTime: undefined,
    params: {}
  },
  rules: {
    businessNumber: [
      {
        validator: (rule, value, callback) => {
          // 如果有业务号码，则通过校验
          if (value) return callback();

          // 没有业务号码时检查日期范围是否完整
          if (!dateRange.value || !dateRange.value[0] || !dateRange.value[1]) {
            return callback(new Error('未填写业务号码时，必须选择起止日期'));
          }
          callback();
        },
        trigger: 'blur'
      }
    ],
    dateRange: [
      {
        validator: (rule, value, callback) => {
          // 如果有业务号码，不校验日期
          if (queryParams.value.businessNumber) return callback();

          if (!dateRange.value || !dateRange.value[0] || !dateRange.value[1]) {
            return callback();
          }

          // 检查日期范围不超过1个月
          const start = new Date(dateRange.value[0]);
          const end = new Date(dateRange.value[1]);
          const diffMonth = (end.getFullYear() - start.getFullYear()) * 12 + (end.getMonth() - start.getMonth());

          if (diffMonth > 1 || (diffMonth === 1 && end.getDate() > start.getDate())) {
            return callback(new Error('日期范围不能超过1个月'));
          }
          callback();
        },
        trigger: ['change', 'blur']
      }
    ]
  }
});

const { queryParams, rules } = toRefs(data);

/** 查询模版打印记录列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTemplatePrintLog(proxy?.addDateRange(queryParams.value, dateRange.value, 'Print'));
  templatePrintLogList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  templatePrintLogFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = async () => {
  try {
    await queryFormRef.value?.validate();
    queryParams.value.pageNum = 1;
    getList();
  } catch (error) {
  }
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};
const handleLook = (row) => {
  proxy?.$download.oss(row.ossId);
};

// 获取模板列表
const quryTemplateList = async () => {
  const res = await queryTemplateList();
  templateList.value = res.data.tempList;
  filteredList.value = templateList.value;
};

// 模糊查询
const filterByTemplateName = () => {
  if (likeName.value) {
    filteredList.value = templateList.value.filter((item) => {
      return item.templateName.includes(likeName.value);
    });
  } else {
    filteredList.value = templateList.value;
  }
};

// 选择模板
const selectTemp = async (newVal) => {
  const val = newVal.split('&');
  queryParams.value.templateCode = val[0];
  //const res = await selectTempByTempCode({ templateCode: val[0] });
  //Object.assign(queryParams.value, res.data);
};

onMounted(() => {
  getList();
  quryTemplateList();
});
</script>
