import type { SubmitCustomerFeeSetModel } from "@/api/customerfee/CustomerFeeSetModel"
import { ListIitem } from "@/api/base/BaseDataModel";
import { useEleFormValidate } from "@/hooks/useEleFormValidate";
import { ref, reactive, computed, Ref, unref } from "vue";
import { Department, FeeApprovalStatus, FeeSetAddType, FeeSetType } from "@/type/BaseBusinessFeeseType";
import { userStore } from "@/store/user";
import { isArrayLength } from "@/utils/is";
import { EditType } from "@/type/BaseEnum";

function useCustomerFeeSetBaseModel() {
    //表单验证
    const rules = reactive({
        productId: [{
            required: true,
            message: '请选择产品',
            trigger: 'change'
        }
        ],
        feeSetName: [
            { required: true, message: '请填写费用名称', trigger: 'change' }
        ],
        feeSetType: [{
            required: true,
            message: '请选择费用类型',
            trigger: 'change'
        }
        ],
        beginDate: [
            { required: true, message: '请选择日期', trigger: 'change' }
        ]
    });
    //表单数据
    const dialogModel = reactive<SubmitCustomerFeeSetModel>({
        id: '',
        productId: '',
        productName: '',
        feeSetName: '',
        groupId: '',
        orgId: '',
        orgName: '',
        customerId: '',
        groupName: '',
        customerName: '',
        feeSetType: 0,
        beginDate: "",
        endDate: undefined,
        isLast: false,
        remark: '',
        activeFlag: false,
        createUserId: 0,
        createTime: '',
        updateUserId: 0,
        updateTime: '',
        feeBasicData: '',
        feeItemComputeList: [],
        feeItemComputeDetailsList: [],
        partitionList: [],
        parentId: '',
        type: "0",
        customerIdList: [],
        customerNameList: [],
        recalculate: 0,
        originalId: '',
        recommendFeeSet: false,
        feeApprovalStatus: FeeApprovalStatus.NO_APPROVAL,
        feeSetAddType: FeeSetAddType.ADD
    })

    return {
        rules,
        dialogModel
    }
}

/**
 * 分公司判断校验
 * @returns 
 */
function useCustomerOrgInfo(props) {
    const userstore = userStore()
    const getSysUserRoleDto = computed(() => userstore.sysUserRoleDto)
    const getDeptCodeList = computed(() => userstore.deptCodeList)
    const orgIdRules = ref<Recordable[]>([])
    const customerFormRules = reactive({
        orgId: [{ required: true, message: '请选择分组', trigger: 'change' }],
        isOrgId: [{ required: false, message: '请选择分组', trigger: 'change' }],
    })
    // 过滤当前分公司
    const getOrgSelectList = computed(() => {
        const orgList = props.orgSelectList as ListIitem[]
        if (unref(getSysUserRoleDto).roleId === Department.SELL) {
            const newOrgList = orgList.filter(item => unref(getDeptCodeList).includes(String(item.value)))
            orgIdRules.value = customerFormRules.orgId
            return newOrgList
        }
        orgIdRules.value = customerFormRules.isOrgId
        return orgList || []
    })
    // 分组根据业务员或渠道部是否校验分公司
    const isShowOrgIdRules = computed(() => {
        const rulesList = orgIdRules.value
        return isArrayLength(rulesList) && rulesList[0].required
    })

    return {
        getOrgSelectList,
        orgIdRules,
        isShowOrgIdRules
    }
}

/**
 * 交叉校验客户与客户分组
 * @param formModel 表单数据
 * @param formModelRef 表单ref
 * @returns 
 */
