<template>
  <div>
    <TableProMax ref="tableRef" :request-api="reqApi" :columns="columns" :searchFormOptions="searchFormOptions" :scroll="{ x }">
      <template #tableHeader>
        <a-space>
          <a-button type="primary" @click="saveOrUpdateEnterprisesUnit">新增企事业单位</a-button>
        </a-space>
      </template>
    </TableProMax>
  </div>
</template>

<script setup lang="tsx">
import { deleteDataModal } from '@/components/tsx/ModalPro.tsx'
import { EnterprisesUnitSaveOrUpdateParams } from '@/types/views/unitManage/police/policeUnit.ts'
import MapContainer from '@/components/aMap/MapContainer.vue'
import { AutoComplete, Button, Input, message, Modal, Space } from 'ant-design-vue'
import { debounce } from 'lodash-es'
import FormProMax from '@/components/form/FormProMax.vue'
import api from '@/axios'
import { ref, reactive } from 'vue'
import TableProMax from '@/components/table/TableProMax.vue'
import { TableProMaxProps } from '@/types/components/table/index.ts'
import { ComponentExposed } from 'vue-component-type-helpers'
import { dictSelectNodes } from '@/config/dict.ts'
import { publicUnitPagerQueryParams } from '@/types/views/publicUnit.ts'
import { FormProMaxItemOptions } from '@/types/components/form//index.ts'
import { FormExpose } from 'ant-design-vue/es/form/Form'
type _FormType = EnterprisesUnitSaveOrUpdateParams & {
  contactPersonInfoName?: string
  contactPersonInfoTelephone?: string
}
type TableProps = TableProMaxProps<publicUnitPagerQueryParams>

// const reqApi: TableProps['requestApi'] = (params) => api.post('/enterprisesUnit/pager', params) //分页
const reqApi: TableProps['requestApi'] = (params) => api.post('/eu/pager', params) //分页
const tableRef = ref<ComponentExposed<typeof TableProMax>>(null)
const columns: TableProps['columns'] = [
  {
    dataIndex: 'name',
    title: '单位名称',
  },

  {
    dataIndex: 'provinceName',
    title: '行政区划',
    customRender: ({ record }) => {
      return `${record?.provinceName}/${record?.cityName}/${record?.districtsName}/${record?.streetName}`
    },
  },

  {
    dataIndex: 'address',
    title: '详细地址',
  },

  {
    dataIndex: 'contactPersonInfo',
    title: '联系人姓名',
    customRender: ({ record }) => {
      return record?.contactPersonInfo?.name
    },
  },
  {
    dataIndex: 'contactPersonInfo',
    title: '联系人手机号',
    customRender: ({ record }) => {
      return record?.contactPersonInfo?.telephone
    },
  },
  {
    dataIndex: 'createTime',
    title: '创建时间',
  },
  {
    dataIndex: 'remark',
    title: '备注',
  },
  {
    dataIndex: 'opt',
    title: '操作',
    customRender: ({ record }) => (
      <Space>
        <Button
          class='btn-warn'
          onClick={() =>
            saveOrUpdateEnterprisesUnit(
              {
                snowFlakeId: record.snowFlakeId,
                policeUnitId: record.policeUnitId,
                name: record.name,
                type: record.type.value,
                administrativeDivisionCodes: [record.province, record.city, record.districts, record.street].filter(Boolean),
                address: record.address,
                point: record.point,
                contactPersonInfoName: record.contactPersonInfo?.name,
                contactPersonInfoTelephone: record.contactPersonInfo?.telephone,
                remark: record.remark,
              },
              tableRef.value?.requestGetTableData
            )
          }
        >
          编辑
        </Button>
        <Button
          class='btn-danger'
          onClick={() =>
            deleteDataModal(record.name, async () => {
              // const resp = await api.delete('/enterprisesUnit/deleteById', {
              const resp = await api.delete('/eu/del_id', {
                enterprisesUnitId: record.snowFlakeId,
              })
              message.success(resp.message)
              await tableRef.value?.requestGetTableData()
            })
          }
        >
          删除
        </Button>
      </Space>
    ),
  },
]
const x: number = columns.reduce((a, b) => a + (b.width as number), 0)

