<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="formRef" v-loading="loading" :model="basicParams" :rules="rules" :inline="true" label-width="130px" label-position="left">
            <el-row>
              <el-form-item label="主题" prop="title">
                <el-input v-model="basicParams.title" style="width: 800px" maxlength="50" show-word-limit placeholder="请输入主题" clearable />
              </el-form-item>
            </el-row>
            <el-form-item label="模版类型" prop="templateType">
              <el-select v-model="basicParams.templateType" placeholder="请输入模版类型" @change="templateTypeChange">
                <el-option v-for="dict in manual_template_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item v-if="basicParams.templateType === '1'" label="模版编码" prop="templateCode">
              <el-input v-model="basicParams.templateCode" placeholder="请输入模版编码" @change="templateCodeChange" />
            </el-form-item>

            <el-form-item v-if="false" label="模版编码" prop="templateCode">
              <el-select v-model="basicParams.templateCode" placeholder="请输入模版编码" @change="templateCodeChange">
                <el-option
                  v-for="dict in tempCodeList"
                  :key="dict.templateCode"
                  :label="dict.templateName + '-v' + dict.version"
                  :value="dict.templateCode + '-' + dict.version"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item v-if="false" label="模版版本号" prop="versionNumber">
              <el-input v-model="basicParams.versionNumber" clearable />
            </el-form-item>

            <el-form-item label="归属机构" prop="institution">
              <el-select v-model="basicParams.institution" placeholder="请输入归属机构" clearable @click="handleSelectClick">
                <template #header>
                  <el-input v-model="likeName" placeholder="可根据机构编码或名称模糊查询" @input="filterByManageCom"></el-input>
                </template>
                <el-option v-for="dict in filteredManagecom" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="false" label="服务商" prop="serviceId">
              <el-select v-model="basicParams.serviceId" placeholder="请输入发送类型">
                <el-option v-for="dict in serviceList" :key="dict.providerId" :label="dict.providerName" :value="dict.providerId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="发送类型" prop="sendType">
              <el-select v-model="basicParams.sendType" placeholder="请输入发送类型">
                <el-option v-for="dict in manual_send_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="basicParams.sendType === '2'" label="发送时间" prop="sendTime">
              <el-date-picker
                v-model="basicParams.sendTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请输入发送时间"
                style="width: 240px"
                clearable
              />
            </el-form-item>
            <el-form-item label="所属系统" prop="system">
              <el-select v-model="basicParams.system" 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="module">
              <el-cascader
                v-model="basicParams.module"
                :options="moduleTreeOptions"
                :props="moduleProps"
                :show-all-levels="false"
                placeholder="请选择渠道"
                clearable
                filterable
                style="width: 100%"
              />
            </el-form-item>
            <el-row>
              <el-form-item label="短信内容" prop="templateContent">
                <el-input
                  v-model="basicParams.templateContent"
                  type="textarea"
                  style="width: 800px"
                  :rows="8"
                  maxlength="1000"
                  show-word-limit
                  placeholder="请输入短信内容"
                  :disabled="contentDisabled"
                  clearable
                />
              </el-form-item>
            </el-row>
            <el-row>
              <el-text style="margin-left: 130px" class="mx-1" type="primary"
                >tips:
                <br />
                1、短信模版定义时使用两个大括号包含包围的元素作为变量参数，参数只能包含英文字母。 样例格式：<el-tag>{{ tipsKey }} </el-tag>
                <br />
                2、如果选择的服务商已包含了短信前、后缀，新定义模版时<el-tag type="danger">请勿</el-tag>添加前后缀信息。
              </el-text>
            </el-row>
          </el-form>
        </el-card>

        <el-card v-if="!reviewFlag && !hideAllButtons" shadow="hover">
          <el-button v-hasPermi="['msg:manualinfo:save']" icon="Check" type="primary" @click="handleSubmit">保存</el-button>
          <el-button v-if="haveContent" v-hasPermi="['msg:manualinfo:download']" icon="Download" type="primary" @click="handleDownload"
            >下载模版</el-button
          >
          <el-button v-if="haveContent" v-hasPermi="['msg:manualinfo:importData']" icon="Upload" type="primary" @click="handleUpload"
            >上传模版</el-button
          >
        </el-card>

        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>附件列表</span>
            </div>
          </template>
          <el-table v-loading="fileLoading" :data="fileList">
            <el-table-column prop="originalName" align="center" label="文件名" width="200" />
            <el-table-column prop="totalNumber" align="center" label="总数量" width="150" />
            <el-table-column prop="effectiveNumber" align="center" label="有效数量" width="180" />
            <el-table-column align="center" label="操作" width="350">
              <template #default="scope">
                <el-button
                  v-hasPermi="['msg:manualinfo:downloadfile']"
                  icon="Download"
                  size="small"
                  type="text"
                  @click="handleDownloadFile(scope.row)"
                  >下载</el-button
                >
                <el-button
                  v-if="!reviewFlag"
                  v-hasPermi="['msg:manualinfo:deleteFile']"
                  icon="Delete"
                  size="small"
                  type="text"
                  @click="handleDeleteFile(scope.row)"
                  >删除</el-button
                >
                <el-button v-hasPermi="['msg:manualinfo:viewfiledetail']" icon="View" size="small" type="text" @click="handleFileDetail(scope.row)"
                  >查看详情</el-button
                >
                <el-button v-hasPermi="['msg:manualinfo:export']" type="text" icon="Download" @click="downloadFailureInfo(scope.row)"
                  >下载导入失败信息</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <el-card shadow="hover">
          <el-button
            v-if="!reviewFlag && !hideAllButtons"
            v-hasPermi="['msg:manualinfo:applayConfirm']"
            icon="Check"
            type="primary"
            @click="handleApplay"
            >申请确认</el-button
          >
          <el-button
            v-if="!reviewFlag && !hideAllButtons"
            v-hasPermi="['msg:manualinfo:applayConfirm']"
            icon="Check"
            type="primary"
            @click="handleDelete"
            >撤销申请</el-button
          >
          <el-form
            v-if="reviewFlag"
            ref="reviewRef"
            :model="reviewParams"
            :rules="reviewRules"
            :inline="true"
            label-width="130px"
            label-position="left"
          >
            <el-form-item label="审核结论">
              <el-select v-model="reviewParams.reviewConclusion" placeholder="审核结论">
                <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-row>
              <el-form-item v-if="reviewParams.reviewConclusion === 'N'" label="不通过原因">
                <el-input v-model="reviewParams.reviewReason" type="textarea" rows="4" style="width: 300px" placeholder="不通过原因" />
              </el-form-item>
            </el-row>
          </el-form>
          <el-button
            v-if="reviewFlag && !hideAllButtons"
            v-hasPermi="['msg:manualinfo:reviewConfirm']"
            icon="Check"
            type="primary"
            @click="handleReview"
            >审核确认</el-button
          >
        </el-card>

        <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
          <el-upload
            ref="uploadRef"
            :limit="1"
            accept=".xlsx"
            :headers="upload.headers"
            :action="upload.url + '?manualId=' + manualId"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
          >
            <el-icon class="el-icon--upload">
              <i-ep-upload-filled />
            </el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
              <div class="text-center el-upload__tip">
                <span>仅允许导入xlsx格式文件。</span>
              </div>
            </template>
          </el-upload>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitFileForm">确 定</el-button>
              <el-button @click="upload.open = false">取 消</el-button>
            </div>
          </template>
        </el-dialog>

        <el-dialog v-model="fileDetail.visible" :title="fileDetail.title" width="80%" append-to-body>
          <el-table v-loading="fileDetailLoading" :data="fileDetailList">
            <el-table-column label="电话号码" align="center" prop="phone" />
            <el-table-column label="参数信息" align="center" prop="parms" show-overflow-tooltip />
            <el-table-column label="申请状态" align="center" prop="applyStatus">
              <template #default="scope">
                <dict-tag :options="manual_export_status" :value="scope.row.applyStatus" />
              </template>
            </el-table-column>
            <el-table-column label="申请失败原因" align="center" prop="applyFailReson" />
          </el-table>
          <pagination
            v-show="total > 0"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            :total="total"
            @pagination="getFileDetailList"
          />
        </el-dialog>
      </div>
    </transition>
  </div>
