<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="消息名称" prop="smsName">
            <el-input v-model="queryParams.smsName" placeholder="请输入消息名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="消息状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择消息状态" clearable style="width: 240px">
                <el-option v-for="dict in business_enable_status" :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>
      </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="['business:smsConfig:add']">新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['business:smsConfig:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['business:smsConfig:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['business:smsConfig:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
        </el-row>
      </template>

      <!-- <el-table v-loading="loading" :data="smsConfigList" @selection-change="handleSelectionChange"> -->
      <el-table v-loading="loading" :data="smsConfigList" :cellStyle="cellStyle">
        <el-table-column label="消息名称" align="center" prop="smsName" />
        <el-table-column label="发送对象" align="center" prop="smsRecipient" />
        <el-table-column label="消息文案" align="center" prop="smsContent" />
        <el-table-column label="状态" align="center" prop="status" :formatter="controlStatusFormat"/>
        <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)" v-hasPermi="['business:smsConfig:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:smsConfig:remove']"></el-button>
            </el-tooltip> -->
            <el-button type="primary" @click="controlStatusBtn($event, scope.row, '0')" :disabled="scope.row.status == 0">启用</el-button>
            <el-button type="danger" @click="controlStatusBtn($event, scope.row, '1')" :disabled="scope.row.status == 1">禁用</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="700px" append-to-body>
      <el-form ref="smsConfigFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="消息名称" prop="smsName">
          <el-input v-model="form.smsName" placeholder="请输入消息名称" />
        </el-form-item>
        <el-form-item label="消息编码" prop="smsCode">
          <el-input v-model="form.smsCode" placeholder="请输入消息编码" />
        </el-form-item>
        <el-form-item label="消息文案" prop="smsContent">
          <!-- <editor v-model="form.smsContent" :min-height="192"/> -->
          <el-input type="textarea" v-model="form.smsContent" placeholder="请输入消息文案" />
        </el-form-item>
        <el-form-item label="发送对象" prop="smsRecipient">
          <el-input v-model="form.smsRecipient" placeholder="请输入发送对象" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in business_enable_status" :key="dict.value" :label="dict.value">{{
              dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SmsConfig" lang="ts">
import { listSmsConfig, getSmsConfig, delSmsConfig, addSmsConfig, updateSmsConfig, controlStatus, initSmsConfig } from '@/api/business/smsConfig';
import { SmsConfigVO, SmsConfigQuery, SmsConfigForm, ControlStatusVO } from '@/api/business/smsConfig/types';
import { TableColumnCtx } from 'element-plus';

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

const smsConfigList = ref<SmsConfigVO[]>([]);
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 queryFormRef = ref<ElFormInstance>();
const smsConfigFormRef = ref<ElFormInstance>();

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

const initFormData: SmsConfigForm = {
  id: undefined,
  smsName: undefined,
  smsCode: undefined,
  smsContent: undefined,
  smsRecipient: undefined,
  status: undefined,
}
const data = reactive<PageData<SmsConfigForm, SmsConfigQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    smsName: undefined,
    status: undefined,
  },
  rules: {
    id: [
      { required: true, message: "主键不能为空", trigger: "blur" }
    ],
    smsName: [
      { required: true, message: "消息名称不能为空", trigger: "blur" }
    ],
    smsCode: [
      { required: true, message: "消息编码不能为空", trigger: "blur" }
    ],
    smsContent: [
      { required: true, message: "消息文案不能为空", trigger: "blur" }
    ],
    smsRecipient: [
      { required: true, message: "发送对象不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态 0启用,1禁用不能为空", trigger: "change" }
    ],
  }
});

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

//列表控制状态
const controlStatusFormat = (row: SmsConfigVO, column: TableColumnCtx<SmsConfigVO>) => {
  if (row.status == '0') {
    return '启用'
  } else if (row.status == '1') {
    return '禁用'
  } else {
    return '未知'
  }
}

//批量导入-用户状态 文字颜色
const cellStyle = ({ row, column }) => {
  let controlStatusStyle
  switch (row.status) {
    case '0':
      controlStatusStyle = { 'color': '#67c23a' }
      break;
    case '1':
      controlStatusStyle = { 'color': '#f00' }
      break;
    default:
      controlStatusStyle = { 'color': '#000' }
      break;
  }
  if (column.label == '状态') {
    return controlStatusStyle
  }
}

/** 查询课件短信配置列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSmsConfig(queryParams.value);
  smsConfigList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

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

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: SmsConfigVO[]) => {
  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 controlStatusBtn = async (event:any, row: SmsConfigVO, status: string) => {
  let target = event.target;
  if(target.nodeName == "SPAN"){
   target = event.target.parentNode;
  }
  target.blur();

  if(status == '1'){
    await proxy?.$modal.confirm('是否禁用该消息模版，禁用后发送对象将无法收到对应提示').finally(() => loading.value = false);
  }
  await controlStatus({id:row?.id,status})
  await getList();
}

/** 修改按钮操作 */
const handleUpdate = async (row?: SmsConfigVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getSmsConfig(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改课件短信配置";
}

/** 提交按钮 */
const submitForm = () => {
  smsConfigFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateSmsConfig(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addSmsConfig(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

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

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

const initData = async () =>{
  await initSmsConfig()
  await getList()
}

onMounted(() => {
  initData()
});
</script>
