<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-form-item label="签名" prop="signName">
              <el-input v-model="queryParams.signName" placeholder="请输入" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="门店" prop="storeId">
              <el-select v-model="queryParams.storeId" placeholder="请选择" filterable clearable>
                <el-option v-for="item in shopList" :key="item.id" :label="item.storeName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="审核" prop="checkStatus">
              <el-select v-model="queryParams.checkStatus" placeholder="请选择" clearable>
                <el-option v-for="dict in check_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择" clearable>
                <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <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">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:msgSignSetting:add']">添加签名</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="msgSignSettingList" @selection-change="handleSelectionChange">
        <el-table-column label="序号" type="index" width="80px" align="center" />
        <el-table-column label="签名名称" align="center" prop="signName" />
        <el-table-column label="主门店名称" align="center" prop="storeNameStr" />
        <el-table-column label="资质类目" align="center" prop="qualificationCategory">
          <template #default="scope">
            <dict-tag :options="qualification_category" :value="scope.row.qualificationCategory" />
          </template>
        </el-table-column>
        <el-table-column label="资质图片" align="center" prop="qualificationPicUrl" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.qualificationPicUrl" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="审核状态" align="center" prop="checkStatus">
          <template #default="scope">
            <dict-tag :options="check_status" :value="scope.row.checkStatus" />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleStatusChange(scope.row)" v-hasPermi="['system:msgSignSetting:edit']">
              {{ scope.row.status === '0' ? '停用' : '启用' }}
            </el-button>
            <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['system:msgSignSetting:edit']">编辑</el-button>
            <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['system:msgSignSetting:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改短信签名管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="650px" append-to-body>
      <el-form ref="msgSignSettingFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="签名名称：" prop="signName">
          <el-input v-model="form.signName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="选择门店：" prop="storeId">
          <el-select v-model="form.storeId" placeholder="请选择" filterable clearable>
            <el-option v-for="item in shopList" :key="item.id" :label="item.storeName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择资质：" prop="qualificationCategory">
          <el-select v-model="form.qualificationCategory" placeholder="请选择">
            <el-option v-for="dict in qualification_category" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传资质图片：" prop="qualificationPic">
          <image-upload v-model="form.qualificationPic" />
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MsgSignSetting" lang="ts">
import {
  listMsgSignSetting,
  getMsgSignSetting,
  delMsgSignSetting,
  addMsgSignSetting,
  updateMsgSignSetting,
  changeStatus
} from '@/api/setting/msgSignSetting/index';
import { MsgSignSettingVO, MsgSignSettingQuery, MsgSignSettingForm } from '@/api/setting/msgSignSetting/types';
import { listSysShop } from '@/api/store/sysShop/index';
import { SysShopVO } from '@/api/store/sysShop/types';

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

const msgSignSettingList = ref<MsgSignSettingVO[]>([]);
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 shopList = ref<SysShopVO[]>([]);
const queryFormRef = ref<ElFormInstance>();
const msgSignSettingFormRef = ref<ElFormInstance>();

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

const initFormData: MsgSignSettingForm = {
  id: undefined,
  signName: undefined,
  remark: undefined,
  storeId: undefined,
  storeName: undefined,
  qualificationCategory: undefined,
  qualificationPic: undefined,
  status: undefined,
  checkStatus: undefined
};
const data = reactive<PageData<MsgSignSettingForm, MsgSignSettingQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    signName: undefined,
    storeId: undefined,
    storeName: undefined,
    qualificationCategory: undefined,
    qualificationPic: undefined,
    status: undefined,
    checkStatus: undefined,
    params: {}
  },
  rules: {
    signName: [{ required: true, message: '签名名称不能为空', trigger: 'blur' }],
    storeId: [{ required: true, message: '主门不能为空', trigger: 'blur' }],
    qualificationCategory: [{ required: true, message: '资质类目不能为空', trigger: 'change' }],
    qualificationPic: [{ required: true, message: '资质图片不能为空', trigger: 'blur' }]
  }
});

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

/** 查询短信签名管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMsgSignSetting(queryParams.value);
  msgSignSettingList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

const getSysShopList = async () => {
  const res = await listSysShop();
  if (res.code == 200) {
    shopList.value = res.rows;
  }
};

/** 切换状态 */
const handleStatusChange = async (row: MsgSignSettingVO) => {
  const newStatus = row.status === '0' ? '1' : '0';
  const text = row.status === '0' ? '停用' : '启用';
  try {
    await proxy?.$modal.confirm(`确认要"${text}" "${row.signName}"短信签名吗?`);

    // 执行状态变更
    await changeStatus(row.id, newStatus);

    row.status = newStatus;
    proxy?.$modal.msgSuccess(`${text}成功`);
    getList();
  } catch (err) {
    // 用户点击取消会抛出 'cancel' 错误，其他错误为实际异常
    if (err !== 'cancel') {
      proxy?.$modal.msgError('操作失败');
    }
  }
};

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

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

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

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

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

/** 修改按钮操作 */
const handleUpdate = async (row?: MsgSignSettingVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getMsgSignSetting(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '编辑短信签名';
};

/** 提交按钮 */
const submitForm = () => {
  msgSignSettingFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateMsgSignSetting(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addMsgSignSetting(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: MsgSignSettingVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除短信签名管理编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delMsgSignSetting(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

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

onMounted(() => {
  getList();
  getSysShopList();
});
</script>
