<template>
  <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" :rules="rules" :inline="true" label-width="130px" label-position="left">
          <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 type="primary" icon="Search" @click="handleQuery">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button v-hasPermi="['print:temp:add']" type="primary" icon="Plus" @click="handleAdd">新增</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" show-overflow-tooltip>
        <template #default="scope">
          <el-tooltip content="继续" placement="top">
            <el-button v-hasPermi="['print:temp:go']" link type="primary" icon="Pointer" @click="handleGoon(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button v-hasPermi="['print:temp:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
          </el-tooltip>
        </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>
  <el-card shadow="hover">
    <el-steps v-if="showSteps" :space="400" :active="activeStep" simple style="margin-top: 30px">
      <el-step title="模版定义" icon="Edit" />
      <el-step title="模版材料维护" icon="UploadFilled" />
      <el-step title="模版参数解析" icon="Picture" />
      <el-step title="模版确认" icon="Picture" />
    </el-steps>
  </el-card>
</template>

<script setup name="Construct" lang="ts">
import { TemplateInfoQuery, TemplateInfoVO } from '@/api/print/template/templateInfotypes';
import { listTemplateInfo, selectTempByTempCode, queryTemplateList, templateInfoDelete } 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 queryFormRef = ref<ElFormInstance>();
const loading = ref(false);
const showSteps = ref(true);
const tempInfoList = ref<TemplateInfoVO[]>([]);
const activeStep = ref(0);
const total = ref(0);
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 resetQuery = async () => {
  // 1. 重置queryParams到初始值
  Object.assign(queryParams.value, initialQueryParams);

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

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

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

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

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

const handleAdd = () => {
  router.push('/print/template/printTempConstruct/templatDetail');
};

const handleGoon = (row) => {
  const templateId = row.templateId;
  router.push('/print/template/printTempConstruct/templatDetail/' + templateId);
};

const handleDelete = (row) => {
  proxy?.$modal
    .confirm(`是否要删除${row.templateName}，版本号为${row.versionNumber}的模板信息？`)
    .then(async () => {
      loading.value = true;
      try {
        const res = await templateInfoDelete(row);
        if (res.code === 200) {
          proxy?.$modal.msgSuccess('删除成功');
          getList(); // 刷新列表
        } else {
          proxy?.$modal.msgError(res.msg || '删除失败');
        }
      } catch (error) {
        proxy?.$modal.msgError('删除失败');
      } finally {
        loading.value = false;
      }
    })
    .catch(() => {
      // 用户取消删除
    });
};

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