<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">
            <el-row>
              <el-form-item label="归属系统" prop="system">
                <el-select v-model="queryParams.system" placeholder="请选择所属系统" clearable>
                  <el-option v-for="dict in msg_system" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <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"></el-input>
                  </template>
                  <el-option
                    v-for="dict in filteredList"
                    :key="dict.templateCode"
                    :label="dict.templateName + '-v' + dict.version"
                    :value="dict.templateCode + '&' + dict.version"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item v-if="false" label="所属模块" prop="module">
                <el-cascader
                  v-model="queryParams.modulePath"
                  :options="moduleTreeOptions"
                  :props="moduleProps"
                  :show-all-levels="false"
                  placeholder="请选择所属模块"
                  clearable
                  filterable
                  style="width: 100%"
                />
              </el-form-item>
              <el-form-item label="审批状态" prop="auditResult">
                <el-select v-model="queryParams.auditResult" placeholder="请选择审批状态" clearable>
                  <el-option label="未审批" :value="0" />
                  <el-option label="审批通过" :value="1" />
                </el-select>
              </el-form-item>
              <el-form-item label="开始日期" prop="applyDate">
                <el-date-picker v-model="queryParams.beginDate" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择申请日期" />
              </el-form-item>
              <el-form-item label="结束日期" prop="applyDate">
                <el-date-picker v-model="queryParams.endDate" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择申请日期" />
              </el-form-item>
            </el-row>
            <el-form-item style="width: 100%">
              <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">
      <el-table v-loading="loading" :data="reviewList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="模板唯一标识" align="center" prop="templateId" />
        <el-table-column label="模板ID" align="center" prop="templateCode" />
        <el-table-column v-if="false" label="模板类型 0短信 1邮件 2微信" align="center" prop="templateType" />
        <el-table-column label="模板名称" align="center" prop="templateName" />
        <el-table-column label="所属系统" align="center" prop="system">
          <template #default="scope">
            <dict-tag :options="msg_system" :value="scope.row.system" />
          </template>
        </el-table-column>
        <el-table-column label="所属模块" align="center" prop="module">
          <template #default="scope">
            <span>{{ moduleValueToLabel[scope.row.module] || scope.row.module }}</span>
          </template>
        </el-table-column>
        <el-table-column label="短信内容" align="center" prop="templateContent" />
        <el-table-column label="版本号" align="center" prop="versionNumber" />
        <el-table-column label="审批状态" align="center" prop="auditResult">
          <template #default="scope">
            <el-tag v-if="scope.row.auditResult === '0'" type="warning">未审批</el-tag>
            <el-tag v-else-if="scope.row.auditResult === '1'" type="success">审批通过</el-tag>
            <span v-else>未知状态</span>
          </template>
        </el-table-column>
        <el-table-column v-if="false" label="版本申请状态" align="center" prop="versionApplyStatus" />
        <el-table-column v-if="false" label="版本启用状态" align="center" prop="versionEnableStatus" />
        <el-table-column v-if="false" label="说明" align="center" prop="description" />
        <el-table-column v-if="false" label="申请日期" align="center" prop="applyDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.applyDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看详情" placement="top">
              <el-button  link type="primary" icon="Edit" @click="handleUpdate(scope.row)">查看 </el-button>
            </el-tooltip>
          </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>
    <!-- 添加或修改短信模板配置对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="95%" append-to-body>
      <el-form ref="mestempFormRef" :model="form" :rules="rules" :inline="true">
        <el-row>
          <el-form-item label="模板编码" prop="templateCode" label-width="100px">
            <el-input v-model="form.templateCode" placeholder="请输入模板编码" readonly />
          </el-form-item>
          <el-form-item label="短信名称" prop="templateName" label-width="100px">
            <el-input v-model="form.templateName" placeholder="请输入模板名称" readonly />
          </el-form-item>
          <el-form-item label="归属系统" prop="system" label-width="100px">
            <el-select v-model="form.system" placeholder="请选择所属系统" disabled>
              <el-option v-for="dict in msg_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="module" label-width="100px">
            <el-cascader
              v-model="form.modulePath"
              :options="moduleTreeOptions"
              :props="moduleProps"
              :show-all-levels="false"
              placeholder="请选择所属模块"
              disabled
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="版本" prop="versionNumber" label-width="100px">
            <el-input v-model="form.versionNumber" placeholder="请输入版本号" readonly />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="短信内容" prop="templateContent" label-width="100px">
            <el-input v-model="form.templateContent" type="textarea" placeholder="请输入内容" style="width: 800px" readonly />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="增加/调整原因" prop="description" label-width="100px">
            <el-input v-model="form.description" type="textarea" placeholder="请输入内容" style="width: 800px" readonly />
          </el-form-item>
          <el-form-item v-if="false" label="申请日期" prop="applyDate">
            <el-date-picker v-model="form.applyDate" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择申请日期">
            </el-date-picker>
          </el-form-item>
        </el-row>
        <!-- 风控规则模板-->
        <msg-risk-control ref="msgRiskControlRef" :disabled="true"></msg-risk-control>
        <!--        <el-table v-loading="loading" :data="temp" @selection-change="handleSelectionChange">-->
        <!--          <el-table-column type="selection" width="55" align="center" />-->
        <!--          <el-table-column label="风控规则编码" align="center" prop="templateCode" />-->
        <!--          <el-table-column label="风控规则描述" align="center" prop="templateName" />-->
        <!--          <el-table-column label="风控规则参数" align="center" prop="templateName" />-->
        <!--          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
        <!--            <template #default="scope">-->
        <!--              <el-tooltip content="编辑" placement="top">-->
        <!--                <el-button v-hasPermi="['msg:mestemp:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>-->
        <!--              </el-tooltip>-->
        <!--              <el-tooltip content="删除" placement="top">-->
        <!--                <el-button v-hasPermi="['msg:mestemp:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>-->
        <!--              </el-tooltip>-->
        <!--            </template>-->
        <!--          </el-table-column>-->
        <!--        </el-table>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-hasPermi="['msg:review:approved']" :loading="buttonLoading" type="primary" @click="Approved()"> 审核通过 </el-button>
          <el-button v-hasPermi="['msg:review:rejected']" :loading="buttonLoading" type="primary" @click="Rejected()"> 审核回退 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增的回退原因输入对话框 -->
    <el-dialog v-model="rejectDialog.visible" title="请输入回退原因" width="500px" append-to-body>
      <el-input v-model="rejectReason" type="textarea" :rows="5" placeholder="请输入回退原因" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="rejectDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleRejectConfirm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Review" lang="ts">
