<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-if="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" v-model="queryParams" :inline="true" :rules="rules" label-position="left" label-width="130px">
            <el-row>
              <el-form-item label="归属系统" prop="systemOwner">
                <el-select v-model="queryParams.systemOwner" 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="moduleOwner">
                <el-select v-model="queryParams.moduleOwner" 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-form-item label="打印归属" prop="printSystem">
                <el-select v-model="queryParams.printSystem" placeholder="请输入打印归属">
                  <el-option v-for="dict in print_action_system" :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="提审时间">
                <el-date-picker
                  v-model="dateRange"
                  end-placeholder="结束日期"
                  range-separator="-"
                  start-placeholder="开始日期"
                  type="daterange"
                  value-format="YYYY-MM-DD"
                >
                </el-date-picker>
              </el-form-item>
            </el-row>
            <el-form>
              <el-button icon="Search" type="primary" @click="handleQuery">查询</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-card shadow="hover">
      <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="tempInfoList">
        <el-table-column align="center" label="模版编码" prop="templateCode" show-overflow-tooltip />
        <el-table-column align="center" label="模版名称" prop="templateName" show-overflow-tooltip />
        <el-table-column align="center" label="归属系统" prop="systemOwner" show-overflow-tooltip />
        <el-table-column align="center" label="归属模块" prop="moduleOwner" show-overflow-tooltip />
        <el-table-column align="center" label="打印归属" prop="printSystem" show-overflow-tooltip />
<!--        <el-table-column align="center" label="打印类型" prop="printType" show-overflow-tooltip />-->
<!--        <el-table-column align="center" label="模版格式" prop="templateType" show-overflow-tooltip />-->
        <el-table-column align="center" label="输出格式" prop="outputType" show-overflow-tooltip />
        <el-table-column align="center" label="是否允许签章" prop="allowSeal" show-overflow-tooltip />
        <el-table-column align="center" label="版本号" prop="versionNumber" show-overflow-tooltip />
        <el-table-column align="center" label="操作" prop="policyNumber" width="120px">
          <template #default="scope">
            <el-space align="center" direction="vertical">
              <el-button v-hasPermi="['print:review:download']" icon="Download" link type="primary" @click="handleDownload(scope.row)">
                下载模版
              </el-button>
              <el-button v-hasPermi="['print:temp:preview']" icon="View" link type="primary" @click="handlePreview(scope.row)"> 打印预览 </el-button>
              <el-button v-hasPermi="['print:review:detail']" icon="Connection" link type="primary" @click="handleShowDetail(scope.row)"> 查看详情 </el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total" @pagination="getList" />
    </el-card>
  </div>
</template>

<script lang="ts" name="ReviewInfo" setup>
import { TemplateInfoQuery, TemplateInfoVO } from '@/api/print/template/templateInfotypes';
import { getDownloadAttType, listReviewInfo } from '@/api/print/review';
import { templetPreview, queryTemplateList, selectTempByTempCode  } from '@/api/print/template';

const router = useRouter();
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 { print_action_system } = toRefs<any>(proxy?.useDict('print_action_system'));

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

const tempInfoList = ref<TemplateInfoVO[]>([]);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const loading = ref(false);
const templateList = ref<any[]>([]);
const filteredList = ref<any[]>([]);
const likeName = ref('');

const initialQueryParams: TemplateInfoQuery = {
  pageNum: 1,
  pageSize: 10,
  systemOwner: undefined,
  templateCode: undefined,
  moduleOwner: undefined,
  printSystem: undefined,
  params: {}
};

const data = reactive<SinglePageData<TemplateInfoQuery>>({
  queryParams: { ...initialQueryParams },
  rules: {}
});
const { queryParams, rules } = toRefs(data);

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

const getList = async () => {
  loading.value = true;
  const res = await listReviewInfo(proxy?.addDateRange(queryParams.value, dateRange.value, 'Create'));
  tempInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 重置按钮操作 */
const resetQuery = async () => {
  // 1. 重置queryParams到初始值
  Object.assign(queryParams.value, initialQueryParams);

  // 2. 重置日期范围
  dateRange.value = ['', ''];

  // 3. 等待DOM更新后重置表单
  await nextTick();

  // 4. 重置表单验证状态和字段值
  queryFormRef.value?.resetFields();

  // 5. 执行查询（保留分页参数）
  handleQuery();
};

const handleDownload = async (row) => {
  loading.value = true;
  const res = await getDownloadAttType(row.templateId);
  if (res.code === 200 && res.data.downloadType === 'doc') {
    await proxy?.$download.oss(res.data.ossId);
  } else if (res.code === 200 && res.data.downloadType === 'zip') {
    await proxy?.$download.zip(
      '/print/reviewInfo/getDownloadAttZip?templateId=' + row.templateId,
      row.templateCode + '-' + row.templateName + '-' + row.versionNumber + '.zip'
    );
  } else {
    proxy?.$modal.msgError(res.msg);
  }
  loading.value = false;
};

const handlePreview = async (row) => {
  loading.value = true;
  const res = await templetPreview(row.templateId);
  if (res.code === 200) {
    proxy?.$download.oss(res.data.ossId);
    loading.value = false;
  } else {
    proxy?.$modal.msgError(res.msg);
    loading.value = false;
  }
};

const handleShowDetail = (row) => {
  const templateId = row.templateId;
  router.push('/print/temp/review/ReviewDetail/' + templateId);
};

// 获取模板列表
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>