</template>
<script setup name="ManualDetail" lang="ts">
import {
  addManualInfo,
  getfileListByManualId,
  getManualInfo,
  getServiceConfig,
  getSmsTempList,
  updateManualInfo,
  deleteFile,
  getFileDetail,
  applayConfirm,
  reviewConfirm,
  revokeSmsManualApply
} from '@/api/msg/smsmanual/manual';
import { constructModuleEnumTree, selectMSMTempByTempCodeByCodeAndVersion } from '@/api/msg/mestemp';
import {globalHeaders, globalUploadHeaders} from '@/utils/request';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
//模版类型
const { manual_template_type } = toRefs<any>(proxy?.useDict('manual_template_type'));
//发送类型
const { manual_send_type } = toRefs<any>(proxy?.useDict('manual_send_type'));
//所属系统
const { sys_from_system } = toRefs<any>(proxy?.useDict('sys_from_system'));
//归属模块
const { print_module } = toRefs<any>(proxy?.useDict('print_module'));
//是否
const { sys_yes_no, manual_export_status, sys_managecom } = toRefs<any>(proxy?.useDict('sys_yes_no', 'manual_export_status', 'sys_managecom'));

const showSearch = ref(true);
const manualId = ref('');
const formRef = ref<ElFormInstance>();
const reviewRef = ref<ElFormInstance>();
const loading = ref(false);
const fileType = ref(['xlsx']);
const serviceList = ref([]);
const tempCodeList = ref([]);
const contentDisabled = ref(false);
const haveContent = ref(false);
const tipsKey = ref('{{Keys}}');
const uploadRef = ref<ElUploadInstance>();
const reviewFlag = ref(false);
const moduleTreeOptions = ref<any[]>([]);
const hideAllButtons = ref();
const moduleProps = {
  value: 'value',
  label: 'label',
  children: 'children',
  checkStrictly: true,
  emitPath: false
};
const likeName = ref('');
const filteredManagecom = ref([]);
const data = reactive({
  basicParams: {},
  rules: {
    title: [{ required: true, message: '主题不能为空', trigger: 'blur' }],
    templateType: [{ required: true, message: '模版类型不能为空', trigger: 'blur' }],
    templateCode: [{ required: true, message: '模版编码不能为空', trigger: 'blur' }],
    system: [{ required: true, message: '所属系统不能为空', trigger: 'blur' }],
    module: [{ required: true, message: '渠道不能为空', trigger: 'blur' }],
    institution: [{ required: true, message: '归属机构不能为空', trigger: 'blur' }],
    serviceId: [{ required: true, message: '服务商不能为空', trigger: 'blur' }],
    description: [{ required: true, message: '说明不能为空', trigger: 'blur' }],
    sendType: [{ required: true, message: '发送类型不能为空', trigger: 'blur' }],
    templateContent: [
      { required: true, message: '短信内容不能为空', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value && value.includes('\t')) {
            callback(new Error('短信内容前面不能有空格'));
          } else {
            callback();
          }
        },
        trigger: ['blur', 'change']
      }
    ]
  }
});
const { basicParams, rules } = toRefs(data);

