import { ref, reactive, unref, computed, watch, watchEffect, h, nextTick, Ref } from 'vue';
import { alphabeticalOrder, dealCountryList } from '@/utils/dealData';
// import type { ListIitem } from '@/api/base/BaseDataModel';
// import { CountryChoiseEnum } from '@/type/BaseEnum';
import { cloneDeep } from '@/utils/cloneDeep';
import { api_checkCustomerGroupOperateType, api_checkFeeSetGroup, customerFilterGroup, getcustomerGroupListApi } from '@/api/customerfee/customerfeeset';
import { resCodeSuccess, useReturnData } from '@/utils/useReturnData';
import { useDropDownData } from "@/hooks/useDropDownData";
import { isArrayLength, isStrings } from '@/utils/is';
import { ListIitem } from '@/api/base/BaseDataModel';
import { useMessage } from '@/hooks/useMessage';
import { EditTypeState } from '@/type/BaseEnum';
import { deal_FindGetItemName } from '@/utils/dealFindData';
import { AddEditCustomerGroup, CustomerFilterGroupParams, CustomerSetGroupState } from '@/api/customerfee/CustomerFeeSetModel';
import { CustomerGroupOperateType, Department } from '@/type/BaseBusinessFeeseType';
import { userStore } from '@/store/user';

// TODO 数据来源：props.customerList => 客户列表（'/api/apiData/apiAllCustomerIdsList'）
/**
 * 处理设置分组
 * @param onShow 弹窗显示
 * @param onClose 弹窗显示
 * @param emit 子组件回传参数
 * @param props 父组件参数
 * @returns 
 */
