<template>
  <div>
    <div style="display: flex">
      <div class="dict-type">
        <en-table-layout :tableData="tableDataType.data" :loading="loading" @cell-click="tableClick" style="cursor: pointer">
          <template #toolbar>
            <div class="inner-toolbar">
              <div class="toolbar-btns">
                <span style="font-size: 15px; padding-right: 10px">{{$t('dic_class_list')}}</span>
                <el-button size="small" v-if="checkPermission(['dictDataType:add'])" type="primary" @click="handleAddType">{{$t('add')}}</el-button>
              </div>
              <div class="toolbar-search"></div>
            </div>
          </template>
          <template #table-columns>
            <el-table-column prop="id" :label="$t('dic_sn')" />
            <el-table-column prop="name" :label="$t('dic_name')" />
            <el-table-column prop="type" :label="$t('dic_type')" />
            <el-table-column :label="$t('operate')" width="150px">
              <template #default="scope">
                <el-button size="small" v-if="checkPermission(['dictDataType:edit'])" @click="handleEditType(scope.$index, scope.row)">{{$t('edit')}}</el-button>
                <el-button size="small" v-if="checkPermission(['dictDataType:del'])" type="danger" @click="handleDeleteType(scope.$index, scope.row)"
                  >{{$t('delete')}}</el-button
                >
              </template>
            </el-table-column>
          </template>

          <template #pagination>
            <el-pagination
              v-if="tableDataType"
              @size-change="handlePageSizeChangeType"
              @current-change="handlePageCurrentChangeType"
              :current-page="tableDataType.page_no"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="tableDataType.page_size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="tableDataType.data_total"
            >
            </el-pagination>
          </template>
        </en-table-layout>
      </div>
      <div class="dict-data">
        <en-table-layout :tableData="tableData.data" :loading="loading">
          <template #toolbar>
            <div class="inner-toolbar">
              <div class="toolbar-btns">
                <span style="font-size: 15px; padding-right: 10px">{{$t('dic_data_list')}}</span>
                <el-button size="small" v-if="checkPermission(['dictData:add']) && params.dict_type" type="primary" @click="handleAddData">{{$t('add')}}</el-button>
              </div>
              <div class="toolbar-search"></div>
            </div>
          </template>

          <template #table-columns>
            <el-table-column prop="id" :label="$t('dic_id')" />
            <el-table-column prop="label" :label="$t('dic_label')" />
            <el-table-column prop="value" :label="$t('dic_value')"/>
            <el-table-column prop="sort" :label="$t('dic_sort')" />
            <el-table-column :label="$t('default_flag')">
              <template #default="{ row }">{{ row.default_flag === true ? '是' : '否' }}</template>
            </el-table-column>
            <el-table-column :label="$t('operate')" width="150px">
              <template #default="scope">
                <el-button size="small" v-if="checkPermission(['dictData:edit'])" @click="handleEditData(scope.$index, scope.row)">{{$t('edit')}}</el-button>
                <el-button size="small" v-if="checkPermission(['dictData:del'])" type="danger" @click="handleDeleteData(scope.$index, scope.row)"
                  >{{$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.page_no"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="tableData.page_size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="tableData.data_total"
            >
            </el-pagination>
          </template>
        </en-table-layout>
      </div>
    </div>
    <el-dialog :title="dictTypeForm.id ? $t('edit') : $t('add')" v-model="dialogTypeVisible" width="500px" class="!rounded-lg">
      <el-form :model="dictTypeForm" :rules="dictTypeRules" ref="dictTypeFormRef" label-width="120px">
        <el-form-item :label="$t('dic_name')" prop="name">
          <el-input v-model="dictTypeForm.name" :minlength="2" :maxlength="20" clearable :placeholder="$t('place')+$t('dic_name')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('dic_type')" prop="type">
          <el-input v-model="dictTypeForm.type" :minlength="2" :maxlength="50" clearable :placeholder="$t('place')+$t('dic_type')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('notes')" prop="remark">
          <el-input v-model="dictTypeForm.remark" type="textarea" :autosize="{ minRows: 3, maxRows: 4 }" :placeholder="$t('place')+$t('notes')"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogTypeVisible = false">{{$t('cancel')}}</el-button>
          <el-button type="primary" @click="submitTypeForm">{{$t('submit')}}</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog :title="dictDataForm.id ?  $t('edit') : $t('add')" v-model="dialogVisible" width="500px" class="!rounded-lg">
      <el-form :model="dictDataForm" :rules="dictDataRules" ref="dictDataFormRef" label-width="120px">
        <el-form-item :label="$t('dic_type')" prop="dict_type">
          <el-input v-model="dictDataForm.dict_type" :disabled="true" :placeholder="$t('place')+$t('dic_type')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('default_flag')" prop="是否默认选中">
          <el-radio-group v-model="dictDataForm.default_flag">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('dic_label')" prop="label">
          <el-input v-model="dictDataForm.label" :minlength="1" :maxlength="20" clearable :placeholder="$t('place')+$t('dic_label')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('dic_value')" prop="value">
          <el-input v-model="dictDataForm.value" :minlength="2" :maxlength="20" clearable :placeholder="$t('place')+$t('dic_value')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('dic_sort')" prop="sort">
          <el-input v-model="dictDataForm.sort" :minlength="2" :maxlength="20" clearable :placeholder="$t('place')+$t('dic_sort')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('notes')" prop="remark">
          <el-input v-model="dictDataForm.remark" type="textarea" :autosize="{ minRows: 3, maxRows: 4 }" :placeholder="$t('place')+$t('notes')"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">{{$t('cancel')}}</el-button>
          <el-button type="primary" @click="submitDataForm">{{$t('submit')}}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import * as API_Setting from '@/api/setting';
import { RegExp } from '../../composables/ui-utils/RegExp';

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

// 列表loading状态
const loading = ref(false);

// 列表参数
const params = reactive({
  page_no: 1,
  page_size: 10,
  dict_type: '',
});

const paramsType = reactive({
  page_no: 1,
  page_size: 10,
});

// 列表数据
const tableData = ref<any>([]);
const tableDataType = ref<any>([]);

// 字典表单
const dictDataForm = ref<any>({});
const dictTypeForm = ref<any>({});

// 字典表单 规则
const dictTypeRules = {
  name: [
    { required: true, message: t('place')+t('dic_name')+'!', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value && !RegExp.userName.test(value)) {
          callback(new Error('只支持汉字、字母、数字、"-"、"_"的组合！'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  type: [
    { required: true, message:t('place')+t('dic_type')+'!', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value && !RegExp.userName.test(value)) {
          callback(new Error('只支持汉字、字母、数字、"-"、"_"的组合！'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
};

const dictDataRules = {
  dict_type: [
    { required: true, message:t('place')+t('dic_type')+'!', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value && !RegExp.userName.test(value)) {
          callback(new Error('只支持汉字、字母、数字、"-"、"_"的组合！'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  label: [
    { required: true, message:t('place')+t('dic_label')+'!', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' },
  ],
  value: [{ required: true, message:t('place')+t('dic_value')+'!', trigger: 'blur' }],
  sort: [{ required: true, message:t('place')+t('dic_sort')+'!', trigger: 'blur' }],
};

// 字典表单 dialog
const dialogVisible = ref(false);
const dialogTypeVisible = ref(false);

const dictTypeFormRef = ref();
const dictDataFormRef = ref();


const tableClick = (row) => {
  params.dict_type = row.type;
  GET_DictDataList();
};

const handlePageSizeChangeType = (size) => {
  paramsType.page_size = size;
  GET_DictTypeList();
};

const handlePageCurrentChangeType = (page) => {
  paramsType.page_no = page;
  GET_DictTypeList();
};

const handlePageSizeChange = (size) => {
  params.page_size = size;
  GET_DictDataList();
};

const handlePageCurrentChange = (page) => {
  params.page_no = page;
  GET_DictDataList();
};

const handleAddType = () => {
  dictTypeForm.value = {
    status: 0,
  };
  dialogTypeVisible.value = true;
};

const handleAddData = () => {
  dictDataForm.value = {
    status: 0,
    sort: 0,
    dict_type: params.dict_type,
    default_flag: false,
  };
  dialogVisible.value = true;
};

const handleEditType = (index, row) => {
  dictTypeForm.value = JSON.parse(JSON.stringify(row));
  dialogTypeVisible.value = true;
};

const handleEditData = (index, row) => {
  dictDataForm.value = JSON.parse(JSON.stringify(row));
  dialogVisible.value = true;
};

const handleDeleteType = (index, row) => {
  ElMessageBox.confirm(t('dic_class_info'), t('prompt'), { type: 'warning' })
    .then(() => {
      API_Setting.deleteDictType({ id: row.id }).then(() => {
        ElMessage.success(t('del_success'));
        GET_DictTypeList();
      });
    })
    .catch(() => {});
};

const handleDeleteData = (index, row) => {
  ElMessageBox.confirm(t('dic_data_info'),  t('prompt'), { type: 'warning' })
    .then(() => {
      API_Setting.deleteDictData({ id: row.id }).then(() => {
        ElMessage.success(t('del_success'));
        GET_DictDataList();
      });
    })
    .catch(() => {});
};
const submitTypeForm = () => {
  dictTypeFormRef.value.validate((valid) => {
    if (valid) {
      const { id } = dictTypeForm.value;
      const params = JSON.parse(JSON.stringify(dictTypeForm.value));
      params.id = id;
      if (id) {
        API_Setting.editDictType(params).then((response) => {
          dialogTypeVisible.value = false;
          ElMessage.success( t('edit_success'));
          GET_DictTypeList();
        });
      } else {
        API_Setting.addDictType(params).then(() => {
          dialogTypeVisible.value = false;
          ElMessage.success( t('add_success'));
          GET_DictTypeList();
        });
      }
    } else {
      ElMessage.error(t('form_erroe'));
      return false;
    }
  });
};

const submitDataForm = () => {
  dictDataFormRef.value.validate((valid) => {
    if (valid) {
      const { id } = dictDataForm.value;
      const params = JSON.parse(JSON.stringify(dictDataForm.value));
      params.id = id;
      if (id) {
        API_Setting.editDictData(params).then((response) => {
          dialogVisible.value = false;
          ElMessage.success(t('edit_success'));
          GET_DictDataList();
        });
      } else {
        API_Setting.addDictData(params).then(() => {
          dialogVisible.value = false;
          ElMessage.success(t('add_success'));
          GET_DictDataList();
        });
      }
    } else {
      ElMessage.error(t('form_erroe'));
      return false;
    }
  });
};

const GET_DictTypeList = () => {
  loading.value = true;
  API_Setting.getDictTypeList(paramsType)
    .then((response) => {
      loading.value = false;
      tableDataType.value = response;
      console.log(tableDataType.value);
    })
    .catch(() => {
      loading.value = false;
    });
};

const GET_DictDataList = () => {
  loading.value = true;
  API_Setting.getDictDataList(params)
    .then((response) => {
      loading.value = false;
      tableData.value = response;
    })
    .catch(() => {
      loading.value = false;
    });
};

const checkPermission = (permissions) => {
  // 实现权限检查逻辑
  return true;
};
onMounted(() => {
  GET_DictDataList();
  GET_DictTypeList();
});

</script>
  
  <style scoped>
.dict-type {
  width: 50%;
}

.dict-data {
  width: 50%;
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

.el-dialog__body {
  padding: 10px 20px;
}
</style>