const reviewData = reactive({
  reviewParams: {
    reviewConclusion: '',
    reviewReason: ''
  },
  reviewRules: {
    reviewConclusion: [{ required: true, message: '审核结论不能为空', trigger: 'blur' }],
    reviewReason: [
      {
        validator: (rule, value, callback) => {
          if (reviewData.reviewParams.reviewConclusion === 'N' && !value) {
            callback(new Error('不通过原因不能为空'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ]
  }
});
const { reviewParams, reviewRules } = toRefs(reviewData);

const fileLoading = ref(false);
const fileList = ref([]);

const fileData = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    manualId: undefined,
    attId: undefined
  }
});
const { queryParams } = toRefs(fileData);
const total = ref(0);
const fileDetailLoading = ref(false);
const fileDetail = reactive<DialogOption>({
  visible: false,
  title: ''
});
const fileDetailList = ref([]);

//获取服务商
const getServiceInfo = async () => {
  const res = await getServiceConfig();
  serviceList.value = res.data;
  filteredManagecom.value = sys_managecom.value;
};

const getfileList = async () => {
  const res = await getfileListByManualId(manualId.value);
  fileList.value = res.data;
};

/**
 * 模版类型改变
 * @param value
 */
const templateTypeChange = async (value) => {
  if (value === '1') {
    const res = await getSmsTempList('auditPassManual');
    tempCodeList.value = res.data.tempList;
  }
};
/**
 * 模版编码改变
 * @param newVal
 */
const templateCodeChange = async () => {
  const res = await selectMSMTempByTempCodeByCodeAndVersion(basicParams.value.templateCode);
  if (!res.data) {
    proxy?.$modal.msgError('未找到该模板最新启用版本');
  }
  basicParams.value.templateContent = res.data.templateContent;
  contentDisabled.value = false;
};

const handleSubmit = async () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      try {
        if (basicParams.value.manualId) {
          await updateManualInfo(basicParams.value);
          proxy?.$modal.msgSuccess('操作成功');
          loading.value = false;
        } else {
          const res = await addManualInfo(basicParams.value);
          Object.assign(basicParams.value, res.data);
          proxy?.$modal.msgSuccess('操作成功');
          loading.value = false;
          const newPath = `/msg/smsmanual/manualDetail/`;
          const routeObj = {
            path: newPath,
            query: {
              manualId: res.data.manualId
            }
          };
          proxy?.$tab.closePage();
          proxy?.$tab.refreshPage(routeObj);
        }
      } catch (e) {
        loading.value = false;
      }
    }
  });
};

