import type { BasicTableProps } from '@/components/VxeTable';
import { api_checkCustomerGroup, api_deleteCustomerGroup, api_pageCustomerGroupList, customerGroupAddApi, customerGroupEditApi, customerGroupListApi } from '@/api/customerfee/customerfeeset';
import { AddEditCustomerGroup, CustomerGroupPageParam, CustomerGroupParam } from '@/api/customerfee/CustomerFeeSetModel';
import { useDropDownData } from '@/hooks/useDropDownData';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';
import { useMessage } from '@/hooks/useMessage';
import { useQueryList } from '@/hooks/useQueryList';
import { EditType, EditTypeState } from '@/type/BaseEnum';
import { cloneDeep } from '@/utils/cloneDeep';
import { isArrayLength } from '@/utils/is';
import { resCodeSuccess, useReturnData } from '@/utils/useReturnData';
import { ref, reactive, unref, onBeforeMount, h } from 'vue';

const { createConfirm } = useMessage()

/**
 * 客户分组处理
 * @returns 
 */
function useCustomerGroupList(customerGroupListOptions: BasicTableProps) {
    const { 
        storeDropDownData, 
        productList, 
        branchCompanyCustomers, 
        customertList,
    } = useDropDownData()
    onBeforeMount(() => {
        storeDropDownData.addProductList()
        storeDropDownData.addBranchCompanyCustomers()
        storeDropDownData.addCustomertList()
    })
    const searchFormRef = ref()
    const customerGroupParms = reactive<CustomerGroupPageParam>({
        productId: undefined,
        orgId: undefined,
        groupName: undefined,
        customerIdList: [],
        pageNum: 1,
        pageSize: 10,
        total: 0
    })
    const customerGroupState = reactive({
        loading: false,//加载loading
        customerGroupList: [],//用户分组list
        orgId: "",//分公司编号
    })
    // 客户弹窗
    const refAddCustomerFeeSet = ref<{ show: Fn }>()
    // 新增分组
    const addBtn = async () => {
        unref(refAddCustomerFeeSet)?.show({}, EditTypeState.ADD, true)
    }
    // 初始化列表
    const initList = async () => {
        try {
            customerGroupState.loading = true
            customerGroupListOptions.loading = true
            const res = await api_pageCustomerGroupList(listParams)
            if (resCodeSuccess(res)) {
                customerGroupListOptions.data = res.data.records
                customerGroupParms.total = res.data.total
            }
        } finally {
            customerGroupState.loading = false
            customerGroupListOptions.loading = false
        }
    }
    const { resetForm } = useEleFormValidate()
    // 重置
    const resetParams = () => {
        resetForm(searchFormRef.value)
    }
    // 初始化列表、分页数据
    const { sizeChange, currentChange, searchBtn, resetBtn, listParams } = useQueryList<CustomerGroupPageParam>(initList, resetParams, customerGroupParms)
    const { resData } = useReturnData()
    // 操作
    const handleClickChange = (row) => {
        const data = cloneDeep(row)
        switch (data.types) {
            case EditType.EDIT:
                customerGroupState.orgId = data.orgId
                const customerIdList = isArrayLength(data.customerIdList) && data.customerIdList.map(key => String(key))
                const dataParams = {
                    ...data, 
                    customerIdList,
                    groupId: data.id,//分组编号
                }
                unref(refAddCustomerFeeSet)?.show(dataParams, EditTypeState.EDIT, true)
                break;
            case EditType.DELETE:
                onDeleteCustomer(data.id)
                break;
        }
    }
    // 删除分组
    const onDeleteCustomer = async (id: string) => {
        // const res = await api_checkCustomerGroup({ id })
        // if (res.data && res.data.split(',').length > 0) {
        //     createConfirm({
        //         type: "warning",
        //         customClass: 'define-checkcustomer',
        //         title: "系统提示",
        //         message: h('div', { style: 'max-height: 81vh;overflow: auto;' }, [
        //             h('p', { style: 'color: #ff0000;padding: 5px 0;' }, res.data),
        //         ]),
        //         cancelButtonText: "取消",
        //         confirmButtonText: "确定",
        //         dangerouslyUseHTMLString: true,
        //         beforeClose: (action, instance, done) => {
        //             if (action === "confirm") {
        //                 // 删除
        //                 getDeleteCustomerGroup(id)
        //             }
        //             done()
        //         },
        //     })
        //     return false
        // }
        getDeleteCustomerGroup(id)
    }
    const getDeleteCustomerGroup = async (id: string) => {
        const res = await api_deleteCustomerGroup({ id })
        const deleteCode = resData(res, "删除成功")
        if (deleteCode !== 500) initList()
    }
    // 设置分组操作
    const hanleSaveFeesetCustomer = async (customerState: Recordable, params: AddEditCustomerGroup, onclose: Fn, setLoading: Fn) => {
        // customerState => {
        //     "customerNameList": ["澳鹏"],
        //     "groupId": "3bcf8b364d2a47ddae178c3668cb322b"
        // }
        if (customerState.groupId) {
            try {
                // 编辑分组
                const res = await customerGroupEditApi(params)
                const resCode = resData(res, "编辑成功")
                if (resCode !== 500) {
                    // 刷新分组数据
                    initList()
                    onclose()
                }
            } finally {
                setLoading(false)
            }
            return false
        }
        try {
            // 添加分组
            const res = await customerGroupAddApi(params)
            const resCode = resData(res, "添加成功")
            if (resCode !== 500) {
                // 刷新分组数据
                initList()
                onclose()
            }
        } finally {
            setLoading(false)
        }
    }
    
    return {
        searchFormRef,
        customerGroupParms,
        customerGroupState,
        productList, 
        branchCompanyCustomers,
        customertList,
        addBtn,
        sizeChange, 
        currentChange, 
        searchBtn, 
        resetBtn,
        handleClickChange,
        refAddCustomerFeeSet,
        hanleSaveFeesetCustomer
    }
}

export {
    useCustomerGroupList
}