import type { StepProps } from 'element-plus';
import { CustomerFeeApprovalStatusDto } from '@/api/customerFeeApproval/customerFeeApprovalModel';
import { ref, reactive, unref, computed } from 'vue';
import { isArrayLength } from '@/utils/is';
import { FeeApprovalStatus } from '@/type/BaseBusinessFeeseType';
import { api_customerFeeActiveBeforeCheck } from '@/api/customerfee/customerfeeset';
import { resCodeSuccess, useReturnData } from '@/utils/useReturnData';
import { PartialCustomerFeeSetCompareDto } from '@/api/customerfee/CustomerFeeSetModel';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';
import { userStore } from '@/store/user';
import { useMessage } from '@/hooks/useMessage';
import { api_customerFeeAllApproval } from '@/api/customerFeeApproval/customerFeeApproval';
import { deal_repeatedlyArray, getApprovalRecordIdCounts } from '@/utils/dealData';
/**
 * 处理审批流程
 * @returns 
 */
const { resData } = useReturnData()
const { createMessage } = useMessage()
function useApprovalProcedure(onClose: Fn, onShow: Fn, setLoading: Fn, emit: Fn, porps: Recordable) {
    const userstore = userStore()
    // 表单 ref
    const approvalProcedureFormRef = ref()
    // 客户费用提示 ref
    const feeNoticeShowRef = ref<{ show: Fn }>()
    const approvalProcedureState = reactive({
        stepList: [
            { title: '审核人1', description: 'Some description', status: 'finish' },
            { title: '审核人2', description: 'Some description', status: 'wait' },
            { title: '审核人3', description: 'Some description', status: 'wait' }
        ] as StepProps[],
        stepActive: 0,
        customerFeeSetCompareList: [] as PartialCustomerFeeSetCompareDto[],
        rulesForm: {
            feeApprovalStatus: [{ required: true, message: '请选择审批状态', trigger: 'change' },]
        },
        customerFeeApprovalStatusDtoList: [] as CustomerFeeApprovalStatusDto[],
        feeNoticeLoading: false
    })
    // 当前行审核的数据
    const currentRow = ref()
    // 根据审批状态获取步骤状态
    const approvalStatus: Map<FeeApprovalStatus, "" | "success" | "error" | "wait" | "finish" | "process"> = new Map([
        [FeeApprovalStatus.PENDING_APPROVAL, "wait"],
        [FeeApprovalStatus.APPROVAL_FAILED, "error"],
        [FeeApprovalStatus.APPROVAL_BY, "success"],
    ])
    // 用户id
    const userId = computed(() => userstore.userId)
    // 处理审批记录==>二级数组
    const getIsEdit = computed(() => porps.isEdit)
    const dealCustomerFeeApprovalList = computed<Recordable[]>(() => {
        const resRepeatedlyArray = deal_repeatedlyArray(approvalProcedureState.customerFeeApprovalStatusDtoList, 'applyCount', 'orderNumber')
        if (!isArrayLength(resRepeatedlyArray)) return [approvalProcedureState.stepList]
        // 编辑显示最新的审批记录
        if (unref(getIsEdit)) return [resRepeatedlyArray[0]]
        return resRepeatedlyArray
    })
    // 判断是否包含通过与不通过
    const isApprovalFn = (feeApprovalStatus: number) => (feeApprovalStatus === FeeApprovalStatus.APPROVAL_BY || feeApprovalStatus === FeeApprovalStatus.APPROVAL_FAILED)
    // 判断当前审批前面是否是已审批过了
    const isAllFeeApprovalStatus = (sortFeeApprovalList: Recordable, orderNumber: number) => {
        // return true //测试
        let isApproval = false
        if (!isArrayLength(sortFeeApprovalList)) return isApproval
        const currentIndex = sortFeeApprovalList.findIndex((item) => item.orderNumber === orderNumber)
        // 默认第一个开始为true
        if (currentIndex === 0) {
            return !isApprovalFn(sortFeeApprovalList[0].feeApprovalStatus)
        }
        const currentFeeApprovalList = sortFeeApprovalList.slice(0, currentIndex)
        isApproval = currentFeeApprovalList.every((item) => item.feeApprovalStatus === FeeApprovalStatus.APPROVAL_BY)
        return isApproval
    }
    const getStepList = computed(() => {
        const sortFeeApprovalList = unref(dealCustomerFeeApprovalList)
        if (!isArrayLength(sortFeeApprovalList)) return [approvalProcedureState.stepList]
        // 是否进行审批状态
        let isApproval = false
        const transformedArr = sortFeeApprovalList.map((innerArray) =>
            innerArray.map((obj) => {
                const status = approvalStatus.get(obj.feeApprovalStatus)
                // 当前的审批步骤
                isApproval = false
                // 判断当前用户设置对应的步骤状态
                if (unref(userId) == obj.approvalUserId && unref(getIsEdit)) {
                    isApproval = isAllFeeApprovalStatus(innerArray, obj.orderNumber) && !isApprovalFn(obj)
                }
                const approvalIsStatus = unref(userId) == obj.approvalUserId && isApproval ? 'finish' : status
                return {
                    title: obj.approvalUserName,
                    description: obj.remark,
                    createTime: obj.createTime,
                    applyCount: obj.applyCount,
                    approvalTime: obj.approvalTime,
                    feeApprovalStatusName: obj.feeApprovalStatusName,
                    status: approvalIsStatus,
                }
            })
        );
        return transformedArr
    })
    // 获取当前的审批信息
    const getCustomerFeeApprovalStatusDto = computed<CustomerFeeApprovalStatusDto>(() => {
        const customerFeeApprovalStatusDtoList = unref(dealCustomerFeeApprovalList)
        const currentCustomerFeeApproval = customerFeeApprovalStatusDtoList[0].find((item) => {
            return item.approvalUserId == unref(userId)
        })
        return (currentCustomerFeeApproval || {}) as CustomerFeeApprovalStatusDto
    })
    // 如果通过与不通过是否显示保存按钮
    const isApprovalStatus = computed(() => {
        const dto = unref(getCustomerFeeApprovalStatusDto)
        if (!dto.orderNumber) return false
        const customerFeeApprovalStatusDtoList = unref(dealCustomerFeeApprovalList)
        const isApproval = isAllFeeApprovalStatus(customerFeeApprovalStatusDtoList[0], dto.orderNumber)
        return isApproval && dto.feeApprovalStatus && !isApprovalFn(dto.feeApprovalStatus)
    })
    // 判断获取的数据
    const isApprovalStatusDtoList = computed(() => {
        const customerFeeApprovalStatusDtoList = approvalProcedureState.customerFeeApprovalStatusDtoList
        return isArrayLength(customerFeeApprovalStatusDtoList)
    })
    // 计算弹窗宽度
    const getSysDialogWidth = computed(() => {
        const customerFeeApprovalStatusDtoList = approvalProcedureState.customerFeeApprovalStatusDtoList
        if(isArrayLength(customerFeeApprovalStatusDtoList)) {
            const approvalNum = getApprovalRecordIdCounts(customerFeeApprovalStatusDtoList)
            if (approvalNum <= 2) return 820
            const approvalWidth = approvalNum * 330
            // 最小宽度
            return approvalWidth < 1080 ? 1160 : approvalWidth
        }
        return 820
    })
    // 参数
    const approvalProcedureparams = reactive<CustomerFeeApprovalStatusDto>({
        approvalRecordId: undefined,
        approvalUserId: undefined,
        approvalUserName: undefined,
        orderNumber: undefined,
        feeApprovalStatus: undefined,
        remark: ''
    })
    // 备注校验
    const remarkRules = computed(() => {
        if (approvalProcedureparams.feeApprovalStatus == FeeApprovalStatus.APPROVAL_FAILED) {
            return [{ required: true, message: '请输入备注', trigger: 'blur' }]
        } else {
            return [{ required: false, message: '请输入备注', trigger: 'blur' }]
        }
    })
    // 费用提示
    const onFeeNoticeShow = async () => {
        approvalProcedureState.feeNoticeLoading = true
        const row = unref(currentRow)
        try {
            // 激活费用对比明细弹窗
            const resBeforeCheck = await api_customerFeeActiveBeforeCheck({
                id: row.feeId,
                productId: row.productId,
                beginDate: row.beginDate,
                endDate: row.endDate
            })
            if (resBeforeCheck.code == 500) {
                createMessage.warning('暂无比对结果数据！')
                return
            }
            const beforeCheckData = resData(resBeforeCheck)
            if (beforeCheckData !== 500 && isArrayLength(beforeCheckData)) {
                unref(feeNoticeShowRef)?.show(row)
                approvalProcedureState.customerFeeSetCompareList = beforeCheckData || []
            } else {
                createMessage.warning('暂无比对结果数据！')
            }
        } finally {
            approvalProcedureState.feeNoticeLoading = false
        }
    }
    // 显示、隐藏
    const { formValidate, resetForm } = useEleFormValidate()
    const onclose = () => {
        resetForm(unref(approvalProcedureFormRef))
        onClose()
    }
    const initData = async (feeId: string) => {
        if (!feeId) return
        const res = await api_customerFeeAllApproval({ feeId })
        if (resCodeSuccess(res)) {
            approvalProcedureState.customerFeeApprovalStatusDtoList = res.data
        }
    }
    const show = (data: Recordable) => {
        currentRow.value = data
        initData(data.feeId)
        onShow()
    }
    const onconfirm = async () => {
        const isValidate = await formValidate(unref(approvalProcedureFormRef));
        if (!isValidate) return;
        setLoading(true)
        const params: CustomerFeeApprovalStatusDto = {
            ...unref(getCustomerFeeApprovalStatusDto),
            feeApprovalStatus: approvalProcedureparams.feeApprovalStatus,
            remark: approvalProcedureparams.remark,
        }
        emit('confirmApproval', params, onclose, setLoading)
    }

    return {
        show,
        onclose,
        onconfirm,
        approvalProcedureState,
        approvalProcedureparams,
        feeNoticeShowRef,
        approvalProcedureFormRef,
        onFeeNoticeShow,
        getStepList,
        isApprovalStatus,
        isApprovalStatusDtoList,
        getSysDialogWidth,
        remarkRules
    }
}

export {
    useApprovalProcedure
}