const loadingPage = async (_manualId) => {
  const res = await getManualInfo(_manualId);
  Object.assign(basicParams.value, res.data.manualInfo);
  if (res.data.manualInfo.status === '-1') {
    reviewParams.value.reviewConclusion = 'N';
  } else {
    reviewParams.value.reviewConclusion = 'Y';
  }
  reviewParams.value.reviewReason = res.data.manualInfo.failReason;
  await getfileList();
};

const handleDownload = () => {
  proxy?.download('msg/manualInfo/download', { manualId: basicParams.value.manualId }, `template_${new Date().getTime()}.xlsx`);
};

/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalUploadHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/msg/manualInfo/importData'
});

/** 导入按钮操作 */
const handleUpload = () => {
  upload.title = '导入';
  upload.open = true;
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}

/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
  getfileList();
};

/**
 * 上传的文件下载
 */
const handleDownloadFile = (row) => {
  proxy?.$download.oss(row.ossId);
};

/**
 * 上传的文件删除
 */
const handleDeleteFile = (row) => {
  fileLoading.value = true;
  deleteFile(row).then(() => {
    getfileList();
    fileLoading.value = false;
  });
};

/**
 * 打开文件详情界面
 * @param row
 */
const handleFileDetail = async (row) => {
  fileDetail.visible = true;
  fileDetail.title = '查看附件详情';
  fileDetailLoading.value = true;
  queryParams.value.manualId = row.manualId;
  queryParams.value.attId = row.attId;
  await getFileDetailList();
  fileDetailLoading.value = false;
};

