<template>
  <TableProMax
      ref="tableRef"
      :request-api="reqApi"
      :columns="columns"
      :searchFormOptions="searchFormOptions"
  >

  </TableProMax>
</template>

<script setup lang="tsx">
import TableProMax from "@/components/table/TableProMax.vue";
import {ref} from "vue";
import {ComponentExposed} from "vue-component-type-helpers";
import {TableProMaxProps, TableProMaxSlots} from "@/types/components/table";
import {
  EnterprisesUnitPagerQueryParams, EnterprisesUnitPagerVo, EnterprisesUnitSaveOrUpdateParams,
  PoliceUnitPagerQueryParams,
  PoliceUnitPagerVo
} from "@/types/views/unitManage/policeUnit.ts";
import api from "@/axios";
import {dictSelectNodes} from "@/config/dict.ts";
import {message, Modal} from "ant-design-vue";
import {UNIT_TYPE} from "@/config";
import {PageParams} from "@/types/hooks/useTableProMax.ts";
import {submitSimpleFormModal, deleteDataModal} from "@/components/tsx/ModalPro.tsx";

type TableProps = TableProMaxProps<PoliceUnitPagerVo, PoliceUnitPagerQueryParams>

const tableRef = ref<ComponentExposed<typeof TableProMax>>(null!)
const reqApi: TableProps['requestApi'] = (params) => api.post('/management/super/policeUnit/pager', params)
const columns: TableProps['columns'] = [
  {
    dataIndex: 'name',
    title: '名称'
  }, {
    dataIndex: 'code',
    title: '代码'
  }, {
    dataIndex: 'contactPersonInfo',
    title: '联系人',
    customRender({record}) {
      return record.contactPersonInfo?.name + "/" + record.contactPersonInfo?.telephone
    },
  }, {
    dataIndex: 'provinceName',
    title: '行政区划',
    customRender: ({record}) => [record.provinceName, record.cityName, record.districtsName, record.streetName].filter(Boolean).join('/')
  }, {
    dataIndex: 'isEnable',
    title: '是否启用',
    customRender: ({text}) => <a-tag color={text?.extData?.color}>{text?.label}</a-tag>,
  }, {
    dataIndex: 'checkStatus',
    title: '审核状态',
    customRender: ({text}) => <a-tag color={text?.extData?.color}>{text?.label}</a-tag>,
  }, {
    dataIndex: 'createTime',
    title: '创建时间'
  }, {
    dataIndex: 'opt',
    title: '操作',
    customRender({record}) {
      if (record.checkStatus.value === 1) {
        return <a-space>
          <a-popconfirm
              title="确认审核通过嘛?"
              onConfirm={async () => {
                const resp = await api.post('/management/checkPass', {
                  checkDataId: record.snowFlakeId,
                  unitOptType: UNIT_TYPE.police
                })
                message.success(resp.message)
                await tableRef.value?.requestGetTableData()
              }}>
            <a-button type="primary">审核通过
            </a-button>
          </a-popconfirm>
        </a-space>
      }
      return <a-space>
        <a-button
            class="btn-success"
            onClick={() => showEnterprisesUnit(record)}
        >企事业单位
        </a-button>
        <a-button
            class={record.isEnable.value === 0 ? 'btn-danger' : 'btn-success'}
            onClick={async () => {
              const resp = await api.post('/management/disableOrEnable', {
                dataId: record.snowFlakeId,
                unitOptType: UNIT_TYPE.police
              })
              message.success(resp.message)
              await tableRef.value?.requestGetTableData()
            }}
        >{record.isEnable.value === 0 ? '禁用' : '启用'}</a-button>
      </a-space>
    },
  }
]
const searchFormOptions = ref<TableProps["searchFormOptions"]>({
  name: {
    type: 'input',
    label: '名称'
  }, code: {
    type: 'input',
    label: '代码'
  }, administrativeDivisionCodes: {
    type: 'administrativeDivisionTree',
    label: '行政区划',
  }, isEnable: {
    type: 'select',
    label: '是否启用',
    options: [
      {
        value: null,
        label: '全部'
      }, ...dictSelectNodes('IsEnable')
    ]
  }, checkStatus: {
    type: 'select',
    label: '审核状态',
    options: [
      {
        value: null,
        label: '全部'
      }, ...dictSelectNodes('CheckStatus')
    ]
  }
})

