<template>
  <!-- 后台用户 -->
  <!-- template 内部必须有一个根节点 div，否则<Transition>将会失效，所以这个<a-modal></a-modal> 组件必须放在 根节点 div 里面 -->
  <div>
    <TableProMax
        ref="tableRef"
        :request-api="reqApi"
        :columns="columns"
        :searchFormOptions="searchFormOptions"
        :scroll="{x}"
    >
      <template #tableHeader>
        <a-space>
          <a-button type="primary" @click="addUserManagement">新增用户</a-button>
        </a-space>
      </template>
    </TableProMax>
    <!-- template 内部必须有一个根节点 div，否则<Transition>将会失效，所以这个<a-modal></a-modal> 组件必须放在 根节点 div 里面 -->
    <a-modal v-model:open="visible" :title="title" @ok="submit" @cancel="closeModal">
      <FormProMax ref="formRef" v-model:value="formParams" :form-item-options="formItemOptions"/>
    </a-modal>
  </div>
</template>

<script setup lang="tsx">
import TableProMax from "@/components/table/TableProMax.vue";
import {TableProMaxProps} from "@/types/components/table";
import {message} from 'ant-design-vue'
import {dictSelectNodes} from '@/config/dict.ts'
// const enumsSex = ref<any[]>(dictSelectNodes('Sex'))
// const enumsIsEnable = ref<any[]>(dictSelectNodes('IsEnable'))
import api from '@/axios/index.ts'
import {ref, reactive, onMounted} from 'vue'
import FormProMax from "@/components/form/FormProMax.vue";
import {FormProMaxItemOptions} from "@/types/components/form";
import {FormExpose} from "ant-design-vue/es/form/Form";
import {publicUnitPagerQueryParams, FromItem} from "@/types/views/publicUnit.ts";

const tableRef = ref<ComponentExposed<typeof TableProMax>>(null!)
const formRef = ref<FormExpose>(null)
type TableProps = TableProMaxProps<publicUnitPagerQueryParams>
const reqApi: TableProps['requestApi'] = (params) => api.post('/management/police/user/pager', params)  //分页
const formParams = ref<{
  snowFlakeId?: string,
  name: string,
  sex: number,
  telephone: string,
  isEnable: any,

}>({
  name: '',
  sex: 0,
  telephone: '',
  isEnable: 0,
})
const formItemOptions = ref<FormProMaxItemOptions<FromItem>>({
  name: {
    type: 'input',
    label: '姓名',
    required: true,
    rules: [
      {required: true, message: '请输入姓名'}
    ],
  },
  sex: {
    type: 'radioGroup',
    label: '性别',
    options: dictSelectNodes('Sex'),
    required: true,
  },
  telephone: {
    type: 'input',
    label: '手机号',
    required: true,
    rules: [
      {required: true, message: '请输入手机号'},
      {
        validator: (rule, value) => {
          const phoneRegex = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
          if (!value) {
            return Promise.reject('手机号不能为空');
          } else if (!phoneRegex.test(value)) {
            return Promise.reject('手机号格式不正确');
          } else {
            return Promise.resolve();
          }
        },
        trigger: 'blur',
      },
    ],
  },
  isEnable: {
    type: 'radioGroup',
    label: '启用状态',
    options: dictSelectNodes('IsEnable'),
    required: true,
  },
})
const columns: TableProps['columns'] = [
  {
    dataIndex: 'account',
    title: '账号',
    width: 100,
    ellipsis: true
  },
  {
    dataIndex: 'name',
    title: '名称',
    width: 200,
    ellipsis: true
  },
  {
    dataIndex: 'sex',
    title: '性别',
    customRender: ({text}) => <a-tag>{text?.label}</a-tag>,
    width: 150
  },
  {
    dataIndex: 'telephone',
    title: '手机号码',
    width: 150,
    ellipsis: true
  },
  {
    dataIndex: 'createTime',
    title: '创建时间',
    width: 200,
    ellipsis: true,
  },

  {
    dataIndex: 'isEnable',
    title: '是否启用',
    customRender: ({text}) => <a-tag color={text?.extData?.color}>{text?.label}</a-tag>,
    width: 150
  },
  {
    dataIndex: 'opt',
    title: '操作',
    fixed: "right",
    customRender({record}) {
      return (
          record.isAdmin.value === 1 ?
              <a-space>
                <a-popconfirm
                    style="width:100%"
                    title="确认删除账号吗?"
                    onConfirm={async () => {
                      const resp = await api.delete('/management/police/user/deleteById', {
                        managementPoliceUnitUserId: record.snowFlakeId,
                      })
                      message.success(resp.message)
                      await tableRef.value?.requestGetTableData()
                    }}>
                  <a-button type="primary" danger>删除</a-button>
                </a-popconfirm>
                <a-button type="primary" onClick={async () => {
                  visible.value = true
                  title.value = "编辑用户"
                  formParams.value.snowFlakeId = record.snowFlakeId
                  formParams.value.name = record.name,
                      formParams.value.sex = record.sex.value,
                      formParams.value.telephone = record.telephone,
                      formParams.value.isEnable = record.isEnable?.value

                }}>
                  编辑
                </a-button>
              </a-space>
              :
              <div>超级管理员不能编辑</div>
      )
    }
  },
]
const x: number = columns.reduce((a, b) => a + (b.width as number), 0)
const searchFormOptions: TableProps["searchFormOptions"] = {
  name: {
    type: 'input',
    label: '名称'
  }, sex: {
    type: 'select',
    label: '性别',
    options: [
      {
        value: null,
        label: '全部'
      }, ...dictSelectNodes('Sex')
    ]
  },
  telephone: {
    type: 'input',
    label: '手机号'
  },
  isEnable: {
    type: 'select',
    label: '是否启用',
    options: [
      {
        value: null,
        label: '全部'
      }, ...dictSelectNodes('IsEnable')
    ]
  }
}
const visible = ref(false)
const title = ref('新增用户')
const addUserManagement = () => {
  visible.value = true
}
const submit = async () => {
  await formRef.value.validate()
  const snowFlakeId = ref('')
  if (title.value === '新增用户') {
    snowFlakeId.value = ''
  } else {
    snowFlakeId.value = formParams.value.snowFlakeId
  }
  const managementSecurityUnitUserSaveOrUpdateParams = {
    snowFlakeId: snowFlakeId.value,
    name: formParams.value.name,
    sex: formParams.value.sex,
    telephone: formParams.value.telephone,
    isEnable: formParams.value.isEnable,

  }
  const resp = await api.post('/management/police/user/saveOrUpdate', managementSecurityUnitUserSaveOrUpdateParams)
  message.success(resp.message)
  tableRef.value?.requestGetTableData()
  closeModal()

}

const closeModal = () => {
  formParams.value = {
    name: '',
    sex: 0,
    telephone: '',
    isEnable: 0
  }
  visible.value = false
  title.value = '新增用户'
}
</script>