/**
 * 获取文件处理详情列表
 * @param row
 */
const getFileDetailList = async () => {
  const res = await getFileDetail(queryParams.value);
  fileDetailList.value = res.rows;
  total.value = res.total;
};
/**
 * 申请确认提交
 */
const handleApplay = async () => {
  if (!fileList.value || fileList.value.length === 0) {
    proxy?.$modal.msgError('附件不能为空');
    return; // 添加return防止继续执行
  }

  // 计算所有文件的有效数量总和
  const totalEffectiveNumber = fileList.value.reduce((sum, file) => {
    return sum + (file.effectiveNumber || 0);
  }, 0);

  // 校验有效数量总和必须大于0
  if (totalEffectiveNumber <= 0) {
    proxy?.$modal.msgError('所有附件的有效数量总和必须大于0才能申请');
    return;
  }
  const res = await applayConfirm(manualId.value);
  if (res.code === 200) {
    proxy?.$modal.msgSuccess('操作成功');
    proxy?.$tab.closePage();
  }
};

/**
 * 撤销申请
 */
const handleDelete = async () => {
  const res = await revokeSmsManualApply(manualId.value);
  if (res.data) {
    proxy?.$modal.msgSuccess('操作成功');
    proxy?.$tab.closePage();
  }
};

/**
 * 审核结论保存
 */
const handleReview = () => {
  reviewRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      const res = await reviewConfirm(manualId.value, reviewParams.value.reviewConclusion, reviewParams.value.reviewReason);
      if (res.code === 200) {
        proxy?.$modal.msgSuccess('操作成功');
        proxy?.$tab.closePage();
      }
    }
  });
};

/**
 * 审核结论校验
 * @param rule
 * @param value
 * @param callback
 */
function checkNonNegative(rule, value, callback) {
  if (reviewParams.value.reviewConclusion === 'N' && value === '') {
    callback(new Error('审核结论为不通过，不通过原因不能为空'));
  } else {
    callback();
  }
}

const handleSelectClick = () => {
  filterByManageCom(); // 触发过滤逻辑
};

const filterByManageCom = () => {
  if (likeName.value) {
    filteredManagecom.value = sys_managecom.value.filter((item) => {
      return item.label.includes(likeName.value) || item.value.includes(likeName.value);
    });
  } else {
    filteredManagecom.value = sys_managecom.value;
  }
};

const getModuleTree = async () => {
  try {
    const res = await constructModuleEnumTree();

    // 如果返回的是字符串，先解析为JSON对象
    const data = typeof res.msg === 'string' ? JSON.parse(res.msg) : res.msg;

    // 处理数据 - 你提供的示例数据已经是正确的树形结构
    moduleTreeOptions.value = Array.isArray(data) ? data : [data];

  } catch (error) {
    moduleTreeOptions.value = [];
  }
};

//下载导入失败详细信息
const downloadFailureInfo = (row) => {
  queryParams.value.manualId = row.manualId;
  queryParams.value.attId = row.attId;
  proxy?.download(
    'msg/manualInfo/exportFailureInfo',
    {
      ...queryParams.value
    },
    `导入失败信息_${new Date().toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      fractionalSecondDigits: 3,
      hour12: false
    })}.xlsx`
  );
};

onMounted(() => {
  const route = useRoute();
  const _manualId = route.query.manualId as string | undefined;
  const _reviewFlag = route.query.reviewFlag as boolean | undefined;
  if (_reviewFlag) {
    reviewFlag.value = true;
  } else {
    reviewFlag.value = false;
  }
  hideAllButtons.value = route.query.hideAllButtons === 'true';
  if (_manualId) {
    manualId.value = _manualId;
    haveContent.value = true;
    loadingPage(manualId.value);
  }
  getServiceInfo();
  getModuleTree();
});
</script>