import { listReview, getReview, delReview, addReview, updateReview, approvedMsgtemp, rejectedMsgtemp } from '@/api/msg/review';
import { ReviewVO, ReviewQuery, ReviewForm } from '@/api/msg/review/types';
import {
  constructModuleEnumTree,
  editStatusMsgtemp,
  queryMSMTemplateList,
  selectMSMTempByTempCode
} from '@/api/msg/mestemp';
import { MestempVO } from '@/api/msg/mestemp/types';
import MsgRiskControl from '@/views/msg/riskControl/msgRiskControl.vue';
import { number } from 'vue-types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { msg_system, print_module } = toRefs<any>(proxy?.useDict('msg_system', 'print_module'));

const reviewList = ref<ReviewVO[]>([]);
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 likeName = ref('');
const templateList = ref<any[]>([]);
const filteredList = ref<any[]>([]);
const moduleTreeOptions = ref<any[]>([]);
const msgRiskControlRef = ref();
const codeSign = ref();
const moduleProps = {
  value: 'value',
  label: 'label',
  children: 'children',
  checkStrictly: true // 可以选择任意一级
};
const rejectDialog = reactive({
  visible: false
});
const rejectReason = ref('');

const queryFormRef = ref<ElFormInstance>();
const reviewFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ReviewForm = {
  templateId: undefined,
  templateCode: undefined,
  templateType: undefined,
  templateName: undefined,
  system: undefined,
  module: undefined,
  versionNumber: undefined,
  templateContent: undefined,
  versionApplyStatus: undefined,
  versionEnableStatus: undefined,
  description: undefined,
  auditResult: undefined,
  rollbackReason: undefined,
  applyDate: undefined,
  modulePath: [],
};
const data = reactive<PageData<ReviewForm, ReviewQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    templateCode: undefined,
    system: undefined,
    module: undefined,
    applyDate: undefined,
    endDate: undefined,
    beginDate: undefined,
    modulePath: [],
    params: {},
    versionApplyStatus: undefined,
    auditResult: ''
  },
  rules: {
    //templateId: [{ required: true, message: '模板唯一标识不能为空', trigger: 'blur' }],
    //templateCode: [{ required: true, message: '模板编码不能为空', trigger: 'blur' }],
    //templateType: [{ required: true, message: '模板类型 0短信 1邮件 2微信不能为空', trigger: 'change' }],
    templateName: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }],
    versionNumber: [{ required: true, message: '版本号不能为空', trigger: 'blur' }],
    templateContent: [{ required: true, message: '模板内容不能为空', trigger: 'blur' }],
    //versionApplyStatus: [{ required: true, message: '版本申请状态不能为空', trigger: 'change' }],
    //versionEnableStatus: [{ required: true, message: '版本启用状态不能为空', trigger: 'change' }],
    description: [{ required: true, message: '说明不能为空', trigger: 'blur' }]
    //applyDate: [{ required: true, message: '申请日期不能为空', trigger: 'blur' }]
  }
});

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