const { resData } = useReturnData()
const { ElMessageBox, createMessage, createConfirm } = useMessage()
export function useAddCustomer(onShow: Fn, onClose: Fn, setLoading: Fn, emit: Fn, props: Recordable, getBindValue: Recordable, isShowOrgIdRules: Ref<boolean>) {
    // 客户分区-选择客户的数据
    const customerState = reactive<CustomerSetGroupState>({
        radioCustomer: 2,
        orgId: undefined,
        groupId: undefined,
        productId: undefined,
        productName: undefined,
        groupName: undefined,
        customerCheckedOptions: [],
        downCustomerKey: undefined,//选择单个客户
        customerIdList: [],//选择多个客户
        customerNameList: [],//分组名称
        checkAllCustomer: false,//全选客户状态
        isCheckAllCustomer: false,//取消全选
        inputCustomerZoning: '',//输入客户，以，分割
        checkCustomerList: [],//显示的复选框
        isGroupName: true,
        isVerifyGroupName: false,
        isVerifyOrgId: false,
        groupLoading: false,
        groupFilter: true,
        isAllProduct: false,
        treeGroupId: undefined,
        isParentFlag: false,
        isLastData: false,
    })
    // 产品列表
    const { productList } = useDropDownData()
    // 分组数据
    const customerGroup = reactive({
        filterGroupIdList: [] as (number | string)[],//当前创建分组的客户id
        groupList: [] as Recordable[],//没处理的已有分组数据
    })
    // 复选框中间状态
    const isIndeterminateCustomer = ref(false)
    // watchEffect(() => {
    //     customerState.orgId = props.orgId
    // })
    // 全部产品的标识
    const isAllProductShow = ref(false)
    // 是否禁用产品名称
    const getIsSingleProduct = computed(() => {
        if (customerState.productId && customerState.isAllProduct) return false
        return customerState.isAllProduct
    })
    // 是否禁用全部产品复选框
    const getIsAllProduct = computed(() => {
        return !!customerState.productId && isStrings(customerState.productId)
    })
    // 客户列表
    const customerList = computed<ListIitem[]>(() => props.customerList)
    watch(() => customerList.value, () => {
        updateCurrentCustomerList()
    })
    const currentCustomerList = ref<ListIitem[]>([])
    // change过滤分组客户
    const changeGroupFilter = () => {
        updateCurrentCustomerList()
    }
    // 更新过滤已有分组客户
    const updateCurrentCustomerList = async () => {
        const list = unref(customerList)
        if(
            isArrayLength(customerGroup.filterGroupIdList) 
            && isArrayLength(list)
            && customerState.groupFilter
        ) {
            currentCustomerList.value = list.filter((item) => 
                !customerGroup.filterGroupIdList.some((key) => key == Number(item.value))
            )
        } else {
            currentCustomerList.value = list
        }
    }
    const userstore = userStore()
    const getSysUserRoleDto = computed(() => userstore.sysUserRoleDto)
    const getDeptCodeList = computed(() => userstore.deptCodeList)
    const orgselectList = computed<ListIitem[]>(() => props.orgSelectList)
    // 初始化角色获取分公司
    const initRoleOrgData = async () => {
        await nextTick()
        await nextTick()
        if (unref(getSysUserRoleDto).roleId === Department.SELL) {
            const newOrgList = unref(orgselectList).filter(item => unref(getDeptCodeList).includes(String(item.value)))
            if (isArrayLength(newOrgList)) {
                customerState.orgId = String(newOrgList[0].value)
            }
        }
    }
    // 查询现有的分组数据
    const getCustomerFilterGroup = async (params: CustomerFilterGroupParams) => {
        // 产品编号、全部产品标识
        const isResult = !params.productId ? (customerState.isAllProduct ? true : false) : true
        if (!isResult) return
        const res = await customerFilterGroup(params)
        if(resCodeSuccess(res)) {
            const filterGroupIdList: number[] = []
            const groupList = res.data
            customerGroup.groupList = res.data
            for (const item of groupList) {
                if(isArrayLength(item.customerIdList)) {
                    filterGroupIdList.push(...item.customerIdList) 
                }
            }
            customerGroup.filterGroupIdList = [...new Set(filterGroupIdList)]
            await updateCurrentCustomerList()
        }
    }
    // 选择产品刷新现有分组客户过滤
    const onChangeProductId = (val: string) => {
        customerState.customerIdList = []
        customerState.isAllProduct = false
        customerState.productName = deal_FindGetItemName(val, unref(productList))
        isStrings(customerState.productId) && getCustomerFilterGroup({ 
            orgId: customerState.orgId, 
            productId: customerState.productId, 
            treeGroupId: customerState.treeGroupId,
            isParentFlag: customerState.isParentFlag,
        })
        changeIsVerifyProductId()
    }
    // 刷新分公司校验
    const changeCustomerOrgId = () => {
        if (unref(isShowOrgIdRules)) {
            !customerState.orgId ? customerState.isVerifyOrgId = true : customerState.isVerifyOrgId = false
        }
    }
    // 判断当前创建或编辑分组客户已存在其它分组里
    const isCustomerIncludeGroup = async () => {
        if(isArrayLength(customerGroup.groupList)) {
            const infoGroupList: Recordable[] = []
            for (const item of customerGroup.groupList) {
                if(isArrayLength(item.customerIdList)) {
                    const filterList = item.customerIdList.filter((key1: any) => 
                        customerState.customerIdList.some(key2 => key1 == key2)
                    )
                    if(isArrayLength(filterList)) {
                        infoGroupList.push({
                            customerGroupVersion: item.customerGroupVersion,
                            groupName: item.groupName,
                            customerIdList: filterList
                        })
                    }
                }
            }
            const list = unref(customerList)
            const infoNameGroupList = infoGroupList.map((item) => {
                if(isArrayLength(item.customerIdList)) {
                    item.customerNameList = list.filter(
                        (i) => item.customerIdList.some(j => j == i.value)
                    )
                }
                return item
            })
            if(isArrayLength(infoNameGroupList)) {
                ElMessageBox({
                    title: '提示',
                    message: h('div', {
                        style: "line-height: 1.6; wdith: "
                    }, [
                        h('div', '当前所选客户与以下分组重叠，具体如下:'),
                        infoNameGroupList.map(item => h('div', [
                            h('p', `${item.groupName}_${item.customerGroupVersion}（重叠客户）:`),
                            isArrayLength(item.customerNameList) && item.customerNameList.map(
                                (info,index) => h('span', {
                                    style: 'color: #E6A23C;'
                                },
                                `
                                    ${info.label}${index != (item.customerNameList.length - 1) ? '，' : ''}
                                `),
                            ),
                        ]))
                    ]),
                    showCancelButton: false,
                    showConfirmButton: false,
                    customClass: 'info-customername-warp',
                })
            }
            return isArrayLength(infoGroupList)
        }
        return false
    }
    // 用于复选框展示客户
    const checkCustomerList = computed(() => {
        // 排序
        const customerList = alphabeticalOrder(currentCustomerList.value)
        return customerList && dealCountryList(customerList)
    })
    // 根据角色是否分公司校验
    const isOrgIdVerify = computed(() => unref(isShowOrgIdRules) && customerState.isVerifyOrgId)
    // 产品编号校验
    const changeIsVerifyProductId = () => {
        // 如果选择全部产品标识取消校验
        if (unref(getIsSingleProduct)) {
            customerState.isVerifyProductId = false
        } else {
            // 产品名称
            !customerState.productId ?
                (customerState.isVerifyProductId = true) : 
                (customerState.isVerifyProductId = false);
        }
    }
    // 自定义校验
    const hanleChangeIsVerify = () => {
        // 分组名称
        !customerState.groupName ?
            (customerState.isVerifyGroupName = true) : 
            (customerState.isVerifyGroupName = false);
        changeIsVerifyProductId()
        changeCustomerOrgId()
    }
    // 处理客户列表数据为复选框显示
    watch(() => checkCustomerList.value, (val) => {
        customerState.checkCustomerList = val
    })
    // 全选
    const handleCheckAllChange = () => {
        customerState.customerIdList = unref(currentCustomerList).map(item => item.value) as string[]
        customerState.isCheckAllCustomer = false
        customerState.checkAllCustomer = true
        customerState.downCustomerKey = undefined
        isIndeterminateCustomer.value = false
    }
    // 取消全选
    const handleIsCheckAllChange = () => {
        customerState.customerIdList = []
        customerState.checkAllCustomer = false
        customerState.isCheckAllCustomer = true
        customerState.downCustomerKey = undefined
        isIndeterminateCustomer.value = false
    }

    // 生成已选客户
    const getCustomerChoice = computed(() => {
        // 如果只选择单个数据
        if (customerState.downCustomerKey) {
            customerState.customerIdList[0] !== customerState.downCustomerKey ? customerState.customerIdList = [customerState.downCustomerKey as string] : null
        }
        if (customerState.customerIdList.length === 0) return
        // let strCustomer = "";
        const filteredCustomerList = unref(currentCustomerList).filter(item => customerState.customerIdList.some(key => item.value == key));
        // value关联的内容
        customerState.customerCheckedOptions = cloneDeep(filteredCustomerList)
        // 分组名称
        customerState.customerNameList = filteredCustomerList.map(item => item.label)
        // 并接成指定字符串
        // strCustomer = customerState.customerNameList.join(',')
        return customerState.customerNameList;
    })

    // 回车分割匹配客户
    const hanleEnterCustomer = () => {
        if (!customerState.inputCustomerZoning) return
        // 分割的客户字符串
        const customerStrList = customerState.inputCustomerZoning.split(/[，,]/)
        // 过滤的客户列表数据
        const cloneCustomerList = cloneDeep(unref(currentCustomerList))
        // const filteredCustomerList = cloneCustomerList.filter((item: ListIitem) => customerStrList.some(keyword => item.label.indexOf(keyword) !== -1)) as ListIitem[];
        //按照关键字  
        const filteredCountryList = cloneCustomerList.filter((item) => {
            const { label } = item;
            const textKeyword = isStrings(label) && label.replace(/\s/g, "")
            return customerStrList.some(keyword => {
                return textKeyword && textKeyword === keyword
            });
        });
        // 匹配勾选到客户
        const checkboxList: string[] = filteredCountryList.map((item) => item.value)
        if(isArrayLength(checkboxList)) {
            customerState.customerIdList = [...customerState.customerIdList, ...checkboxList]
        }
        // const newList = alphabeticalOrder(filteredCountryList)
        // customerState.checkCustomerList = dealCountryList(newList)
    }

    // 获取已选客户数据:key,value
    const hanleCustomerChoice = () => customerState.customerCheckedOptions;

    // 清除选中的客户信息
    const clearOnClose = () => {
        customerState.customerIdList = []
        customerState.customerCheckedOptions = []
        customerState.isCheckAllCustomer = false
        customerState.checkAllCustomer = false
        customerState.groupFilter = true
        customerState.isGroupName = true
        customerState.downCustomerKey = undefined
        customerState.groupName = undefined
        customerState.groupId = undefined
        customerState.treeGroupId = undefined
        customerState.isParentFlag = false
        customerState.radioCustomer = 2
        customerState.inputCustomerZoning = ''
        customerState.isVerifyGroupName = false
        customerState.isVerifyProductId = false
        customerState.isVerifyOrgId = false
        customerState.isAllProduct = false
        isAllProductShow.value = false
        setLoading(false)
        onClose()
    }

    // 查询分组所属的客户
    const initCustomerGroupList = async (id): Promise<string[]> => {
        if (!id) return []
        // 查询分组所属的客户
        const res = await getcustomerGroupListApi({ id })
        const list = resData(res)
        if (!isArrayLength(list)) return []
        const customerIdList = list[0].customerIdList
        const resultArr = customerIdList.map(item => String(item))
        return resultArr
    }
    // 判断是否外部新增
    const isExternalAdmin = ref(false)
    const getExternalAdmin = computed(() => isExternalAdmin.value)
    /**
     * 弹窗操作
     * @param row 接收数据参数
     * @param type 当前编辑/新增状态
     * @param isAdmin 是否在分组管理显示
     */
    const show = async (row: Recordable, type: string, isAdmin = false) => {
        initRoleOrgData()
        isExternalAdmin.value = isAdmin
        getBindValue.title = type === EditTypeState.ADD ? '新增分组' : '编辑分组'
        // 选择分组内容
        if (row) {
            customerState.isLastData = !!row.isLastData
            customerState.productName = row.productName
            customerState.orgId = row.orgId
            customerState.groupName = row.groupName
            customerState.groupId = row.groupId
            customerState.treeGroupId = row.treeGroupId
            customerState.isParentFlag = row.isParentFlag
            customerState.productId = row.productId
            isAllProductShow.value = row.isAllProduct
            customerState.isAllProduct = row.isAllProduct ? row.isAllProduct : false
            await getCustomerFilterGroup({ 
                productId: row.productId, 
                id: row.groupId, 
                treeGroupId: row.treeGroupId, 
                isParentFlag: row.isParentFlag, 
                orgId: row.orgId
            })
            if(isArrayLength(row.customerIdList)) {
                unref(currentCustomerList).forEach((item) => {
                    if(row.customerIdList.some((value) => item.value === value)) {
                        item.value && customerState.customerIdList.push(String(item.value))
                    }
                })
            }
            changeCheckCustomerIdList(customerState.customerIdList)
        }
        onShow()
    }
    const confirm = async () => {
        hanleChangeIsVerify()
        if (customerState.isVerifyGroupName || customerState.isVerifyProductId || unref(isOrgIdVerify)) return
        // 判断是否当前分组是否包含其它分组的客户
        const isGroup = await isCustomerIncludeGroup()
        if(isGroup) return
        if(!isArrayLength(customerState.customerIdList)) {
            createMessage.warning('分组的客户不能为空！')
            return
        }
        // 是否最新数据
        if(!customerState.isLastData && customerState.groupId) {
            createMessage.warning('非最新记录不能再次修改！')
            return
        }
        // 请求开始
        setLoading(true)
        const customer_state = {
            customerNameList: getCustomerChoice.value,
            groupId: customerState.groupId
        }
        const customerGroupData = {
            id: !customerState.groupId ? undefined : customerState.groupId,
            orgId: customerState.orgId,
            productId: customerState.productId,
            productName: customerState.productName,
            isAllProduct: customerState.isAllProduct,
            treeGroupId: customerState.treeGroupId,
            isParentFlag: customerState.isParentFlag,
            groupName: customerState.groupName,
            customerIdList: customerState.customerIdList,
            customerNameList: getCustomerChoice.value,
        }
        // console.log(customerGroupData, ":分组添加或编辑",customer_state);
        // 分组编号存在时的操作
        if (customerGroupData.id) {
            // 获取分组客户操作类型
            const groupOperateTypeRes = await api_checkCustomerGroupOperateType({ id: customerGroupData.id, customerIdList: customerState.customerIdList.map(Number) })
            if (groupOperateTypeRes.code !== 200) return false
            const customerGroupOperateType = groupOperateTypeRes.data
            const customerGroupParams = { ...customerGroupData, customerGroupOperateType }
            switch (customerGroupOperateType) {
                case CustomerGroupOperateType.ADD:
                    emit('saveFeesetCustomer', customer_state, customerGroupParams, clearOnClose, setLoading)
                    break;
                case CustomerGroupOperateType.DELETE:
                    emit('saveFeesetCustomer', customer_state, customerGroupParams, clearOnClose, setLoading)
                    break;
                case CustomerGroupOperateType.MODIFY:
                    const checkRes = await api_checkFeeSetGroup(customerGroupParams as unknown as AddEditCustomerGroup)
                    if (checkRes.code === 200 && checkRes.data) {
                        createConfirm({
                            type: "warning",
                            customClass: 'define-checkcustomer',
                            title: "系统提示",
                            message: h('div', { style: 'max-height: 81vh;overflow: auto;' }, [
                                h('p', `${customerState.groupName}分组对应的客户费用:`),
                                h('p', { style: 'color: #ff0000;padding: 5px 0;' }, checkRes.data),
                                h('p', '编辑分组将添加新分组版本，您确定是否要修改分组？')
                            ]),
                            cancelButtonText: "取消",
                            confirmButtonText: "确定",
                            dangerouslyUseHTMLString: true,
                            beforeClose: (action, instance, done) => {
                                if (action === "confirm") {
                                    emit('saveFeesetCustomer', customer_state, customerGroupParams, clearOnClose, setLoading)
                                }
                                setLoading(false)
                                done()
                            },
                        })
                    } else {
                        emit('saveFeesetCustomer', customer_state, customerGroupParams, clearOnClose, setLoading)
                    }
                    break;
                default:
                    createMessage.error('操作类型缺失！')
                    break;
            }
            return false
        }
        // 判断是全部产品标识才提示
        if (unref(isAllProductShow) || customerState.isAllProduct) {
            createConfirm({
                type: "warning",
                title: '系统提示',
                message: "该分组对所有线路都生效，您确定要修改？",
                cancelButtonText: "取消",
                confirmButtonText: "确定",
                beforeClose: (action, instance, done) => {
                    if (action === "confirm") {
                        emit('saveFeesetCustomer', customer_state, customerGroupData, clearOnClose, setLoading)
                    }
                    setLoading(false)
                    done()
                },
            })
            return
        }
        emit('saveFeesetCustomer', customer_state, customerGroupData, clearOnClose, setLoading)
    }
    // 分组事件
    const hanleChangeGroup = async (id) => {
        if (!id) return
        customerState.groupLoading = true
        customerState.customerIdList = await initCustomerGroupList(id)
        customerState.groupLoading = false
    }
    // 选中的CustomerIdList
    const changeCheckCustomerIdList = (value: string[]) => {
        const customerList_ = unref(currentCustomerList)
        const checkedCount = value.length
        const customerListCount = isArrayLength(customerList_) ? customerList_.length : 0
        if(checkedCount > 0 && checkedCount < customerListCount) {
            isIndeterminateCustomer.value = true
            customerState.isCheckAllCustomer = false
        } else {
            isIndeterminateCustomer.value = false
        }
    }
    // 勾选全部产品
    const changeAllProduct = (isAllProduct: boolean) => {
        customerState.productId = undefined
        customerState.customerIdList = []
        if (isAllProduct) {
            getCustomerFilterGroup({ 
                treeGroupId: customerState.treeGroupId, 
                isParentFlag: customerState.isParentFlag,
                orgId: customerState.orgId,
            })
        } else {
            isStrings(customerState.groupId) && getCustomerFilterGroup({ 
                id: customerState.groupId, 
                treeGroupId: customerState.treeGroupId,
                isParentFlag: customerState.isParentFlag,
                orgId: customerState.orgId,
            })
        }
        changeIsVerifyProductId()
    }
   
    return {
        handleCheckAllChange,
        handleIsCheckAllChange,
        hanleCustomerChoice,
        clearOnClose,
        hanleEnterCustomer,
        confirm,
        show,
        getCustomerChoice,
        customerState,
        checkCustomerList,
        hanleChangeGroup,
        changeCheckCustomerIdList,
        isIndeterminateCustomer,
        productList,
        getExternalAdmin,
        onChangeProductId,
        changeCustomerOrgId,
        changeGroupFilter,
        isAllProductShow,
        getIsSingleProduct,
        getIsAllProduct,
        changeAllProduct
    }
}