<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-row>
          <el-form>
            <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button type="info" v-hasPermi="['print:version:loglist']" icon="HomeFilled" @click="handleVersionLog" :disabled="!currentRow"> 版本操作轨迹查询 </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" highlight-current-row @current-change="handleCurrentChange">
      <el-table-column align="center" label="模版编码" prop="templateCode" width="200px" show-overflow-tooltip />
      <el-table-column align="center" label="版本号" prop="versionNumber" 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="outputType" show-overflow-tooltip />
      <el-table-column align="center" label="是否允许签章" prop="allowSeal" show-overflow-tooltip />
      <el-table-column align="center" label="是否启用" prop="versionActiveStatus">
        <template #default="scope">
          <el-switch v-model="scope.row.versionActiveStatus" active-value="Y" inactive-value="N" @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" prop="policyNumber" width="145px">
        <template #default="scope">
          <el-button v-hasPermi="['print:version:preview']" icon="View" link type="primary" @click="handlePreview(scope.row)"> 预览 </el-button>
          <el-button v-hasPermi="['print:version:downloadmsg']" icon="Download" link type="primary" @click="downLoadMsg(scope.row.templateId)"> 下载报文样例 </el-button>
          <el-button v-hasPermi="['print:version:download']" icon="Download" link type="primary" @click="handleDownload(scope.row)"> 下载附件 </el-button>
        </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>
  <VersionLogDialog v-model="versionLogVisible" :templateCode="currentRow?.templateCode" />
</template>

<script setup name="ControVersial" lang="ts">
import { TemplateInfoQuery, TemplateInfoVO } from '@/api/print/template/templateInfotypes';
import { changeTemplateVsersionStatus, queryControversialList, templetPreview, queryTemplateList } from '@/api/print/template';
import { getDownloadAttType } from '@/api/print/review';
import { RoleVO } from '@/api/system/role/types';
import { changeRoleStatus } from '@/api/system/role';
import { getInfo } from '@/api/login';
import VersionLogDialog from '@/views/print/version/versionLog.vue';

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 queryFormRef = ref<ElFormInstance>();
const loading = ref(false);
const tempInfoList = ref<TemplateInfoVO[]>([]);
const total = ref(0);
const currentRow = ref<TemplateInfoVO | null>(null);
const versionLogVisible = ref(false);
const templateList = ref<any[]>([]);
const filteredList = ref<any[]>([]);
const likeName = ref('');

const data = reactive<SinglePageData<TemplateInfoQuery>>({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    systemOwner: undefined,
    templateCode: undefined,
    moduleOwner: undefined,
    printSystem: undefined,
    params: {}
  },
  rules: {}
});
const { queryParams, rules } = toRefs(data);

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    systemOwner: undefined,
    templateCode: undefined,
    moduleOwner: undefined,
    printSystem: undefined,
    params: {}
  };
  handleQuery();
};

/** 打印预览 */
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 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 getList = async () => {
  loading.value = true;
  const res = await queryControversialList(queryParams.value);
  tempInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

const handleStatusChange = async (row: TemplateInfoVO) => {
  let text = row.versionActiveStatus === 'Y' ? '启用' : '停用';
  try {
    await proxy?.$modal.confirm('确认要"' + text + '""' + row.templateName + '"模版吗?');
    await changeTemplateVsersionStatus(row.templateId, row.versionActiveStatus);
    proxy?.$modal.msgSuccess(text + '成功');
  } catch {
    row.versionActiveStatus = row.versionActiveStatus === 'Y' ? 'N' : 'Y';
  }
};

/**
 * 下载报文样例
 */
const downLoadMsg = (templateId) => {
  proxy?.download(
    'print/parameterPreviewValues/downLoadMsg',
    {
      templateId: templateId
    },
    `msg_${templateId}_${new Date().getTime()}.txt`
  );
};

// 表格行选择事件
const handleCurrentChange = (row: TemplateInfoVO | null) => {
  currentRow.value = row;
};

// 版本操作轨迹查询
const handleVersionLog = () => {
  if (!currentRow.value) {
    proxy?.$modal.msgWarning('请先选择一条记录');
    return;
  }
  versionLogVisible.value = true;
};

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