/** 查询短信模板配置列表 */
const getList = async () => {
  loading.value = true;
  const res = await listReview(queryParams.value);
  reviewList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  reviewFormRef.value?.resetFields();
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  // 重置查询参数到初始状态
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    templateCode: undefined,
    system: undefined,
    module: undefined,
    applyDate: undefined,
    versionApplyStatus: 0,
    endDate: undefined,
    beginDate: undefined,
    params: {},
    auditResult: undefined,
    modulePath:[]
  };
  // 重置模板名称过滤相关状态
  likeName.value = '';
  filteredList.value = templateList.value;
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ReviewVO[]) => {
  ids.value = selection.map((item) => item.templateId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加短信模板配置';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ReviewVO) => {
  reset();
  const _templateId = row?.templateId || ids.value[0];
  const res = await getReview(_templateId);
  Object.assign(form.value, res.data);
  form.value.modulePath = findModulePath(form.value.module);

  // 先打开弹窗
  dialog.visible = true;
  dialog.title = '修改短信模板配置';

  // 确保弹窗完全渲染后再加载风控规则
  nextTick(() => {
    if (msgRiskControlRef.value) {
      msgRiskControlRef.value.loadingPage(_templateId);
    }
  });
};

/**审核通过
 *
 * 点击审核通过
 * 修改申请，审核表审核状态，
 * 存储申请，审核轨迹表
 *
 */
const Approved = async () => {
  const templateId = form.value.templateId;
  await approvedMsgtemp(templateId);
  proxy?.$modal.msgSuccess('审核通过');
  proxy?.$modal.alert('模板配置完成请与运营人员联系配置发送通道并启用');
  dialog.visible = false;
  await getList();
};
/**
 * 审核回退
 * 点击审核回退，
 * 判断是否填写 回退原因，为空阻断
 * 删除申请，审核表此模板信息，
 * 存储申请表，审核轨迹表，
 * 更新模板定义表中 审核状态以及回退原因
 *
 */
const Rejected = async () => {
  showRejectDialog();
};

// 显示回退原因输入对话框
const showRejectDialog = () => {
  rejectReason.value = ''; // 清空之前的输入
  rejectDialog.visible = true;
};

// 处理回退确认
const handleRejectConfirm = async () => {
  if (!rejectReason.value) {
    proxy?.$modal.msgWarning('请录入回退原因！');
    return;
  }

  try {
    buttonLoading.value = true;
    form.value.rollbackReason = rejectReason.value; // 设置回退原因
    await rejectedMsgtemp(form.value);
    proxy?.$modal.msgSuccess('操作成功');
    rejectDialog.visible = false;
    dialog.visible = false;
    await getList();
  } finally {
    buttonLoading.value = false;
  }
};
/** 删除按钮操作 */
const handleDelete = async (row?: ReviewVO) => {
  const _templateIds = row?.templateId || ids.value;
  await proxy?.$modal.confirm('是否确认删除短信模板配置编号为"' + _templateIds + '"的数据项？').finally(() => (loading.value = false));
  await delReview(_templateIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'msg/review/export',
    {
      ...queryParams.value
    },
    `review_${new Date().getTime()}.xlsx`
  );
};

const selectTemp = async (newVal) => {
  const val = newVal.split('&');
  queryParams.value.templateCode = val[0];
  // form.value.templateCode = val[0];
  // form.value.versionNumber = val[1];
  // const res = await selectMSMTempByTempCode(form.value);
  // Object.assign(form.value, res.data);
};
//模糊查询
const filterByTemplateName = () => {
  if (likeName.value) {
    // 过滤操作
    filteredList.value = templateList.value.filter((item) => {
      return item.templateName.includes(likeName.value);
    });
  } else {
    // 如果 likeName 为空，显示原始列表
    filteredList.value = templateList.value;
  }
};

const quryTemplateList = async (codeSign) => {
  const res = await queryMSMTemplateList(codeSign);
  templateList.value = res.data.tempList;
  filteredList.value = templateList.value;
};

// 新增方法：根据模块值查找完整路径
const findModulePath = (moduleValue) => {
  // 这里需要实现根据moduleValue在moduleTreeOptions中查找完整路径的逻辑
  // 这是一个示例实现，需要根据你的实际数据结构调整
  const findPath = (nodes, target, path = []) => {
    for (const node of nodes) {
      if (node.value === target) {
        return [...path, node.value];
      }
      if (node.children) {
        const found = findPath(node.children, target, [...path, node.value]);
        if (found) return found;
      }
    }
    return null;
  };

  return findPath(moduleTreeOptions.value, moduleValue) || [];
};

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 moduleValueToLabel = computed(() => {
  const map: Record<string, string> = {};
  const buildMap = (nodes: any[]) => {
    nodes.forEach((node) => {
      map[node.value] = node.label;
      if (node.children) buildMap(node.children);
    });
  };
  buildMap(moduleTreeOptions.value);
  return map;
});

onMounted(() => {
  codeSign.value = 'audit';
  getList();
  quryTemplateList(codeSign.value);
  getModuleTree();
});
</script>

<style scoped>
.dialog-footer {
  text-align: left; /* 将按钮左对齐 */
}
</style>
