import { PartitionList } from '@/api/customerfee/CustomerFeeSetModel';
import { FormActionType } from '@/components/Form/src/types';
import { BaseTableProps } from '@/components/Table/src/types';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';
import { EditType } from '@/type/BaseEnum';
import { BaseZoning, BaseZoningAction } from '@/type/BaseZoningAction';
import { cloneDeep } from '@/utils/cloneDeep';
import { dealCountryInfoList, dealProtTargetTableList, dealZipCodeBelongAreaList } from '@/utils/dealData';
import { zoningKey } from '@/utils/injectionKey';
import { ref, computed, unref, reactive, inject, watch, nextTick } from 'vue';
import { v4 as uuidv4 } from 'uuid';
import { BasePartitionTypeEnum } from '@/type/BasePartitionTypeEnum';
import { isArray, isArrayLength } from '@/utils/is';
import { ListIitem } from '@/api/base/BaseDataModel';
import { useErrorConfirm } from '@/utils/useErrorConfirm';
import { zoningStore } from '@/store/zoning';

// 分区下拉列表
const zoningActionOptions = [
    {
        value: BaseZoningAction.ZONING_SETING,
        label: '分区设置'
    },
    {
        value: BaseZoningAction.ZONING_VIEW,
        label: '分区查看'
    },
    {
        value: BaseZoningAction.ZONING_TEMPLATE,
        label: '导出模板',
        permissions: ['sys:customerfeeset:export', 'sys:customerfeeset:export']
        // TODO 权限按钮显示
    },
    {
        value: BaseZoningAction.ZONING_TEMPLATE_LOAD,
        label: '模板加载'
    },
    {
        value: BaseZoningAction.ZONING_SPECIAL_PARAMETER,
        label: '特殊参数'
    }
]
const { report } = useErrorConfirm()
/**
 *  口岸分区 
 */
