import { AddEditCustomerGroup, SubmitCustomerFeeSetModel } from "@/api/customerfee/CustomerFeeSetModel"
import { EditType, EditTypeState, RecalculateType, Title } from "@/type/BaseEnum";
import { DialogModel } from "@/type/BastType"
import { reactive, ref, unref, computed, nextTick, watch, h } from "vue";
import type { FormInstance } from 'element-plus'
import { useDropDownData } from "@/hooks/useDropDownData";
import { ListIitem } from "@/api/base/BaseDataModel";
import { api_checkCustomerGroup, api_deleteCustomerGroup, customerGroupAddApi, customerGroupEditApi, getcustomerGroupListApi } from "@/api/customerfee/customerfeeset";
import { useReturnData } from "@/utils/useReturnData";
import { cloneDeep } from "@/utils/cloneDeep";
import { formatDateTime } from "@/utils/dateFormate";
import { clearData } from "@/utils/clearData";
import { isArrayLength } from "@/utils/is";
import { useEleFormValidate } from "@/hooks/useEleFormValidate";
import { useMessage } from "@/hooks/useMessage";
import { deal_FindGetItemName } from "@/utils/dealFindData";
import { Department, FeeApprovalStatus, FeeSetAddType, GroupOperateType } from "@/type/BaseBusinessFeeseType";
import { userStore } from "@/store/user";

const { createMessage, createConfirm } = useMessage()
/**
 * 新增费用设置
 * @param dialog 
 * @param onClose 
 * @param onShow 
 * @param setLoading 
 * @param emit 
 * @param props 
 * @returns 
 */