const saveOrUpdateEnterprisesUnit = (params: _FormType, callback: Function) => {
  const _formRef = ref<FormExpose>(null)
  const _mapRef = ref<ComponentExposed<typeof MapContainer>>(null)
  const _formParams = ref<_FormType>({ ...params })

  let city = ''
  const initMarker = (map: AMap.Map) => {
    //添加maker点 设置point
    const maker = new AMap.Marker({
      position: _formParams.value.point,
      draggable: true,
    })
    maker.on('dragend', ({ lnglat }) => {
      _formParams.value.point = lnglat
    })
    map.clearMap()
    map.add(maker)
    map.setFitView()
  }
  const autoAddress = ref<SelectNodeVo<string>[]>([])

  const _formOptions = ref<FormProMaxItemOptions<_FormType>>({
    name: {
      type: 'custom',
      label: '单位名称',
      required: true,
      customRender: () => {
        return (
          // AutoComplete 自动完成 组件
          <AutoComplete
            v-model:value={_formParams.value.name}
            options={autoAddress.value}
            onSelect={(_, options: SelectNodeVo<string>) => {
              _formParams.value.point = options.extData?.location
              _formParams.value.address = options.extData?.address
              initMarker(_mapRef.value?.mapInstance)
            }}
            onSearch={debounce((val: string) => {
              console.log('onSearch___________________', val)

              //@ts-ignore
              const auto = new AMap.AutoComplete({
                city: city,
                // input: 'tipinput',
                citylimit: true,
              })
              auto.search(val, (status, result) => {
                console.log('🚀 ~ auto.search ~ status, result:', status, result)
                if (status === 'complete') {
                  // 生成组件需要数据
                  autoAddress.value = result.tips?.map((e) => {
                    return {
                      value: e.name,
                      label: e.name,
                      extData: {
                        district: e.district,
                        address: e.address,
                        location: e.location,
                      },
                    } as SelectNodeVo<string>
                  })
                } else {
                  autoAddress.value = []
                }
              })
            }, 300)}
            v-slots={{
              option: (item: SelectNodeVo<string>) => {
                return (
                  <div>
                    <p>{item.label}</p>
                    <p style={{ color: '#9a9c9d' }}>
                      {item.extData?.district} {item.extData?.address}
                    </p>
                  </div>
                )
              },
            }}
          >
            <Input placeholder='请输入单位名称' />
          </AutoComplete>
        )
      },
    },
    type: {
      type: 'select',
      label: '单位类型',
      required: true,
      // @ts-ignore
      options: dictSelectNodes('EnterprisesUnitType'),
    },
    administrativeDivisionCodes: {
      type: 'administrativeDivisionTree',
      label: '行政区划',
      required: true,
      componentsProps: {
        // @ts-ignore
        displayRender: ({ labels }): string => {
          city = labels[1]
          return labels.join(' / ')
        },
      },
    },
    address: {
      type: 'inputTextArea',
      label: '详细地址',
    },
    map: {
      type: 'custom',
      label: '经纬度',
      customRender: () => (
        <MapContainer
          ref={_mapRef}
          plugins={['AMap.AutoComplete', 'AMap.PlaceSearch']}
          style={{ width: '100%', height: '300px', position: 'relative' }}
          initCallback={(map) => {
            const contextMenu = new AMap.ContextMenu()
            contextMenu.addItem(
              '标记',
              () => {
                const { lng, lat } = contextMenu.getPosition()
                _formParams.value.point = [lng, lat]
                initMarker(map)
              },
              0
            )
            map.on('rightclick', ({ lnglat }) => {
              contextMenu.open(map, lnglat)
            })
            if (_formParams.value.point) {
              initMarker(map)
            }
          }}
        ></MapContainer>
      ),
    },
    contactPersonInfoName: {
      type: 'input',
      label: '联系人名称',
    },
    contactPersonInfoTelephone: {
      type: 'input',
      label: '联系人电话',
    },
    remark: {
      type: 'inputTextArea',
      label: '备注',
    },
  })
  Modal.confirm({
    title: params.snowFlakeId ? `【${params.name}】 信息编辑` : '新增企事业单位',
    width: 600,
    icon: ' ',
    centered: true,
    content: () => <FormProMax ref={_formRef} v-model:value={_formParams.value} formItemOptions={_formOptions.value} />,
    onOk: async () => {
      await _formRef.value?.validate()
      // const resp = await api.post('/enterprisesUnit/saveOrUpdate', {
      const resp = await api.post('/eu/add_upd', {
        ..._formParams.value,
        contactPersonInfo: {
          name: _formParams.value.contactPersonInfoName,
          telephone: _formParams.value.contactPersonInfoTelephone,
        },
      })
      message.success(resp.message)
      await tableRef.value?.requestGetTableData()

      // reqApi(params)
      callback && callback()
    },
  })
}

const searchFormOptions = reactive<TableProps['searchFormOptions']>({
  name: {
    type: 'input',
    label: '名称',
  },
  treeSelect: {
    // type: 'cascader',
    type: 'administrativeDivisionTree',
    label: '行政区划',
  },
  telephone: {
    type: 'input',
    label: '手机号',
  },
})
</script>
