import type { BasicTableProps, VxeGridInstance } from '@/components/VxeTable';
import { CustomerParam, CustomerPaymentTypeParam } from '@/api/paymentType/paymentTypeModle';
import { useDropDownData } from '@/hooks/useDropDownData';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';
import { useQueryList } from '@/hooks/useQueryList';
import { ref, reactive, unref, computed, onBeforeMount } from 'vue';
import { resCodeSuccess, useReturnData } from '@/utils/useReturnData';
import { api_customerList, api_customerSetPaymentType, api_getCustomerByName } from '@/api/paymentType/paymentType';
import { isArrayLength } from '@/utils/is';
import { useMessage } from '@/hooks/useMessage';
import { usePersonnel } from '@/store/list_personnel';
import { ListIitem } from '@/api/base/BaseDataModel';
import { userStore } from '@/store/user';
import { Department } from '@/type/BaseBusinessFeeseType';

const { resData } = useReturnData()
const { createMessage } = useMessage()
// TODO 客户支付方式管理
/**
 * 
 * @returns 
 */
function usePaymentTypeList(customerListOptions: BasicTableProps) {
    const { storeDropDownData, branchCompanyCustomers, accountPeriodTypeList } = useDropDownData()
    const storePersonnel = usePersonnel()
    const searchFormRef = ref()
    const customerListParams = reactive<CustomerParam>({
        salesmanUserId: undefined,
        orgId: undefined,
        idList: [],
        customerNameList: [],
        pageNum: 1,
        pageSize: 10,
        total: 0
    })
    const customerListState = reactive({
        loading: false,
        setPaymentFlagList: [
            { value: 0, label: '否' },
            { value: 1, label: '是' },
        ] as ListIitem[],//支付方式
        isOrderIdList: false,//显示/隐藏输入框框
        inputMultiCustomerName: '',//单号文本框1
        inputCustomerName: '',//单号文本框2
        reportType: 0,//报表类型
        oldIdList: [],//客户名称匹配的客户编号
    })
    // 设置支付方式弹窗
    const setPaymentTypeRef = ref<{ show: Fn }>()
    const paymentTypeTableRef = ref<VxeGridInstance>()
    const userstore = userStore();
    const getSysUserRoleDto = computed(() => userstore.sysUserRoleDto);
    // 判断是否显示销售人员搜索
    const getShowSalesmanUser = computed(() => {
        if (unref(getSysUserRoleDto).roleId === Department.SELL) return false
        return true
    })

    onBeforeMount(() => {
        // storeDropDownData.addCustomertList()
        storeDropDownData.addBranchCompanyCustomers()
        storeDropDownData.addPaymentPlatformList()
        storeDropDownData.addAccountPeriodTypeList()
        storePersonnel.addGetSalesmanUserList()
    })
    const { resetForm } = useEleFormValidate()
    // 重置
    const resetParams = () => {
        resetForm(searchFormRef.value)
    }
    // 初始化列表
    const initList = async () => {
        try {
            customerListState.loading = true
            customerListOptions.loading = true
            const res = await api_customerList(listParams)
            if (resCodeSuccess(res)) {
                customerListOptions.data = res.data.records
                customerListParams.total = res.data.total
            }
        } finally {
            customerListState.loading = false
            customerListOptions.loading = false
        }
    }
    // 初始化列表、分页数据
    const { sizeChange, currentChange, searchBtn, resetBtn, listParams } = useQueryList<CustomerParam>(initList, resetParams, customerListParams)
    // 打开设置
    const hanleSetPaymentType = (row) => {
        unref(setPaymentTypeRef)?.show(row.oldId)
    }
    // 设置客户支付方式
    const saveSetPaymentType = async (params: CustomerPaymentTypeParam, onclose: Fn, setLoading: Fn) => {
        try {
            const res = await api_customerSetPaymentType(params)
            const codeData = resData(res, "操作成功")
            if (codeData !== 500) {
                onclose()
                initList()
            }
        } finally {
            setLoading(false)
        }
    }
    // 批量设置支付方式
    const hanleBatchSetPayment = async () => {
        const $table = unref(paymentTypeTableRef)
        if(!$table) return
        const checkData = $table.getCheckboxRecords()
        const oldIdList = checkData.map(item => item.oldId)
        const mergeOldIdList = [...customerListState.oldIdList, ...oldIdList]
        if (!isArrayLength(mergeOldIdList)) {
            createMessage.warning('请选择客户！')
            return
        }
        unref(setPaymentTypeRef)?.show(mergeOldIdList)
    }

    // 显示小提示框输入客户名称
    const multiCustomerNameRef = ref()
    // 清除客户名称按钮
    const hanlClearCustomerNameList = () => {
        customerListState.inputMultiCustomerName = ''
        customerListState.inputCustomerName = ''
        customerListParams.customerNameList = []
        customerListState.oldIdList = []
    }
    // 确定单号按钮
    const confirmMultiCustomerName = async () => {
        const customerNames = customerListState.inputMultiCustomerName.split(/,|，| |\r|\n/)
        customerListParams.customerNameList = customerNames.filter(item => item)
        customerListState.inputCustomerName = customerNames.join(',')
        // 获取客户编号
        if (isArrayLength(customerListParams.customerNameList)) {
            const res = await api_getCustomerByName({ customerNameList: customerListParams.customerNameList })
            if (resCodeSuccess(res) && res.data.length > 0) {
                customerListState.oldIdList = res.data
            }
        }
    }
    // popover显示结束事件
    const afterEnterCustomerName = () => {
        if (!unref(multiCustomerNameRef)) return
        multiCustomerNameRef.value?.focus()
    }
    // change事件
    const changeCustomerName = (val) => {
        if (!val) hanlClearCustomerNameList()
    }
    // 单号聚焦事件
    const focusCustomerName = async () => {
        afterEnterCustomerName()
    }
    
    return {
        searchFormRef,
        customerListParams,
        customerListState,
        branchCompanyCustomers,
        setPaymentTypeRef,
        sizeChange,
        currentChange,
        searchBtn,
        resetBtn,
        hanleSetPaymentType,
        saveSetPaymentType,
        paymentTypeTableRef,
        hanleBatchSetPayment,
        storePersonnel,
        getShowSalesmanUser,
        accountPeriodTypeList,
        multiCustomerNameRef,
        changeCustomerName,
        focusCustomerName,
        afterEnterCustomerName,
        confirmMultiCustomerName,
        hanlClearCustomerNameList
    }
}


