<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="$t('warehousing_state')">
            <el-select v-model="searchForm.enable_status" clearable :placeholder="$t('place')+$t('warehousing_state')">
              <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="$t('template_name')">
            <el-input v-model="searchForm.name" clearable :placeholder="$t('place')+$t('template_name')"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item :label="$t('template_code')">
            <el-input v-model="searchForm.code" clearable :placeholder="$t('place')+$t('template_code')"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="flex justify-end">
      <el-button class="mr-3" @click="searchEvent"> {{$t('search')}} </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">{{$t('add')}}</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="$t('template_name')" />
      <!-- <el-table-column prop="template_type" label="短信类型" /> -->
      <el-table-column prop="remark" :label="$t('template_remark')"/>
      <!--  <el-table-column prop="audit_status" label="审核状态" /> -->
      <el-table-column prop="enable_status" :label="$t('user_state')">
        <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="$t('operate')" fixed="right" width="300">
        <template #default="scope">
          <el-button size="small" @click="handleView(scope.row)" v-if="checkPermission([''])">{{$t('view')}}</el-button>
          <el-button size="small" type="primary" @click="handleEditRole(scope.row)" v-if="checkPermission([''])">{{$t('edit')}}</el-button>
          <el-button size="small" type="danger" @click="handleDeleteRole(scope.row)" v-if="checkPermission([''])">{{$t('delete')}}</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" :modal-append-to-body="false" :close-on-click-modal="false" :close-on-press-escape="false" class="!rounded-lg">
    <el-form :model="EmailForm" :rules="EmailFormRules" ref="EmailFormRef" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('superior_template')+':'" prop="pid">
            <el-select v-model="EmailForm.pid" clearable :placeholder="$t('place')+$t('superior_template')" :disabled="disabled">
              <el-option v-for="item in pidList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('template_name')+':'" prop="name">
            <el-input v-model="EmailForm.name" :disabled="disabled" clearable :placeholder="$t('place')+$t('template_name')"></el-input>
          </el-form-item>
        </el-col>
        <!-- <el-form-item label="短信类型:" prop="template_type">
          <el-select v-model="EmailForm.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-col :span="12">
          <el-form-item :label="$t('template_code')+':'" prop="code">
            <el-input v-model="EmailForm.code" :disabled="disabled" clearable :placeholder="$t('place')+$t('template_code')"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('enable_status')+':'" prop="enable_status">
            <el-switch v-model="EmailForm.enable_status" inline-prompt :disabled="disabled" active-text="启用" inactive-text="禁用" />
          </el-form-item>
        </el-col>
        <el-form-item :label="$t('template_content')+':'" prop="content">
          <div style="border: 1px solid #ccc">
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
            <Editor
              style="height: 300px; overflow-y: hidden"
              v-model="EmailForm.content"
              :defaultConfig="editorConfig"
              :readOnly="editorReadonly || disabled"
              :mode="editorReadonly || disabled ? 'simple' : 'default'"
              @onCreated="handleCreated"
            />
          </div>
          <!-- <el-input v-model="EmailForm.content" :disabled="disabled" clearable placeholder="请输入模版内容"></el-input> -->
        </el-form-item>
        <el-col :span="24">
          <el-form-item :label="$t('template_remark')+':'" prop="remark">
            <el-input
              v-model="EmailForm.remark"
              type="textarea"
              :disabled="disabled"
              :autosize="{ minRows: 3, maxRows: 4 }"
              :placeholder="$t('place')+$t('template_remark')"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="systemVisible = false">{{$t('cancel')}}</el-button>
        <el-button type="primary" @click="submitEmailForm" :disabled="disabled">{{$t('submit')}}</el-button>
      </div>
    </template>
  </el-dialog>
</template>
          
          <script lang="ts" setup>
import { ref, onMounted, reactive, watch, shallowRef, onBeforeUnmount, nextTick } 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';
import { createEditor, createToolbar, IEditorConfig, IDomEditor } from '@wangeditor/editor';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