export default function useAddCustomerFeeSet(dialog: DialogModel, onClose: Fn, onShow: Fn, setLoading: Fn, emit: Fn, props: Recordable) {
    const { countryList } = useDropDownData()
    //获取全局属性
    // const { global } = useInstance()
    //表单ref属性
    const addCustomerFeeSetForm = ref<FormInstance>()
    //表单绑定的数据
    const addModel = reactive<SubmitCustomerFeeSetModel>({
        id: '',
        productId: '',
        productName: '',
        feeSetName: '',
        groupId: '',
        groupName: '',
        orgId: '',
        orgName: '',
        customerId: '',
        customerName: '',
        feeSetType: 0,
        beginDate: "",
        endDate: undefined,
        isLast: false,
        remark: '',
        activeFlag: false,
        createUserId: 0,
        createTime: '',
        updateUserId: 0,
        updateTime: '',
        feeBasicData: null,
        feeItemComputeList: [],
        feeItemComputeDetailsList: [],
        partitionList: [],
        parentId: '',
        type: '',
        customerIdList: [],
        customerNameList: [],
        recalculate: 0,
        originalId: '',
        recommendFeeSet: null,
        feeApprovalStatus: FeeApprovalStatus.NO_APPROVAL,
        feeSetAddType: FeeSetAddType.ADD
    })
    const addModelState = reactive({
        groupLoading: false,//分组加载数据
        filterGroupList: [],//查询原有的分组客户
        currentOrgId: '',//当前分组分公司
        checkLoading: false,
        isAllProduct: false,//全部产品的标识
        treeGroupId: undefined,//同一目录树分组编号
        isParentFlag: false,//是否父分组
        groupOperateType: GroupOperateType.ADD_FEE,
        isLastData: false,//分组是否最新数据
    })
    // 起始时间与结束时间
    const beginAndEndDateArr = ref<Recordable[]>([])
    // 是否禁用
    const isDisabled = computed(() => {
        return addModel.type === EditType.VERSION || addModel.type === EditType.RECALCULATE || unref(isActiveFlagStatus)
    })
    // 判断是否可以删除分组
    const isDeleteCustomer = computed(() => {
        return unref(isDisabled) || !addModel.groupId
    })
    // 编辑状态
    const isEditStatus = computed(() => {
        return addModel.type === EditType.EDIT
    })
    // 已激活状态不能编辑
    const isActiveFlagStatus = computed(() => {
        return addModel.activeFlag && addModel.type === EditType.EDIT
    })
    // 是否重算
    const isRecalculate = computed(() => {
        return addModel.recalculate === RecalculateType.YES
    })
    // 是否分组超长省略
    const isCustomerIdList = computed(() => !isArrayLength(addModel.customerIdList))
    const getFeeSetTypeSelectList = computed<ListIitem[]>(() => props.feeSetTypeSelectList)
    // 获取业务人员的费用类型的默认值
    const feeSetTypeDefault = computed(() => {
        const list = unref(getFeeSetTypeSelectList)
        if(list && list.length === 1) return list[0].value as number
        return 0
    })
    // 判断费用类型是否为客户价
    const getIsShowFeeSetType = computed(() => {
        const feeSetType = unref(getFeeSetTypeSelectList).find((item) => item.value === addModel.feeSetType)
        if(!feeSetType) return false
        return feeSetType.label === "客户价"
    })
  
    const { resData } = useReturnData()
    const { validateFieldForm } = useEleFormValidate()
    // 客户弹窗
    const refAddCustomerFeeSet = ref<{ show: Fn }>()
    // 打开新增或编辑分组设置
    const hanleFocusCustomer = async () => {
        // 判断是否有分组名
        const type = addModel.groupId ? EditTypeState.EDIT : EditTypeState.ADD
        // 判断产品编号不能为空 ==》 分组参数必填
        const isProductId = await validateFieldForm(addCustomerFeeSetForm.value, ["productId"])
        if(!isProductId) return
        // 分组不存在时不能进入分组设置
        if(!unref(getIsShowFeeSetType)) return
        const group = cloneDeep(addModel)
        if(!group.productId) {
            return
        }
        const orgId = addModelState.currentOrgId ? addModelState.currentOrgId : addModel.orgId
        unref(refAddCustomerFeeSet)?.show({ 
            ...group, 
            orgId, 
            isAllProduct: addModelState.isAllProduct,
            treeGroupId: addModelState.treeGroupId,
            isParentFlag: addModelState.isParentFlag,
            isLastData: addModelState.isLastData,
        }, type)
    }
    // 建议价change事件
    const changeRecommendFeeSet = (val) => {
        val ? addModel.recommendFeeSet = val : addModel.recommendFeeSet = null
    }
    // 费用类型的change事件
    const changeFeeSetType = (val) => {
        addModel.feeSetTypeName = deal_FindGetItemName(val, unref(getFeeSetTypeSelectList))
        // 如果不是客户价清除对应分组信息
        !unref(getIsShowFeeSetType) ? 
            clearGroup() : changeSelect(addModel.orgId, addModel.productId)
    }
    
    // 重算设置
    const changeBeginAndEndDate = (dateArr: Recordable[]) => {
        if (isArrayLength(dateArr)) {
            addModel.beginDate = formatDateTime(dateArr[0])
            addModel.endDate = formatDateTime(dateArr[1])
        } else {
            addModel.beginDate = ""
            addModel.endDate = ""
        }
    }
    //确定
    const confirm = () => {
        // console.log(addModel);
        // 判断单个客户与分组只能设置其中一种
        if(addModel.customerIdList && addModel.customerIdList.length > 0 && Number(addModel.customerId) > 0) {
            createMessage.warning('客户与分组不能同时设置！')
            return
        }
        // 生效时间处理
        if (addModel.beginDate && !isArrayLength(unref(beginAndEndDateArr))) {
            addModel.beginDate = formatDateTime(addModel.beginDate)
        }
        if (!addModel.orgId) addModel.orgName = ''
        //表单验证
        addCustomerFeeSetForm.value?.validate(valid => {
            if (valid) {
                setLoading(true)
                addModel.productName = deal_FindGetItemName(addModel.productId, unref(getProductSelectList))
                emit('save', addModel, clearClose, setLoading)
                // clearClose()
            }
        })
    }
    // 删除当前分组
    const getDeleteCustomerGroup = async () => {
        const res = await api_deleteCustomerGroup({ id: addModel.groupId })
        const deleteCode = resData(res, "删除成功")
        if (deleteCode !== 500) {
            addModel.groupId = ''
            addModel.groupName = ''
            addModel.customerIdList = []
            addModel.customerNameList = []
            changeSelect(addModel.orgId, addModel.productId)
        }
    }
    // 删除分组
    const hanleDeleteCustomer = async () => {
        try {
            addModelState.checkLoading = true
            // const res = await api_checkCustomerGroup({ id: addModel.groupId })
            // 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()
            //             }
            //             done()
            //         },
            //     })
            //     return false
            // }
            // 删除
            getDeleteCustomerGroup()
        } finally {
            addModelState.checkLoading = false
        }
    }

    // 取消
    const clearClose = () => {
        const data = clearData(addModel)
        Object.assign(addModel, data)
        addModel.recalculate = 0
        addModel.feeApprovalStatus = FeeApprovalStatus.NO_APPROVAL
        addModelState.currentOrgId = ''
        beginAndEndDateArr.value = []
        // console.log(data, "addModel <== 取消");
        onClose();
    }

    //显示弹框 type : 0 和 1
    const show = (type: string, row: SubmitCustomerFeeSetModel) => {
        //设置弹框的高度
        dialog.height = 210;
        unref(getIsShowFeeSetType) && changeSelect(addModel.orgId, addModel.productId)
        //设置弹框的标题
        switch (type) {
            case EditType.ADD:
                dialog.title = Title.ADD
                addModelState.groupOperateType = GroupOperateType.ADD_FEE
                break;
            case EditType.EDIT:
                dialog.title = Title.EDIT
                addModelState.groupOperateType = GroupOperateType.EDIT_FEE
                break;
            case EditType.VERSION:
                addModelState.groupOperateType = GroupOperateType.ADD_FEE_VERSION
                dialog.title = Title.VERSION
                break;
            case EditType.RECALCULATE:
                addModelState.groupOperateType = GroupOperateType.RE_COUNT_FEE
                dialog.title = Title.VERSION
                break;
        }
        //显示弹框
        onShow();
        //如果是编辑，复制当前行到表单绑定的数据 
        nextTick(() => {
            // 费用类型默认值
            addModel.feeSetType = unref(feeSetTypeDefault)
            addModel.groupId = undefined  as any
            addModel.recalculate = 0
            if (type == EditType.EDIT) {
                // 赋值分组给即将编辑信息
                // global.$objCoppy(row, addModel)
                Object.assign(addModel, { ...row })
                addModel.beginDate = row.beginDate
            }
            // 新增版本
            if (type === EditType.VERSION) {
                Object.assign(addModel, { ...row })
                // global.$objCoppy(row, addModel)
                addModel.feeApprovalStatus = FeeApprovalStatus.NO_APPROVAL
                addModel.id = ''
                addModel.beginDate = ''
                addModel.originalId = row.id
            }
            // 重算新增版本
            if (type === EditType.RECALCULATE) {
                Object.assign(addModel, { ...row })
                addModel.feeApprovalStatus = FeeApprovalStatus.NO_APPROVAL
                addModel.id = ''
                addModel.beginDate = ''
                addModel.recalculate = 1
                addModel.originalId = row.id
            }
            //设置编辑属性
            addModel.type = type;
            initRoleOrgData()
        })
        //清空表单
        addCustomerFeeSetForm.value?.resetFields();
    }

    //当期日期以后的的时间(暂时失效，待处理)
    const pickerOptions = {
        disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
        }
    };

    //  禁用当日之前的时间
    const disabledDate = (time: Date) => {
        // 一天的时间戳
        const daysTime = 24 * 60 * 60 * 1000
        return time.getTime() < Date.now() - daysTime;
    }
    const userstore = userStore()
    const getSysUserRoleDto = computed(() => userstore.sysUserRoleDto)
    const getDeptCodeList = computed(() => userstore.deptCodeList)
    const orgselectList = computed<ListIitem[]>(() => props.orgSelectList)
    // 初始化角色获取分公司
    const initRoleOrgData = () => {
        if (unref(getSysUserRoleDto).roleId === Department.SELL) {
            const newOrgList = unref(orgselectList).filter(item => unref(getDeptCodeList).includes(String(item.value)))
            if (isArrayLength(newOrgList)) {
                addModel.orgId = String(newOrgList[0].value)
                addModel.orgName = newOrgList[0].label
            }
        }
    }
    // 分公司change事件
    const changeOrgId = (val) => {
        const findObj = unref(orgselectList).find(item => item.value === val)
        unref(getIsShowFeeSetType) && changeSelect(addModel.orgId, addModel.productId)
        findObj ? addModel.orgName = findObj.label : addModel.orgName = ''
        clearGroup()
    }
    // 设置分组操作
    const hanleSaveFeesetCustomer = async (customerState: Recordable, params: AddEditCustomerGroup, onclose: Fn, setLoading: Fn) => {
        debugger
        // addModel.orgId = params.orgId
        // const findObj = unref(orgselectList).find(item => item.value == addModel.orgId)
        // if (findObj) addModel.orgName = findObj.label
        // addModel.groupId = customerState.groupId
        // 设置客户id、客户名称
        if(isArrayLength(addModel.customerIdList)) addModel.customerIdList = params.customerIdList
        if(isArrayLength(addModel.customerNameList)) addModel.customerNameList = customerState.customerNameList
        // if (!customerState.isGroupName) {
        //     setLoading(false)
        //     onclose()
        // }
        // 判断是否导出分组
        if(!addModel.groupId) {
            try {
                // 添加分组
                const res = await customerGroupAddApi(params)
                const resCode = resData(res, "添加成功")
                if (resCode !== 500) {
                    if(res.data) addModel.groupId = res.data
                    // 刷新分组数据
                    await changeSelect(params.orgId, params.productId)
                    onclose()
                }
            } finally {
                setLoading(false)
            }
            return false
        }
        try {
            // 编辑分组
            const res = await customerGroupEditApi(params)
            const resCode = resData(res, "编辑成功")
            if (resCode !== 500) {
                if(res.data) addModel.groupId = res.data
                // 刷新分组数据
                await changeSelect(params.orgId, params.productId)
                onclose()
            }
        } finally {
            setLoading(false)
        }
    }
    // 清除分组信息
    const clearGroup = (isGroupId = true) => {
        addModelState.isLastData = false
        addModelState.isAllProduct = false
        addModelState.currentOrgId = ''
        if(isGroupId) {
            addModel.groupId = undefined as any
            addModel.groupName = undefined  as any
            addModelState.treeGroupId = undefined
            addModelState.isParentFlag = false
        }
        addModel.customerIdList = []
        addModel.customerNameList = []
    }
    // 分公司change事件
    const changeSelect = (orgId?: string, productId?: string | number) => {
        emit("changeSelect", { orgId, productId, groupOperateType: addModelState.groupOperateType, id: addModel.groupId })
    }
    // 点击产品名称
    const hanleChangeProduct = (product: ListIitem) => {
        if (product.label) addModel.productName = product.label
    }
    // 选择change产品名称
    const changeProductId = (value) => {
        clearGroup()
        unref(getIsShowFeeSetType) && changeSelect(addModel.orgId, value)
    }
    // 选择客户名称
    const changeCustomerSelect = (val: string, customerList: ListIitem[]) => {
        // 根据客户编号查找对应名称
        const customerOrg = customerList.find(item => item.value == val)
        customerOrg?.label ? addModel.customerName = customerOrg?.label : addModel.customerName = ''
    }
    // 产品列表
    const getProductSelectList = computed<ListIitem[]>(() => props.productSelectList)
    // 查询分组所属的客户
    const initCustomerGroupList = async (id, isGroupId): Promise<any[]> => {
        if (!id) return []
        // 查询分组所属的客户
        const res = await getcustomerGroupListApi({ id })
        const list = resData(res)
        if (!isArrayLength(list)) {
            clearGroup(isGroupId)
            return []
        }
        const currentCustomer = list[0]
        // 当前客户id列表
        const customerIdList = currentCustomer.customerIdList
        // 分公司编号
        addModelState.currentOrgId = currentCustomer.orgId
        // 全部产品标识
        addModelState.isAllProduct = currentCustomer.isAllProduct ? currentCustomer.isAllProduct : false
        // 同一目录树分组编号
        addModelState.treeGroupId = currentCustomer.treeGroupId
        // 是否父分组
        addModelState.isParentFlag = currentCustomer.isParentFlag
        // 是否最新数据
        addModelState.isLastData = currentCustomer.isLastData
        addModel.groupName = currentCustomer.groupName
        const resultArr = customerIdList.map(item => String(item))
        return resultArr
    }
    const customerList = computed(() => props.customerSelectList || [])
    const groupSelectList = computed(() => props.groupSelectList)
    watch(
        () => groupSelectList.value, 
        (val) => {
        if(isArrayLength(val)) {
            if (addModelState.groupOperateType === GroupOperateType.ADD_FEE_VERSION) addModel.groupId = val[0].value
            hanleChangeGroup(addModel.groupId, true)
        } else {
            clearGroup()
        }
    }, { immediate: true })
    // 分组事件
    const hanleChangeGroup = async (id, isGroupId = false) => {
        addModelState.groupLoading = true
        addModel.customerIdList = await initCustomerGroupList(id, isGroupId)
        addModelState.groupLoading = false
    }
    // 生成已选客户
    const getCustomerArr = computed(() => {
        if (!isArrayLength(addModel.customerIdList) || !isArrayLength(unref(customerList))) {
            return []
        }
        const filteredCustomerList = customerList.value.filter(item => addModel.customerIdList.includes(item.value));
        // 分组名称
        addModel.customerNameList = filteredCustomerList.map(item => item.label)
        // 并接成指定字符串
        return addModel.customerNameList;
    })

    return {
        confirm,
        show,
        clearClose,
        addModel,
        addCustomerFeeSetForm,
        pickerOptions,
        disabledDate,
        countryList,
        refAddCustomerFeeSet,
        isDisabled,
        isDeleteCustomer,
        isEditStatus,
        isActiveFlagStatus,
        beginAndEndDateArr,
        hanleFocusCustomer,
        hanleDeleteCustomer,
        hanleSaveFeesetCustomer,
        changeCustomerSelect,
        hanleChangeProduct,
        changeBeginAndEndDate,
        isCustomerIdList,
        changeOrgId,
        isRecalculate,
        addModelState,
        hanleChangeGroup,
        getCustomerArr,
        clearGroup,
        getIsShowFeeSetType,
        changeFeeSetType,
        changeProductId,
        changeRecommendFeeSet
    }
}