function useChangeCustomerRules(formModel: SubmitCustomerFeeSetModel, formModelRef: Ref) {
    const userstore = userStore()
    const isSell = computed(() => {
        return userstore.sysUserRoleDto.roleId === Department.SELL
    })
    const isChannel = computed(() => {
        return userstore.sysUserRoleDto.roleId === Department.CHANNEL
    })
    const customerFormRules = reactive({
        customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
        groupId: [{ required: true, message: '请选择分组', trigger: 'change' }],
        recommendFeeSet: [{ required: true, message: '请勾选建议价', trigger: 'change' }],
        isCustomerId: [{ required: false, message: '请选择客户', trigger: 'change' }],
        isGroupId: [{ required: false, message: '请选择分组', trigger: 'change' }],
        isRecommendFeeSet: [{ required: false, message: '请勾选建议价', trigger: 'change' }],
    })
    const { clearValidateForm } = useEleFormValidate();
    //客户校验-关联客户分组
    const customerIdRules = computed({
        get: () => {
            if (formModel.groupId) {
                clearValidateForm(formModelRef.value, ['customerId'])
                return customerFormRules.isCustomerId
            } else {
                // 判断客户价且是销售部门人员及不是渠道部人员
                const isFlag = formModel.feeSetType === FeeSetType.CUSTOMER && unref(isSell) && !unref(isChannel)
                isFlag && (groupIdRules.value = customerFormRules.groupId)
                return isFlag ? customerFormRules.customerId : customerFormRules.isCustomerId
            }
        },
        set: (val) => {
            customerFormRules.customerId = val
        }
    })
    //客户分组校验-关联客户
    const groupIdRules = computed({
        get: () => {
            if (formModel.customerId) {
                clearValidateForm(formModelRef.value, ['groupId'])
                return customerFormRules.isGroupId
            } else {
                // 判断客户价且是销售部门人员及不是渠道部人员
                const isFlag = formModel.feeSetType === FeeSetType.CUSTOMER && unref(isSell) && !unref(isChannel)
                isFlag && (customerIdRules.value = customerFormRules.customerId)
                return isFlag ? customerFormRules.groupId : customerFormRules.isGroupId
            }
        },
        set: (val) => {
            customerFormRules.groupId = val
        }
    })
    // 建议价复选框
    const isFeeSetTypeChannel = computed(() => {
        return userstore.sysUserRoleDto.roleId === Department.CHANNEL && formModel.feeSetType === FeeSetType.CUSTOMER
    })
    // 建议价校验
    const recommendFeeSetRules = computed(() => {
        if (formModel.recommendFeeSet) clearValidateForm(formModelRef.value, ['recommendFeeSet'])
        if (unref(isFeeSetTypeChannel)) {
            return customerFormRules.recommendFeeSet
        }
        clearValidateForm(formModelRef.value, ['recommendFeeSet'])
        return customerFormRules.isRecommendFeeSet
    })
    // 判断如果是建议价就分公司、客户、客户分组都不能选
    const getDisabledSuggested = computed(() => {
        if (formModel.feeSetType === FeeSetType.SUGGESTED) return true;
        return false
    })
    // 判断当前时间是否在生效时间，如果是，禁用编辑分组
    const isDisabledBeginDate = computed(() => {
        if (formModel.type === EditType.VERSION) return false;
        const currentDate = new Date();
        const beginDate = new Date(`${formModel.beginDate}`)
        const endDate = new Date(`${formModel.endDate}`)
        if (currentDate >= beginDate && currentDate <= endDate) {
            return true
        }
        // 激活状态也禁止编辑
        if (formModel.activeFlag) return true
        return false
    })
    // 一天时间戳
    const millisecondsPerDay = 24 * 60 * 60 * 1000;
    //  禁用当日及之前的时间 ==> 新增版本
    const disabledCurrentDate = (time: Date) => {
        return formModel.type === EditType.VERSION && time.getTime() < Date.now()//(Date.now() - millisecondsPerDay);
    }

    return {
        customerIdRules,
        groupIdRules,
        isFeeSetTypeChannel,
        recommendFeeSetRules,
        getDisabledSuggested,
        isDisabledBeginDate,
        disabledCurrentDate
    }
}

export {
    useCustomerFeeSetBaseModel,
    useChangeCustomerRules,
    useCustomerOrgInfo
}