const editorReadonly = ref(false);
const disabled = ref(false);
const editorRef = shallowRef();
const mode = ref('default');
const toolbarConfig = {};
const editorConfig = {
  placeholder: t('place')+'...',
  readOnly: editorReadonly.value || disabled.value,
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

// 修改 onEditorContentChange 函数
const onEditorContentChange = (editor: IDomEditor) => {
};

const router = useRouter();
/* 模版表单 */
const pidList = ref<any>([]);
let templateTitle = ref('');
const EmailFormRef = ref();
const systemVisible = ref(false);
const EmailForm = ref<any>({
  name: '',
  content: '',
  code: '',
  enable_status: false,
  remark: '',
  type: 'MAIL',
});
const EmailFormRules = ref<any>({
  pid: [{ required: true, message: t('change')+t('superior_template')+'!', trigger: 'change' }],
  name: [{ required: true, message: t('place')+t('template_name')+'!', trigger: 'blur' }],
  content: [{ required: true, message: t('place')+t('template_content')+'!', trigger: 'blur' }],
  code: [
    { required: true, message:t('place')+t('template_code')+'!', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message:t('template_tips')+'!', trigger: 'blur' },
  ],
  /* template_type: [{ required: true, message: '请选择短信类型', trigger: 'change' }],
   user_num: [{ required: true, message: '请输入可创建用户数', trigger: 'blur' }], */
});
/* 新增 */
const handleAddRole = () => {
  templateTitle.value = t('template_add');
  disabled.value = false;
  editorReadonly.value = false; // 允许编辑
  EmailForm.value = {};
  EmailForm.value.type = 'MAIL';
  EmailForm.value.enable_status = false;
  systemVisible.value = true;
  nextTick(() => {
    if (editorRef.value) {
      editorRef.value.setHtml(''); // 清空编辑器内容
      editorRef.value.enable(); // 启用编辑器
    }
  });
};
/* 表单提交 */
const submitEmailForm = () => {
  EmailFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const { id } = EmailForm.value;
      const params = { ...EmailForm.value };
      // 确保获取最新的编辑器内容
      if (editorRef.value) {
        params.content = editorRef.value.getHtml();
      }
      if (id) {
        API_Template.editTemplate(id, params).then(() => {
          systemVisible.value = false;
          ElMessage.success(t('edit_success')+'！');
          GET_EmailList();
        });
      } else {
        API_Template.addTemplate(params).then(() => {
          systemVisible.value = false;
          ElMessage.success(t('created_success')+'！');
          GET_EmailList();
        });
      }
    } else {
      ElMessage.error(t('form_erroe'));
      /*    store.dispatch('showMessage', { message: '表单填写有误，请核对！', type: 'error' }); */
      return false;
    }
  });
};
/* 修改状态 */
const switchEnableStatus = (event, row) => {
  API_Template.editStatus(row.id).then((res) => {
    ElMessage.success(t('template_type_success')+'!');
    GET_EmailList();
  });
};
/* 查看模版 */
const handleView = (row) => {
  templateTitle.value = t('template_view');
  EmailForm.value = { ...row };
  disabled.value = true;
  editorReadonly.value = true; // 设置编辑器为只读
  systemVisible.value = true;
  nextTick(() => {
    if (editorRef.value) {
      editorRef.value.setHtml(EmailForm.value.content);
      editorRef.value.disable(); // 禁用编辑器
    }
  });
};
/* 编辑模版 */
const handleEditRole = (row: any) => {
  templateTitle.value = t('template_edit');
  disabled.value = false;
  editorReadonly.value = false; // 允许编辑
  EmailForm.value = { ...row };
  EmailForm.value.type = 'MAIL';
  systemVisible.value = true;
  nextTick(() => {
    if (editorRef.value) {
      editorRef.value.setHtml(EmailForm.value.content);
      editorRef.value.enable(); // 启用编辑器
    }
  });
};
/* 删除模版 */
const handleDeleteRole = (row: any) => {
  ElMessageBox.confirm(t('del_info'), t('prompt'), { type: 'warning' })
    .then(() => {
      API_Template.delTemplate(row.id).then(() => {
        ElMessage.success(t('del_success'));
        GET_EmailList();
      });
    })
    .catch(() => {});
};

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

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

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

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

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

const GET_EmailList = () => {
  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('MAIL').then((res) => {
    pidList.value = res;
  });
};
watch(systemVisible, (newValue) => {
  if (!newValue) {
    editorReadonly.value = false;
    if (editorRef.value) {
      editorRef.value.enable();
    }
  }
});
onMounted(() => {
  GET_EmailList();
  GET_PidList();
});
</script>
<style scoped>
:deep(.w-e-text-container) {
  min-height: 200px !important;
}

:deep(.w-e-full-screen-container) {
  z-index: 3000;
}
</style>