/**
 * 表格配置
 * @returns 
 */
function usePaymentTypeListModle() {
    const customerListGridOptions = reactive<BasicTableProps>({
        id: 'customer_list_table',
        border: true,
        keepSource: true,
        showOverflow: true,
        height: 520,
        loading: false,
        stripe: true,
        rowConfig: {
            isHover: true,
        },
        customConfig: {
            storage: {
                visible: true,
            }
        },
        columnConfig: {
            resizable: true
        },
        columns: [
            { type: "checkbox", width: 45, visible: true },
            { type: "seq", width: 55, title: '序号' },
            { field: 'companyName', title: '客户名称', minWidth: 130 },
            { field: 'displayName', title: '简称', minWidth: 100 },
            { field: 'accountPeriodName', title: '账期类型', width: 100 },
            { field: 'orgId', title: '分公司', width: 120, slots: {  default: 'orgId' } },
            { field: 'salesmanUserName', title: '业务员', width: 120 },
            { field: 'customerCode', title: '编码', width: 170 },
            { 
                field: 'paymentTypeList', 
                title: '支付方式', 
                width: 130,
                formatter: ({ row }) => {
                    if (isArrayLength(row.paymentTypeList)) return row.paymentTypeList.join('、')
                    return ''
                }
            },
            { field: 'createTime', title: '创建时间', width: 155 },
            { title: '操作', slots: { default: 'actions' }, width: 106, fixed: 'right' }
        ],
        data: []
    })
    
    return {
        customerListGridOptions
    }
}

export {
    usePaymentTypeList,
    usePaymentTypeListModle
}