<template>
  <div class="search bg-white p-3">
    <el-form :model="searchForm" label-width="100px">
      <el-row>
        <el-col :span="5">
          <el-form-item label="状态">
            <el-select v-model="searchForm.enable_status" clearable placeholder="请选择模板状态">
              <el-option label="启用" :value="true" />
              <el-option label="禁用" :value="false" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="模板名称">
            <el-input v-model="searchForm.name" clearable placeholder="请输入模板名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="模板code">
            <el-input v-model="searchForm.code" clearable placeholder="请输入模板code"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="flex justify-end">
      <el-button class="mr-3" @click="searchEvent"> 搜索 </el-button>
    </div>
  </div>
  <en-table-layout :tableData="tableData.records" :loading="loading">
    <template #toolbar>
      <div class="inner-toolbar w-11/12 flex justify-between">
        <div class="toolbar-btns">
          <el-button size="small" type="primary" :icon="CirclePlus" v-if="checkPermission([''])" @click="handleAddRole">添加</el-button>
        </div>
        <!-- <div class="toolbar-search">
            <en-table-search @search="searchEvent" placeholder="请输入关键字" />
          </div> -->
      </div>
    </template>

    <template #table-columns>
      <el-table-column prop="name" label="模版名称" />
      <!-- <el-table-column prop="template_type" label="短信类型" /> -->
      <el-table-column prop="remark" label="模版说明" />
      <el-table-column prop="audit_status" label="审核状态" />
      <el-table-column prop="enable_status" label="状态">
        <template #default="scope">
          <el-switch v-model="scope.row.enable_status" inline-prompt active-text="启用" inactive-text="禁用" @change="switchEnableStatus($event, scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleView(scope.row)" v-if="checkPermission([''])">查看</el-button>
          <el-button size="small" type="primary" @click="handleEditRole(scope.row)" v-if="checkPermission([''])">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDeleteRole(scope.row)" v-if="checkPermission([''])">删除</el-button>
        </template>
      </el-table-column>
    </template>

    <template #pagination>
      <el-pagination
        v-if="tableData"
        @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange"
        :current-page="tableData.pages"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="tableData.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.total"
      >
      </el-pagination>
    </template>
  </en-table-layout>
  <el-dialog
    :title="templateTitle"
    v-model="systemVisible"
    width="500px"
    :modal-append-to-body="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form :model="SMSForm" :rules="SMSFormRules" ref="SMSFormRef" label-width="120px">
      <el-form-item label="上级模板:" prop="pid">
        <el-select v-model="SMSForm.pid" clearable placeholder="请选择上级模板" :disabled="disabled">
          <el-option v-for="item in pidList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="模版名称:" prop="name">
        <el-input v-model="SMSForm.name" :minlength="2" :maxlength="20" :disabled="disabled" clearable placeholder="请输入模版名称"></el-input>
      </el-form-item>
      <el-form-item label="平台模版code:" prop="template_code">
        <el-input v-model="SMSForm.template_code" :minlength="2" :maxlength="20" :disabled="disabled" clearable placeholder="请输入平台模版code"></el-input>
      </el-form-item>
     <!--  <el-form-item label="短信类型:" prop="template_type">
        <el-select v-model="SMSForm.template_type" clearable :disabled="disabled" placeholder="请选择短信类型">
          <el-option label="验证码" value="0" />
          <el-option label="短信通知" value="1" />
          <el-option label="推广短信" value="2" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="自定义模版code:" prop="code">
        <el-input v-model="SMSForm.code" :disabled="disabled" clearable placeholder="请输入模版code"></el-input>
      </el-form-item>
      <el-form-item label="是否启用:" prop="enable_status">
        <el-switch v-model="SMSForm.enable_status" inline-prompt :disabled="disabled" active-text="启用" inactive-text="禁用" />
      </el-form-item>
       <el-form-item label="模版内容:" prop="content">
        <el-input v-model="SMSForm.content"  :disabled="disabled" type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" clearable placeholder="请输入模版内容"></el-input>
      </el-form-item>
      <el-form-item label="模版说明:" prop="remark">
        <el-input v-model="SMSForm.remark" type="textarea" :disabled="disabled" :autosize="{ minRows: 3, maxRows: 4 }" placeholder="请输入模版说明"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="systemVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitSMSForm" :disabled="disabled">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
        
        <script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Edit, Search, Share, Upload, CirclePlus } from '@element-plus/icons-vue';
