<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"
    width="500px"
    :modal-append-to-body="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    class="!rounded-lg"
  >
    <el-form :model="systemForm" :rules="systemFormRules" ref="systemFormRef" label-width="120px">
      <el-form-item :label="$t('template_name')+':'" prop="name">
        <el-input v-model="systemForm.name"  :disabled="disabled" clearable :placeholder="$t('place')+$t('template_name')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('template_content')+':'" prop="content">
        <el-input v-model="systemForm.content"  type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" :disabled="disabled" clearable :placeholder="$t('place')+$t('template_content')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('template_code')+':'" prop="code">
        <el-input v-model="systemForm.code"  :disabled="disabled" clearable :placeholder="$t('place')+$t('template_code')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('enable_status')+':'" prop="enable_status">
        <el-switch v-model="systemForm.enable_status" inline-prompt :disabled="disabled" active-text="启用" inactive-text="禁用" />
      </el-form-item>
      <el-form-item :label="$t('template_remark')+':'" prop="remark">
        <el-input
          v-model="systemForm.remark"
          type="textarea"
          :disabled="disabled"
          :autosize="{ minRows: 3, maxRows: 4 }"
          :placeholder="$t('place')+$t('template_remark')"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="systemVisible = false">{{$t('cancel')}}</el-button>
        <el-button type="primary" @click="submitsystemForm" :disabled="disabled">{{$t('submit')}}</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';

import { useI18n } from 'vue-i18n';
const { t } = useI18n();

const router = useRouter();
/* 模版表单 */
const disabled = ref(false);
let templateTitle = ref('');
const systemFormRef = ref();
const systemVisible = ref(false);
const systemForm = ref<any>({
  name: '',
  content: '',
  code: '',
  enable_status: false,
  remark: '',
  type: 'SYSTEM',
});
const systemFormRules = ref<any>({
  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' },
  ],
  /* enable_status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    user_num: [{ required: true, message: '请输入可创建用户数', trigger: 'blur' }], */
});
/* 新增 */
const handleAddRole = () => {
  templateTitle.value = t('template_add');
  disabled.value = false;
  systemForm.value = {};
  systemForm.value.type = 'SYSTEM';
  (systemForm.value.enable_status = false), (systemVisible.value = true);
};
/* 表单提交 */
const submitsystemForm = () => {
  systemFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const { id } = systemForm.value;
      const params = { ...systemForm.value };
      if (id) {
        API_Template.editTemplate(id, params).then(() => {
          systemVisible.value = false;
          ElMessage.success(t('edit_success')+'！');
          GET_systemList();
        });
      } else {
        API_Template.addTemplate(params).then(() => {
          systemVisible.value = false;
          ElMessage.success(t('created_success')+'！');
          GET_systemList();
        });
      }
    } 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_systemList();
  });
};
/* 查看模版 */
const handleView = (row) => {
  templateTitle.value = t('template_view');
  systemForm.value = { ...row };
  disabled.value = true;
  systemVisible.value = true;
};
/* 编辑模版 */
const handleEditRole = (row: any) => {
  templateTitle.value = t('template_edit');
  disabled.value = false;
  systemForm.value = { ...row };
  systemForm.value.type = 'SYSTEM';
  systemVisible.value = true;
};
/* 删除模版 */
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_systemList();
      });
    })
    .catch(() => {});
};

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

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

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

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

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

const GET_systemList = () => {
  loading.value = true;
  API_Template.getSMSList(params.value)
    .then((response) => {
      loading.value = false;
      tableData.value = response;
    })
    .catch(() => {
      loading.value = false;
    });
};

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