function useBasicZoning(addTableData: BaseTableProps, viewTableData: BaseTableProps, methodsForm: FormActionType) {
    const zoningData = reactive({
        actionsZoning: EditType.ADD,//分区操作状态-默认添加
        partitionList: [] as Partial<PartitionList>[],// 分区参数
        zoningEditData: {} as Recordable//正在编辑分区内容
    })
    // 动态表格-表单-DOM节点
    const ruleFormTableRef = ref();
    // 编辑、保存状态显示
    const actionsZoningText = computed(() => {
        const text = zoningData.actionsZoning === EditType.ADD ? '新增' : '编辑';
        return text;
    })
    // 分区 store
    const zoningstore = zoningStore()
    const orderNumber = computed(() => zoningstore.getOrderNumber)
    // 处理对应分区信息
    const zoningType = inject(zoningKey)
    // 校验表单
    const { formValidate } = useEleFormValidate();
    // 切换分区时切回新增状态
    watch(() => zoningType?.value, (val) => {
        nextTick(() => {
            if (val) {
                clearForm()
            }
            zoningstore.addOrderNumber(zoningData.partitionList.length)
            methodsForm.setDefaultValue({ orderNumber: orderNumber.value })
        })
    }, { immediate: true })

    // 添加行数据
    const hanleAddColumns = () => addTableData.dataSource.push({})
    // 行内添加行数据-口岸分区
    function hanleAddColumnsPort(scope) {
        debugger
        // 当前行合并的字段数据
        const portCode = scope.row.portCode;
        const arr = [...addTableData.dataSource];
        const index = arr.map(item => item.portCode).lastIndexOf(portCode);
        addTableData.dataSource.splice(index, 0, {
            portCode: portCode,
            startZipCode: '',
            endZipCode: "",
            zipCodeRegex: "",
            address: ""
        })
    }

    /**
    * 保存表单数据
    * @param typeZoning 分区类型
    * @param type 操作类型
    */
    async function hanleGetData(typeZoning: string, type: string) {
        // 获取全部表单内容
        switch (type) {
            // 添加
            case EditType.ADD:
                dealZoningDataAdd(typeZoning)
                break;
            //编辑
            case EditType.EDIT:
                dealZoningDataEdit(typeZoning)
                break;
            default:
                break;
        }
    }
    /**
     * 清空/重置数据
     */
    function clearForm() {
        methodsForm.resetForm();
        addTableData.dataSource = [];
        zoningData.actionsZoning = EditType.ADD;
        zoningData.zoningEditData = {}
    }
    /**
     * 清空动态表格表单的数据
     */
    function clearFormSource() {
        addTableData.dataSource = [];
    }

    /**
     * 添加分区内容
     * @param typeZoning 分区类型
     */
    async function dealZoningDataAdd(typeZoning: string) {
        debugger
        // 校验基础表单、动态表格表单
        Promise.all([formValidate(ruleFormTableRef.value), methodsForm.getFieldsValue()])
            .then(async (results) => {
                // console.log(results, ":results");
                // 校验的全部状态
                const isValidate = results.every((item) => {
                    if (item === undefined) return true
                    return item
                })
                if (!isValidate) return
                // 添加口岸分区列表数据
                switch (typeZoning) {
                    // TODO 1、序号默认按照顺序添加
                    // 添加-口岸分区数据
                    case BaseZoning.ZONING_PORT:
                        // 表单基础数据
                        const formPort = await methodsForm.getVaule();
                        // 口岸基本数据
                        const portDataSource = cloneDeep(addTableData.dataSource)
                        // 处理口岸列表
                        const portWithZipCodeList = dealZipCodeBelongAreaList(portDataSource)
                        const partitionPort: Partial<PartitionList> = {
                            id: uuidv4(),// 分区编号
                            feeId: zoningstore.feeId,// 费用编号
                            partitionType: BasePartitionTypeEnum.PORT,// 分区类型PartitionType
                            ...unref(formPort),
                            portWithZipCodeList
                        }
                        // console.log(partitionPort, ":添加-口岸分区数据");
                        // 添加分区数据
                        zoningData.partitionList.push(partitionPort)
                        viewTableData.dataSource = zoningData.partitionList
                        // 清空数据
                        clearForm();
                        break;
                    // 添加-国家/地区分区数据
                    case BaseZoning.ZONING_COUNTRY:
                        // 表单基础数据
                        const formCountry = await methodsForm.getVaule();
                        // 选择的国家/地区
                        const countryDataSource = addTableData.dataSource
                        const countryInfoList = countryDataSource.map(item => ({ countryId: item.value, haveZipCodeArea: false }))
                        const countryId = countryDataSource.map(item => item.label).join(',')
                        const countryData: Partial<PartitionList> = {
                            id: uuidv4(),// 分区编号
                            feeId: zoningstore.feeId,// 费用编号
                            partitionType: BasePartitionTypeEnum.COUNTRY,// 分区类型PartitionType
                            ...unref(formCountry),
                            countryId,
                            countryInfoList//国家/地区分区
                        }
                        // console.log('国家/地区分区数据', countryData);
                        // 向分区列表添加数据
                        zoningData.partitionList.push(countryData)
                        viewTableData.dataSource = zoningData.partitionList
                        // // 清空数据
                        clearForm();
                        break;
                    // 添加-邮编分区数据
                    case BaseZoning.ZONING_POSTAL_CODE:
                        // 表单基础数据
                        const formPostalCode = await methodsForm.getVaule();
                        // 邮编基本数据
                        const postalCodeDataSource = cloneDeep(addTableData.dataSource)
                        const postalCodeData = {
                            id: uuidv4(),// 分区编号
                            feeId: zoningstore.feeId,// 费用编号
                            partitionType: BasePartitionTypeEnum.POSTALCODE,// 分区类型PartitionType
                            ...unref(formPostalCode),
                            countryInfoList: postalCodeDataSource
                        }
                        const [partitionPostalCode] = dealCountryInfoList([postalCodeData])
                        // console.log(postalCodeData, ":添加-邮编分区数据", partitionPostalCode);
                        // 向分区列表添加数据
                        zoningData.partitionList.push(partitionPostalCode);
                        viewTableData.dataSource = zoningData.partitionList
                        // 清空数据
                        clearForm();
                        break;
                    default:
                        break;

                }
                zoningstore.addOrderNumber(zoningData.partitionList.length)
                methodsForm.setDefaultValue({ orderNumber: orderNumber.value })
            }).catch((error) => report(error))
    }
    /**
     * 编辑分区内容
     */
    async function dealZoningDataEdit(typeZoning: string) {
        // 校验基础表单、动态表格表单
        Promise.all([formValidate(ruleFormTableRef.value), methodsForm.getFieldsValue()])
            .then(async (results) => {
                // 校验的全部状态
                const isValidate = results.every((item) => {
                    if (item === undefined) return true
                    return item
                })
                if (!isValidate) return
                switch (typeZoning) {
                    case BaseZoning.ZONING_PORT:
                        // 表单基础数据
                        const form = await methodsForm.getVaule();
                        // 口岸基本数据
                        const portDataSource = addTableData.dataSource
                        // 处理口岸列表
                        const portWithZipCodeList = dealZipCodeBelongAreaList(portDataSource)
                        zoningData.partitionList.map(item => {
                            if (item.id === zoningData.zoningEditData.id) {
                                return Object.assign(item, { ...form, portWithZipCodeList })
                            }
                            return item
                        })
                        // // 清空数据
                        clearForm();
                        break;
                    case BaseZoning.ZONING_COUNTRY:
                        console.log('国家/地区分区-编辑');
                        // 表单基础数据
                        const form2 = await methodsForm.getVaule();
                        // // 选择的国家/地区
                        const icountryDataSource = addTableData.dataSource
                        const countryInfoList = icountryDataSource.map(item => ({ countryId: item.value, haveZipCodeArea: false }))
                        const countryId = icountryDataSource.map(item => item.label).join(',')
                        zoningData.partitionList.map(item => {
                            if (item.id === zoningData.zoningEditData.id) {
                                return Object.assign(item, { ...form2, countryId, countryInfoList })
                            }
                            return item
                        })
                        // // 清空数据
                        clearForm();
                        break;
                    case BaseZoning.ZONING_POSTAL_CODE:
                        // 表单基础数据
                        const form3 = await methodsForm.getVaule();
                        const countryDataSource = addTableData.dataSource
                        const countryInfoListFilter = countryDataSource.map(item => ({ ...item, countryId: form3.countryId }))
                        zoningData.partitionList.map(item => {
                            if (item.id === zoningData.zoningEditData.id) {
                                const [editItem] = dealCountryInfoList([{ ...item, ...form3, countryInfoList: countryInfoListFilter }])
                                return Object.assign(item, { ...editItem })
                            }
                            return item
                        })
                        // 清空数据
                        clearForm();
                        break;
                    default:
                        break;
                }
            }).catch((error) => report(error))
    }

    // 编辑/删除-分区列表数据
    function hanleActionColumns(scope, zoningType: string, type: string) {
        const rowData = scope.row;
        // 第几行的索引
        const index = scope.$index || scope.rowIndex;
        // 正在编辑内容
        zoningData.zoningEditData = rowData
        switch (type) {
            // 编辑
            case EditType.EDIT:
                //分区操作状态-编辑
                zoningData.actionsZoning = EditType.EDIT;
                switch (zoningType) {
                    case BaseZoning.ZONING_PORT:
                        addTableData.dataSource = [];
                        // 设置动态表格-表单数据
                        addTableData.dataSource = dealProtTargetTableList(rowData.portWithZipCodeList) as Recordable[] //口岸对应列表
                        // 设置基础表单数据
                        methodsForm.setDefaultValue({ ...rowData })
                        // data.dataSource = rowData.portWithZipCodeList //口岸对应列表
                        break;
                    case BaseZoning.ZONING_COUNTRY:
                        addTableData.dataSource = [];
                        if (!isArrayLength(rowData.countryInfoList)) return
                        // 选取key值
                        const countryKeys = rowData.countryInfoList.map(item => item.countryId)
                        methodsForm.setDefaultValue({ ...rowData, countryKeys })
                        break;
                    case BaseZoning.ZONING_POSTAL_CODE:
                        addTableData.dataSource = [];
                        // console.log(rowData, ":编辑邮编信息");
                        if (!isArrayLength(rowData.countryInfoList)) return methodsForm.setDefaultValue({ ...rowData })
                        // 设置动态表格-表单数据
                        if (!isArrayLength(rowData.countryInfoList[0].zipCodeBelongAreaList)) {
                            const countryInfo = rowData.countryInfoList
                            let countryId = isArrayLength(rowData.countryInfoList) ? rowData.countryInfoList[0].countryId || rowData.countryId : rowData.countryId
                            // 编辑邮编列表显示
                            addTableData.dataSource = isArrayLength(countryInfo) ? cloneDeep(countryInfo) : []
                            methodsForm.setDefaultValue({ ...rowData, countryId: countryId })
                        } else {
                            const countryInfo = rowData.countryInfoList[0]
                            let countryId = countryInfo.countryId ? countryInfo.countryId : rowData.countryId
                            // 编辑邮编列表显示
                            addTableData.dataSource = isArrayLength(countryInfo.zipCodeBelongAreaList) ? cloneDeep(countryInfo.zipCodeBelongAreaList) : []
                            methodsForm.setDefaultValue({ ...rowData, countryId: countryId })
                        }
                        break;
                    default:
                        break;
                }
                break;
            // 删除
            case EditType.DELETE:
                deleteActions(index)
                break;
            default:
                break;
        }
        // console.log(rowData, type, ":编辑/删除-分区列表数据");
    }

    /**
     * 表格数据-删除操作
     * @param index 数组索引
     */
    function deleteActions(index: number) {
        // 获取查看表格数据
        const dataSource = viewTableData.dataSource
        if (dataSource.length === 0) return;
        // 删除一行数据
        dataSource.splice(index, 1);
        // 更新数据
        zoningData.partitionList = dataSource
        viewTableData.dataSource = dataSource
        clearForm()
    }

    // 删除-动态表单数据
    function hanleDeleteColumnsPort(row) {
        const index = row.$index;
        addTableData.dataSource.splice(index, 1)
    }

    // 校验邮编数据
    const hanleCancelValida = () => {
        nextTick(async () => {
            await ruleFormTableRef.value.validate()
        })
    }

    return {
        hanleAddColumns,
        hanleGetData,
        hanleDeleteColumnsPort,
        hanleActionColumns,
        hanleAddColumnsPort,
        clearForm,
        clearFormSource,
        dealWithPortCodeData,
        hanleCancelValida,
        ruleFormTableRef,
        zoningData,
        actionsZoningText,
        zoningstore,
        orderNumber
    }
}

/**
 * 口岸编号显示对应文本
 */
const dealWithPortCodeData = (portWithZipCodeList: ListIitem[], list: Recordable[]) => {
    if (!isArrayLength(portWithZipCodeList) && !isArray(list)) return
    const portCodeTextArr: ListIitem[] = []
    for (const item of list) {
        if (item.portCode) {
            const portCode = portWithZipCodeList.find(port => port.value == item.portCode)
            portCode && portCodeTextArr.push(portCode)
        }
    }
    const portCodeText = portCodeTextArr.map(item => item.label).join(',')
    return portCodeText
}


export {
    useBasicZoning,
    dealWithPortCodeData,
    zoningActionOptions,
}