import * as API_Template from '@/api/templateManage';

const router = useRouter();
/* 模版表单 */
const pidList = ref<any>([]);
const disabled = ref(false);
let templateTitle = ref('');
const SMSFormRef = ref();
const systemVisible = ref(false);
const SMSForm = ref<any>({
  name: '',
  content: '',
  code: '',
  enable_status: false,
  remark: '',
  type: 'SMS',
  template_code:''
});
const SMSFormRules = ref<any>({
  pid: [{ required: true, message: '请选择上级模板', trigger: 'change' }],
  name: [{ required: true, message: '请输入模版名称', trigger: 'blur' }],
  template_code: [{ required: true, message: '请输入平台模版code', trigger: 'blur' }],
  content: [{ required: true, message: '请输入模版内容', trigger: 'blur' }],
  code: [
    { required: true, message: '请输入模版code', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '只能输入英文、数字和下划线，不能包含空格', trigger: 'blur' },
  ],
  /*template_type: [{ required: true, message: '请选择短信类型', trigger: 'change' }],
    user_num: [{ required: true, message: '请输入可创建用户数', trigger: 'blur' }], */
});
/* 新增 */
const handleAddRole = () => {
  templateTitle.value = '添加模版';
  disabled.value = false;
  SMSForm.value = {};
  SMSForm.value.type = 'SMS';
  (SMSForm.value.enable_status = false), (systemVisible.value = true);
};
/* 表单提交 */
const submitSMSForm = () => {
  SMSFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const { id } = SMSForm.value;
      const params = { ...SMSForm.value };
      if (id) {
        API_Template.editTemplate(id, params).then(() => {
          systemVisible.value = false;
          ElMessage.success('修改成功！');
          GET_SMSList();
        });
      } else {
        API_Template.addTemplate(params).then(() => {
          systemVisible.value = false;
          ElMessage.success('创建成功!');
          GET_SMSList();
        });
      }
    } else {
      ElMessage.error('表单填写有误，请核对！');
      /*    store.dispatch('showMessage', { message: '表单填写有误，请核对！', type: 'error' }); */
      return false;
    }
  });
};
/* 修改状态 */
const switchEnableStatus = (event, row) => {
  API_Template.editStatus(row.id).then((res) => {
    ElMessage.success('状态修改成功!');
    GET_SMSList();
  });
};
/* 查看模版 */
const handleView = (row) => {
  templateTitle.value = '查看模版';
  SMSForm.value = { ...row };
  disabled.value = true;
  systemVisible.value = true;
};
/* 编辑模版 */
const handleEditRole = (row: any) => {
  templateTitle.value = '编辑模版';
  disabled.value = false;
  SMSForm.value = { ...row };
  SMSForm.value.type = 'SMS';
  systemVisible.value = true;
};
/* 删除模版 */
const handleDeleteRole = (row: any) => {
  ElMessageBox.confirm('确定要删除这个模版吗？', '提示', { type: 'warning' })
    .then(() => {
      API_Template.delTemplate(row.id).then(() => {
        ElMessage.success('删除成功！');
        GET_SMSList();
      });
    })
    .catch(() => {});
};

const loading = ref(false);
const params = ref({
  page_no: 1,
  page_size: 10,
  type: 'SMS',
});
const tableData = ref<any>({});
/* 搜索 */
const searchForm = reactive({
  enable_status: '',
  name: '',
  code: '',
  type: 'SMS',
});

const checkPermission = (permissions: string[]): boolean => {
  return true;
};

const handlePageSizeChange = (size: number) => {
  params.value.page_size = size;
  GET_SMSList();
};

const handlePageCurrentChange = (page: number) => {
  params.value.page_no = page;
  GET_SMSList();
};

const searchEvent = (data: string) => {
  Object.assign(params.value, searchForm);
  params.value.page_no = 1;
  GET_SMSList();
};

const GET_SMSList = () => {
  loading.value = true;
  API_Template.getSMSList(params.value)
    .then((response) => {
      loading.value = false;
      tableData.value = response;
    })
    .catch(() => {
      loading.value = false;
    });
};
const GET_PidList = () => {
  API_Template.getPidList('SMS').then((res) => {
    pidList.value = res;
  });
};
onMounted(() => {
  GET_SMSList();
  GET_PidList();
});
</script>