type _TableProps = TableProMaxProps<EnterprisesUnitPagerVo, EnterprisesUnitPagerQueryParams>;
const showEnterprisesUnit = (policeUnitPagerVo: PoliceUnitPagerVo) => {
  const saveOrUpdateEnterprisesUnit = (data?: EnterprisesUnitSaveOrUpdateParams & {
    contactPersonInfoName?: string;
    contactPersonInfoTelephone?: string
  }) => submitSimpleFormModal<EnterprisesUnitSaveOrUpdateParams & {
    contactPersonInfoName?: string;
    contactPersonInfoTelephone?: string
  }>({
    title: data.snowFlakeId ? `【${data.name}】 信息编辑` : '新增企事业单位',
    formOptions: {
      name: {
        type: 'input',
        label: '单位名称',
        required: true
      },
      administrativeDivisionCodes: {
        type: 'administrativeDivisionTree',
        label: '行政区划',
        required: true,
      },
      address: {
        type: 'inputTextArea',
        label: '详细地址'
      },
      contactPersonInfoName: {
        type: 'input',
        label: '联系人名称'
      },
      contactPersonInfoTelephone: {
        type: 'input',
        label: '联系人电话'
      },
      remark: {
        type: 'inputTextArea',
        label: '备注'
      }
    },
    formParams: data,
    submit: async (params) => {
      params.contactPersonInfo = {
        name: params.contactPersonInfoName,
        telephone: params.contactPersonInfoTelephone
      }
      const resp = await api.post('/enterprisesUnit/saveOrUpdate', params)
      message.success(resp.message)
      await _tableRef.value?.requestGetTableData()
    }
  })
  const _tableRef = ref<ComponentExposed<typeof TableProMax>>(null)
  const _columns: _TableProps['columns'] = [
    {
      dataIndex: 'name',
      title: '名称'
    }, {
      dataIndex: 'contactPersonInfo',
      title: '联系人',
      customRender: ({text}) => text?.name + "/" + text.telephone
    }, {
      dataIndex: 'province',
      title: '行政区划',
      customRender: ({record}) => [record.provinceName, record.cityName, record.districtsName, record.streetName].filter(Boolean).join("/")
    }, {
      dataIndex: 'address',
      title: '详细地址'
    }, {
      dataIndex: 'remark',
      title: '备注'
    }, {
      dataIndex: 'createTime',
      title: '创建时间'
    }, {
      dataIndex: 'opt',
      title: '操作',
      customRender: ({record}) => <a-space>
        <a-button
            class="btn-warn"
            onClick={() => saveOrUpdateEnterprisesUnit({
              snowFlakeId: record.snowFlakeId,
              policeUnitId: record.policeUnitId,
              name: record.name,
              administrativeDivisionCodes: [record.province, record.city, record.districts, record.street].filter(Boolean),
              address: record.address,
              contactPersonInfoName: record.contactPersonInfo?.name,
              contactPersonInfoTelephone: record.contactPersonInfo?.telephone,
              remark: record.remark
            })}
        >编辑
        </a-button>
        <a-button class="btn-danger" onClick={() => deleteDataModal(record.name, async () => {
          const resp = await api.delete('/enterprisesUnit/deleteById', {
            enterprisesUnitId: record.snowFlakeId
          })
          message.success(resp.message)
          await _tableRef.value?.requestGetTableData()
        })}>删除
        </a-button>
      </a-space>
    }
  ]
  const _reqApi: _TableProps["requestApi"] = (params) => {
    (params as PageParams<EnterprisesUnitPagerQueryParams>).params.policeUnitId = policeUnitPagerVo.snowFlakeId
    return api.post('/enterprisesUnit/pager', params)
  }
  Modal.info({
    title: `【${policeUnitPagerVo.name}】 管辖企事业单位`,
    width: '80%',
    content: () => <TableProMax
        ref={_tableRef}
        columns={_columns}
        requestApi={_reqApi}
        v-slots={{
          tableHeader: (_) => {
            return <a-space>
              <a-button
                  class="btn-success"
                  onClick={() => saveOrUpdateEnterprisesUnit({
                    name: undefined,
                    policeUnitId: policeUnitPagerVo.snowFlakeId,
                    administrativeDivisionCodes: [policeUnitPagerVo.province, policeUnitPagerVo.city, policeUnitPagerVo.districts, policeUnitPagerVo.street].filter(Boolean)
                  })}
              >新增
              </a-button>
              <a-button disabled>导入</a-button>
            </a-space>
          }
        } as TableProMaxSlots<PoliceUnitPagerVo>}
    />
  })
}

</script>

<style scoped lang="scss">

</style>
