<template>
    <x-search-bar class="mb-8-2">
        <template #default="{ gutter, colSpan }">
            <a-form :model="searchFormData" labelAlign="left">
                <a-row :gutter="24">
                    <!-- 姓名 -->
                    <a-col :span="8">
                        <a-form-item label="姓名112" name="name">
                            <a-input v-model:value="searchFormData.name" placeholder="请输入姓名" />
                        </a-form-item>
                    </a-col>

                    <!-- 身份证号 -->
                    <a-col :span="8">
                        <a-form-item label="身份证号" name="idNumber">
                            <a-input v-model:value="searchFormData.idNumber" placeholder="请输入身份证号" />
                        </a-form-item>
                    </a-col>
                    <!-- 联系方式 -->
                    <a-col :span="8">
                        <a-form-item label="联系方式" name="contact1">
                            <a-input v-model:value="searchFormData.contact1" placeholder="请输入联系方式" />

                        </a-form-item>
                    </a-col>


                    <!-- 分类标签 -->
                    <a-col :span="8">
                        <a-form-item label="分类标签" name="serviceRecipientCategory">
                            <a-select v-model:value="searchFormData.serviceRecipientCategory" allowClear>
                                <a-select-option v-for="item in dicsStore.dictOptions.Service_Recipient_Category2"
                                    :key="item.dval" :value="item.dval">{{
                                        item.introduction }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>

                    <!-- 服务状态（未在映射表中） -->
                    <a-col :span="8">
                        <a-form-item label="服务状态" name="serviceStatus">
                            <a-select v-model:value="searchFormData.serviceStatus" allowClear>
                                <a-select-option v-for="item in dicsStore.dictOptions.SERVICE_STATUS" :key="item.dval"
                                    :value="item.dval">{{
                                        item.introduction }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>

                    <!-- 生存状态 -->
                    <a-col :span="8">
                        <a-form-item label="生存状态" name="survivalStatus">
                            <a-select v-model:value="searchFormData.survivalStatus" allowClear>
                                <a-select-option v-for="item in dicsStore.dictOptions.LIVING_STATUS" :key="item.dval"
                                    :value="item.dval">{{
                                        item.introduction }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>



                    <!-- 档案号 -->
                    <!-- <a-col :span="8">
                                <a-form-item label="档案号" name="fileNumber">
                                    <a-input v-model:value="searchFormData.fileNumber" placeholder="请输入档案号" />
                                </a-form-item>
                            </a-col> -->

                    <!-- 残疾类型 -->
                    <a-col :span="8">
                        <a-form-item label="残疾类型" name="disabilityType">
                            <a-select v-model:value="searchFormData.disabilityType" allowClear>
                                <a-select-option v-for="item in dicsStore.dictOptions.DISABILITY_TYPES" :key="item.dval"
                                    :value="item.dval">{{
                                        item.introduction }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>

                    <!-- 残疾等级 -->
                    <a-col :span="8">
                        <a-form-item label="残疾等级" name="disabilityLevel">
                            <a-select v-model:value="searchFormData.disabilityLevel" allowClear>
                                <a-select-option v-for="item in dicsStore.dictOptions.Disability_Level" :key="item.dval"
                                    :value="item.dval">{{
                                        item.introduction }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>

                    <!-- 是否出租屋/地下室 -->
                    <a-col :span="8">
                        <a-form-item label="是否出租屋/地下室" name="livesInRentedRoomOrBasement">
                            <a-select v-model:value="searchFormData.livesInRentedRoomOrBasement" allowClear>
                                <a-select-option v-for="item in dicsStore.dictOptions.Property_Basement"
                                    :key="item.dval" :value="item.dval">{{ item.introduction
                                    }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>

                    <!-- 是否完成能力评估 -->
                    <a-col :span="8">
                        <a-form-item label="是否完成能力评估" name="completedCapacityAssessment">
                            <a-select v-model:value="searchFormData.completedCapacityAssessment" allowClear>
                                <a-select-option v-for="item in dicsStore.dictOptions.Capability_Assessment"
                                    :key="item.dval" :value="item.dval">{{ item.introduction
                                    }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>

                    <!-- 是否人户分离 -->
                    <a-col :span="8">
                        <a-form-item label="是否人户分离" name="householdResidenceSeparation">
                            <a-select v-model:value="searchFormData.householdResidenceSeparation" allowClear>
                                <a-select-option v-for="item in dicsStore.dictOptions.Separation" :key="item.dval"
                                    :value="item.dval">{{
                                        item.introduction }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>

                    <!-- 婚姻状况 -->
                    <a-col :span="8">
                        <a-form-item label="婚姻状况" name="maritalStatus">
                            <a-select v-model:value="searchFormData.maritalStatus" allowClear>
                                <a-select-option v-for="item in dicsStore.dictOptions.Marital_Status" :key="item.dval"
                                    :value="item.dval">{{
                                        item.introduction }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>

                    <!-- 健康状况 -->
                    <a-col :span="8">
                        <a-form-item label="健康状况" name="healthStatus">
                            <a-select v-model:value="searchFormData.healthStatus" allowClear>
                                <a-select-option v-for="item in dicsStore.dictOptions.Health_Condition" :key="item.dval"
                                    :value="item.dval">{{
                                        item.introduction }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>

                    <!-- 居住情况 -->
                    <a-col :span="8">
                        <a-form-item label="居住情况" name="livingSituation">
                            <a-select v-model:value="searchFormData.livingSituation" allowClear>
                                <a-select-option v-for="item in dicsStore.dictOptions.Living_Situation" :key="item.dval"
                                    :value="item.dval">{{
                                        item.introduction }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>

                    <!-- 统计分类（未在映射表中） -->
                    <a-col :span="8">
                        <a-form-item label="统计分类" name="statisticalClassification">
                            <a-select v-model:value="searchFormData.statisticalClassification" allowClear>
                                <a-select-option v-for="item in dicsStore.dictOptions.Statistical_Classification"
                                    :key="item.dval" :value="item.dval">{{ item.introduction
                                    }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>

                    <!-- 智力情况（未在映射表中） -->
                    <a-col :span="8">
                        <a-form-item label="智力情况" name="intellectualCondition">
                            <a-select v-model:value="searchFormData.intellectualCondition" allowClear>
                                <a-select-option v-for="item in dicsStore.dictOptions.Intellectual_Condition"
                                    :key="item.dval" :value="item.dval">{{ item.introduction
                                    }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>

                    <!-- 是否长期照料失能子女（未在映射表中） -->
                    <a-col :span="8">
                        <a-form-item label="是否长期照料失能子女" name="longTermCareForDisabledChild">
                            <a-select v-model:value="searchFormData.longTermCareForDisabledChild" allowClear>
                                <a-select-option v-for="item in dicsStore.dictOptions.Disabled_Child" :key="item.dval"
                                    :value="item.dval">{{
                                        item.introduction }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>

                    <!-- 老人子女探望情况（未在映射表中） -->
                    <a-col :span="8">
                        <a-form-item label="老人子女探望情况" name="frequencyOfVisits">
                            <a-select v-model:value="searchFormData.frequencyOfVisits" allowClear>
                                <a-select-option v-for="item in dicsStore.dictOptions.Frequency_Visits" :key="item.dval"
                                    :value="item.dval">{{
                                        item.introduction }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>

                    <!-- 户籍地址（建议：若为区域，则用 region；若为详细地址，则用 detailedAddress） -->
                    <a-col :span="8">
                        <a-form-item label="户籍地址" name="hAreaCodes">
                            <AreaCascader v-model:value="searchFormData.hAreaCodes" @change="detailedAddressChange" />
                        </a-form-item>
                    </a-col>



                    <!-- 操作按钮 -->
                    <a-col class="align-left" :span="8">
                        <a-space>
                            <a-button @click="handleResetSearch">{{ $t('button.reset') }}</a-button>
                            <a-button ghost type="primary" @click="handleSearch">
                                {{ $t('button.search') }}
                            </a-button>
                        </a-space>
                    </a-col>
                </a-row>

            </a-form>
        </template>
    </x-search-bar>
    <a-row :gutter="8" :wrap="false">
        <a-col flex="auto">
            <a-card>
                <template #title>
                    <a-space>
                        <span style="font-size: 18px;">服务对象列表</span>
                        <span style="margin-left: 10px;color: #666;">({{ totalCount }}人)</span>
                    </a-space>
                </template>
                <template #extra>
                    <a-space>

                        <a-button type="primary" @click="$refs.editDialogRef.handleCreate()">新建</a-button>
                        <a-dropdown>
                            <template #overlay>
                                <a-menu @click="handleMenuClick">
                                    <a-menu-item key="1">
                                        <UserOutlined />
                                        服务对象导入
                                    </a-menu-item>
                                    <a-menu-item key="2">
                                        <UserOutlined />
                                        更新导入
                                    </a-menu-item>
                                    <a-menu-item key="3">
                                        <UserOutlined />
                                        联系人导入
                                    </a-menu-item>
                                </a-menu>
                            </template>
                            <a-button>
                                导入
                                <DownOutlined />
                            </a-button>
                        </a-dropdown>
                        <a-button danger>批量打标</a-button>
                        <a-button>导入记录</a-button>
                        <a-button>导出</a-button>
                        <a-button>导出记录</a-button>
                    </a-space>
                </template>
                <a-table :columns="columns" :data-source="listData" bordered="true" :loading="loading"
                    :pagination="paginationState" :scroll="{ x: 'max-content' }" @change="onTableChange">
                    <template #bodyCell="{ index, column, record }">
                        <template v-if="column.key === 'serialNumber'">
                            <span>{{ index + 1 }}</span>
                        </template>
                        <template v-if="column.key === 'gender'">
                            <span>{{ record.gender === '1' ? '男' : '女' }}</span>
                        </template>
                        <template v-if="column.key === 'survivalStatus'">
                            <span>{{ dicsStore.getDictLabel('LIVING_STATUS', record.survivalStatus) }}</span>
                        </template>
                        <template v-if="column.key === 'healthStatus'">
                            <span>{{ dicsStore.getDictLabel('Health_Condition', record.healthStatus) }}</span>
                        </template>
                        <template v-if="column.key === 'governmentPurchasedService'">
                            <span>{{ record.governmentPurchasedService ? '是' : '' }}</span>
                        </template>
                        <template v-if="column.key === 'region'">
                            <span>{{ record.region && record.region.join('/') }}</span>
                        </template>
                        <template v-if="column.key === 'serviceRecipientCategory'">
                            <span>{{
                                dicsStore.getDictLabel('Service_Recipient_Category2', record.serviceRecipientCategory)
                            }}</span>
                        </template>

                        <template v-if="'action' === column.key">
                            <x-action-button @click="$refs.editDialogRef.handleEdit(record)">
                                <span>编辑</span>
                            </x-action-button>
                            <x-action-button @click="$refs.detailRef.handleCreate(record)">
                                <span>详情</span>
                            </x-action-button>
                            <x-action-button v-if="platForm==='yunying'">
                                <a-dropdown>
                                    <a class="ant-dropdown-link" @click.prevent>
                                        绑定
                                        <DownOutlined />
                                    </a>
                                    <template #overlay>
                                        <a-menu>
                                            <a-menu-item>
                                                <span>绑定服务人员</span>
                                            </a-menu-item>
                                            <a-menu-item>
                                                <span>绑定管家</span>
                                            </a-menu-item>
                                        </a-menu>
                                    </template>
                                </a-dropdown>
                            </x-action-button>
                            <x-action-button @click="$refs.lineOrderRef.handleEdit(record, '2')">
                                <span>线下工单</span>
                            </x-action-button>
                            <x-action-button @click="checkHandler(record)">
                                <span>转出</span>
                            </x-action-button>
                        </template>
                    </template>
                </a-table>
            </a-card>
        </a-col>
    </a-row>
    <edit-dialog ref="editDialogRef" @ok="onOk"></edit-dialog>
    <detail ref="detailRef"></detail>
    <LineOrder2 ref="lineOrderRef" />

    <!-- <a-drawer v-model:open="lineOpen" class="custom-class" width="600" root-class-name="root-class-name" :root-style="{ color: 'blue' }" :title="lineTitle" placement="right">
        <LineOrder ref="lineOrderRef" />
    </a-drawer> -->
</template>

<script setup>
import { message, Modal } from 'ant-design-vue'
import { nextTick, onMounted, ref } from 'vue'
import apis from '@/apis'
import { config } from '@/config'
import { usePagination } from '@/hooks'
import { useI18n } from 'vue-i18n'
import totalImg from '@/assets/imgs/total.png'
import EditDialog from './components/EditDialog.vue'
import detail from '../../serverObj/serverList/components/detail.vue'
import LineOrder2 from '../../serverObj/serverList/components/LineOrder2.vue'
import { useDicsStore } from '@/store'
import AreaCascader from '@/components/AreaCascader/index.vue'
import NodeTree from '@/components/NodeTree/index.vue'
import dayjs from 'dayjs'
import {DownOutlined} from '@ant-design/icons-vue'
import storage from '@/utils/storage'
defineOptions({
    name: 'yunYingServerObj',
})
const platForm = storage.local.getItem('platform')
const totalCount = ref(0) // 总人数
const dicsStore = useDicsStore()
const lineOpen = ref(false)
const lineTitle = ref('线下工单')

const serviceName = ref('')
const columns = [
    {
        title: '序号',
        dataIndex: 'serialNumber',
        key: 'serialNumber',
        align: 'center',
        width: 80,
    },
    {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
        align: 'center',
        width: 100,
    },
    {
        title: '性别',
        dataIndex: 'gender',
        key: 'gender',
        align: 'center',
        width: 80,
    },
    {
        title: '年龄',
        dataIndex: 'age',
        key: 'age',
        align: 'center',
        width: 80,
    },
    {
        title: '身份证号',
        dataIndex: 'identityNo',
        key: 'identityNo',
        align: 'center',
        width: 180,
    },
    {
        title: '二维码',
        dataIndex: 'qrCode',
        key: 'qrCode',
        align: 'center',
        width: 100,
    },
    {
        title: '是否政府购买服务',
        dataIndex: 'governmentPurchasedService',
        key: 'governmentPurchasedService',
        align: 'center',
        width: 150,
    },
    {
        title: '服务对象分类',
        dataIndex: 'serviceRecipientCategory',
        key: 'serviceRecipientCategory',
        align: 'center',
        width: 120,
    },
    {
        title: '健康状况',
        dataIndex: 'healthStatus',
        key: 'healthStatus',
        align: 'center',
        width: 120,
    },

    {
        title: '生存状态',
        dataIndex: 'survivalStatus',
        key: 'survivalStatus',
        align: 'center',
        width: 120,
    },
    // --- 时间字段：去世时间 ---
    {
        title: '去世时间',
        dataIndex: 'passWayAt',
        key: 'passWayAt',
        align: 'center',
        width: 140,
        customRender: ({ text, record }) => {
            return text ? dayjs(text).format('YYYY-MM-DD') : '-';
        },
    },
    // --- 去世原因 ---
    {
        title: '去世原因',
        dataIndex: 'passWayReason',
        key: 'passWayReason',
        align: 'center',
        width: 140,
    },
    // --- 更新时间 ---
    {
        title: '更新时间',
        dataIndex: 'updateTime',
        key: 'updateTime',
        align: 'center',
        width: 140,
        customRender: ({ text, record }) => {
            return text ? dayjs(text).format('YYYY-MM-DD') : '-';
        },
    },
    // --- 失能险签约日期 ---
    {
        title: '失能险签约日期',
        dataIndex: 'ltcInsuranceSignUpDate',
        key: 'ltcInsuranceSignUpDate',
        align: 'center',
        width: 150,
        customRender: ({ text, record }) => {
            return text ? dayjs(text).format('YYYY-MM-DD') : '-';
        },
    },
    // --- 失能险解约日期 ---
    {
        title: '失能险解约日期',
        dataIndex: 'ltcInsuranceTerminationDate',
        key: 'ltcInsuranceTerminationDate',
        align: 'center',
        width: 150,
        customRender: ({ text, record }) => {
            return text ? dayjs(text).format('YYYY-MM-DD') : '-';
        },
    },
    // --- 联系方式 ---
    {
        title: '联系方式1',
        dataIndex: 'contact1',
        key: 'contact1',
        align: 'center',
        width: 130,
    },
    {
        title: '联系方式2',
        dataIndex: 'contact2',
        key: 'contact2',
        align: 'center',
        width: 130,
    },
    {
        title: '联系方式3',
        dataIndex: 'contact3',
        key: 'contact3',
        align: 'center',
        width: 130,
    },
    {
        title: '所在区域',
        dataIndex: 'region',
        key: 'region',
        align: 'center',
        width: 180,
        ellipsis: true,
    },
    {
        title: '详细地址',
        dataIndex: 'detailedAddress',
        key: 'detailedAddress',
        align: 'center',
        width: 200,
        ellipsis: true,
    },
    {
        title: '残疾类型',
        dataIndex: 'disabilityType',
        key: 'disabilityType',
        align: 'center',
        width: 120,
    },
    {
        title: '残疾等级',
        dataIndex: 'disabilityLevel',
        key: 'disabilityLevel',
        align: 'center',
        width: 120,
    },
    {
        title: '残疾证号',
        dataIndex: 'disabilityCertificateNumber',
        key: 'disabilityCertificateNumber',
        align: 'center',
        width: 160,
    },
    {
        title: '所在站点',
        dataIndex: 'stationName',
        key: 'stationName',
        align: 'center',
        width: 120,
    },
    {
        title: '档案号',
        dataIndex: 'fileNumber',
        key: 'fileNumber',
        align: 'center',
        width: 140,
    },
    // --- 档案创建日期 ---
    {
        title: '建档日期',
        dataIndex: 'dateOfFileCreation',
        key: 'dateOfFileCreation',
        align: 'center',
        width: 140,
        customRender: ({ text, record }) => {
            return text ? dayjs(text).format('YYYY-MM-DD') : '-';
        },
    },
    {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        align: 'center',
        width: 350,
        fixed: 'right',
    }
];
const { t } = useI18n() // 解构出t方法
const { listData, loading, showLoading, hideLoading, paginationState, resetPagination, searchFormData } = usePagination()
const editDialogRef = ref()
const detailRef = ref()
const lineOrderRef = ref()

onMounted(() => {
    searchFormData.value.serviceNodeIds = dicsStore.orgTree[0].value
    getCount(searchFormData.value.serviceNodeIds)
})
getPageList()

async function getCount(params) {
    try {
        const { success, data } = await apis.serverObj.getCount({ serviceNodeCodes: params })
        if (config('http.code.success') === success) {
            totalCount.value = data.count
        }
    } catch (error) {

    }

}
/**
 * 获取表格数据
 * @returns {Promise<void>}
 */
async function getPageList() {
    try {
        const { pageSize, current } = paginationState
        const { success, data, total } = await apis.serverObj
            .getProjectList({
                stationId:storage.local.getItem('stationId'),
                companyId:storage.local.getItem('companyId'),
                pageSize,
                current: current,
                ...searchFormData.value,
            })
            .catch(() => {
                throw new Error()
            })

        if (config('http.code.success') === success) {
            listData.value = data
            paginationState.total = total
        }
    } catch (error) {

    }
}
/**核销 */
const checkHandler = (record) => {
    Modal.confirm({
        title: '即将核销是否继续',
        content: t('button.confirm'),
        okText: t('button.confirm'),
        onOk: async () => {
            const params = {
                ...record,
                status: 'success'
            }
            const { success } = await apis.productOrder.updateItem(params.id, params).catch(() => {
                // throw new Error()
            })
            if (config('http.code.success') === success) {
                // resolve()
                message.success('核销成功')
                await getPageList()
            }
        },
    })
}
/**
 * 删除
 */
function handleDelete({ id }) {
    Modal.confirm({
        title: t('pages.system.user.delTip'),
        content: t('button.confirm'),
        okText: t('button.confirm'),
        onOk: () => {
            return new Promise((resolve, reject) => {
                ; (async () => {
                    try {
                        const { success } = await apis.productOrder.delItem(id).catch(() => {
                            throw new Error()
                        })
                        if (config('http.code.success') === success) {
                            resolve()
                            message.success(t('component.message.success.delete'))
                            await getPageList()
                        }
                    } catch (error) {
                        reject()
                    }
                })()
            })
        },
    })
}
function onAreaChange(value) {
    searchFormData.value.areaCodes = value
}
function detailedAddressChange(value) {
    searchFormData.value.hAreaCodes = value
}
/**
 * 分页
 */
function onTableChange({ current, pageSize }) {
    paginationState.current = current
    paginationState.pageSize = pageSize
    getPageList()
}

/**
 * 搜索
 */
function handleSearch() {
    resetPagination()
    getPageList()
}
/**
 * 重置
 */
function handleResetSearch() {
    searchFormData.value = {}
    resetPagination()
    getPageList()
}
/**
 * 编辑完成
 */
async function onOk() {
    await getPageList()
}
function lineOrder(record) {
    lineOpen.value = true;
    lineTitle.value = '线下工单';

}
</script>

<style lang="less" scoped></style>
