<template>
  <cacp-search-layout>
    <template #search>
      <cacp-search-panel-layout
        :model="state.queryData"
        ref="formRef"
        label-position="left"
        label-width="auto"
        :gutter="30"
      >
        <el-form-item label="字典名称" prop="dictName">
          <el-input
            v-model="state.queryData.dictName"
            placeholder="请输入字典名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType">
          <el-input
            v-model="state.queryData.dictType"
            placeholder="请输入字典类型"
            clearable
          />
        </el-form-item>
        <el-form-item label="创建开始时间" prop="beginTime">
          <el-date-picker v-model="state.queryData.beginTime" clearable />
        </el-form-item>
        <el-form-item label="创建结束时间" prop="endTime">
          <el-date-picker v-model="state.queryData.endTime" clearable />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="state.queryData.status"
            placeholder="字典状态"
            clearable
          >
            <el-option
              v-for="item in dict.sys_normal_disable"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>

        <template #buttonGroup>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="info" @click="onReset">重置</el-button>
        </template>
      </cacp-search-panel-layout>
    </template>
    <cacp-complex-table
      :actions="actions"
      :data="tableData"
      :pagination="tablePagination"
      :actionsWidth="120"
      @selection-change="handleSelectionChange"
      @on-page-change="onPageChange"
      @on-size-change="onSizeChange"
      :loading="loading"
    >
      <el-table-column type="selection" width="36" align="center" />
      <el-table-column label="字典名称" align="center" prop="dictName" :show-overflow-tooltip="true" />
      <el-table-column label="字典类型" align="center" :show-overflow-tooltip="true">
        <template #default="scope">
          <router-link :to="'/system-dictData/' + scope.row.pkDictType" class="link-type">
            <span>{{ scope.row.dictType }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ dayjs(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
        </template>
      </el-table-column>
    </cacp-complex-table>
  </cacp-search-layout>

  <cacp-dialog v-model="state.dialogVisible" :resizable="false" :title="state.title" width="500px" @closed="onDialogClosed">
    <el-form
      :model="state.orderInfo"
      ref="modifyFormRef"
      :rules="infoRules"
      label-width="auto"
      label-position="left"
      :disabled="!state.isEdit"
    >
      <el-form-item label="字典名称" prop="dictName" required>
        <el-input v-model="state.orderInfo.dictName" maxlength="100" show-word-limit />
      </el-form-item>
      <el-form-item label="字典类型" prop="dictType" required>
        <el-input v-model="state.orderInfo.dictType" maxlength="100" show-word-limit/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="state.orderInfo.status">
          <el-radio
            v-for="dict in sys_normal_disable"
            :key="dict.value"
            :label="dict.value"
          >{{ dict.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="state.orderInfo.remark" type="textarea" placeholder="请输入内容" />
      </el-form-item>
    </el-form>
    <template #footer v-if="state.isEdit">
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onSubmit">确定</el-button>
    </template>
  </cacp-dialog>
</template>
<script setup lang="ts">
import { useLoading } from '@cacp/ui'
import { listType, addType, updateType, delType, refreshCache, remove } from '@/apis/system/dictType'
import config from '@/config'

import dayjs from 'dayjs'

import {
  SuccessResultCode,
  useComplexTable,
  type SearchPanelLayoutInstance,
  type TableAction
} from '@cacp/ui'
import type { FormInstance, FormRules } from 'element-plus'
import { ref, reactive, onBeforeMount } from 'vue'
import { permissionStatus } from '@/utils/globalPermission'
import type { DictTypeQuery, DictTypeInfo, AjaxResult } from '@/types/system/dictType'
import { useDictType } from '@/components/useDict'
import { ElForm, ElMessage } from 'element-plus'
// 字典数据
const sys_normal_disable = [
  { label: '正常', value: '0' },
  { label: '停用', value: '1' }
]
interface State {
  queryData: DictTypeQuery
  orderInfo: DictTypeInfo
  dialogVisible: boolean
  isEdit: boolean
  title: string
  isEditDisabled: boolean
}
const { loading, setLoading } = useLoading()
const { dict } = useDictType('sys_normal_disable')
const tableHooks = useComplexTable<DictTypeInfo>(config)
const { tableData, tablePagination, setPagination, setPageIndex, setPageSizes } = tableHooks

const formRef = ref<SearchPanelLayoutInstance>()
const modifyFormRef = ref<FormInstance>()
const ids = ref<number[]>([])

const state = reactive<State>({
  queryData: {
    dictName: '',
    dictType: '',
    status: '',
    beginTime: '',
    endTime: ''
  },
  orderInfo: {
    pkDictType: null,
    dictName: '',
    dictType: '',
    status: '0',
    createBy: '',
    createTime: '',
    updateBy: '',
    updateTime: '',
    remark: ''
  },
  dialogVisible:false,
  isEdit: false,
  title: '',
  isEditDisabled: false
})

const infoRules = reactive<FormRules<DictTypeInfo>>({
  dictName: [{ required: true, message: '必须输入字典名称', trigger: 'blur'}],
  dictType: [{ required: true, message: '必须输入字典类型', trigger: 'blur' },
    {
      pattern: /^[a-z][a-z0-9_]*$/,
      message: '字典类型必须以字母开头，且只能为（小写字母，数字，下滑线）',
      trigger: 'blur' }],
  status: [{ required: true, message: '必须选择状态', trigger: 'blur'}]
})

const actions = <Array<TableAction>>[
  {
    key: '1',
    text: '新建',
    onclick: onCreate,
    limit: permissionStatus('none', 'DICT_TYPE_ADD_BT'),
    position: 'left',
    type: 'primary',
  },
  {
    key: '2',
    text: '编辑',
    onclick: onEdit,
    limit: permissionStatus('one', 'DICT_TYPE_EDIT_BT'),
    type: 'primary'
  },
  {
    key: '3',
    text: '删除',
    onclick: onDelete,
    confirm: true,
    limit: permissionStatus('none', 'DICT_TYPE_DELETE_BT'),
    position: 'left',
    type: 'primary'
  },
  {
    key: '4',
    text: '删除',
    onclick: onDelete,
    confirm: true,
    limit: permissionStatus('one', 'DICT_TYPE_DELETE_BT'),
    type: 'primary'
  },
  {
    key: '5',
    text: '刷新',
    type: 'primary',
    plain: true,
    onclick: handleRefreshCache,
    limit: 'none',
    position: 'right'
  },
]

function onDialogClosed() {
  if(state.dialogVisible){
    state.dialogVisible = false
    onPageChange(1)
  }
}
function handleRefreshCache() {
  refreshCache().then(() => {
    ElMessage.success("刷新成功");
  });
}

function onSearch() {
  onPageChange(1)
}

function onReset() {
  formRef.value.resetFields()
  onPageChange(1)
}

function onCreate() {
  state.dialogVisible = true
  state.isEdit = true
  state.title = "新 增";
  state.isEditDisabled = true
  const newForm = <DictTypeInfo>{
      pkDictType:undefined,
      dictName: '',
      dictType: '',
      status: '0',
      createBy: '',
      createTime: '',
      updateBy: '',
      updateTime: '',
      remark: ''
  }
  Object.assign(state.orderInfo, newForm)
}

async function onDelete(row: DictTypeInfo) {
  const res = await remove([row.pkDictType] || ids.value)
  console.log(res);
  if (res.code == "0") {
    ElMessage.success("修改成功")
    onPageChange(1)
  } else {
    ElMessage.error(res.message)
  }
}

// 取消
function onCancel() {
  if(state.dialogVisible){
    state.dialogVisible = false
    onPageChange(1)
  }
}
// 提交
function onSubmit() {
  modifyFormRef.value.validate(async (isValid: boolean) => {
    if (isValid) {
      if (state.orderInfo.pkDictType) {
        const res: AjaxResult<number> = await updateType(state.orderInfo)
          if(res.code == "200"){
            ElMessage.success("修改成功")
            state.dialogVisible = false
            onPageChange(1)
          } else {
            ElMessage.error(res.msg)
          }
      } else {
        const res: AjaxResult<number> = await addType(state.orderInfo)
        if(res.code == "200"){
          ElMessage.success("新增成功")
          state.dialogVisible = false
          onPageChange(1)
        } else {
          ElMessage.error(res.msg)
        }
      }
    }
  })
}

function onView(row: DictTypeInfo) {
  state.dialogVisible = true
  state.isEdit = false
  state.title = "查 看";
  state.orderInfo = row
}

function onEdit(row: DictTypeInfo) {
  state.dialogVisible = true
  state.isEdit = true
  state.title = "编 辑";
  state.isEditDisabled = false
  state.orderInfo = row
}

function onPageChange(page: number) {
  setPageIndex(page)
  onLoadData()
}
function onSizeChange(size: number) {
  setPageSizes(size)
  onLoadData()
}
// 多选框选中数据
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.pkDictType)
}

// 加载数据
async function onLoadData() {
  const query = { ...state.queryData, pageIndex: tablePagination.currentPage, pageSize: tablePagination.pageSize }
  setLoading(true)
  const res = await listType(query)
  if (res.code == SuccessResultCode) {
    setPagination(res.data)
  }
  setLoading(false)
}

onBeforeMount(async () => {
  onLoadData()
})
</script>
