import { PartitionList } from '@/api/customerfee/CustomerFeeSetModel';
import { FormActionType } from '@/components/Form/src/types';
import { TableActionType } from '@/components/Table/src/types';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';
import { useMessage } from '@/hooks/useMessage';
import { EditType } from '@/type/BaseEnum';
import { BaseZoning } from '@/type/BaseZoningAction';
import { cloneDeep } from '@/utils/cloneDeep';
import { dealCountryInfoList, dealProtTargetTableList, dealZipCodeBelongAreaList } from '@/utils/dealData';
import { feeIdKey, 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 { isArrayLength } from '@/utils/is';
import { ListIitem } from '@/api/base/BaseDataModel';

type Methods = { methodsForm: FormActionType, methodsFormTable: TableActionType, methodsTableZoning: TableActionType }

type ZoningData = {
    actionsZoning: string,//分区操作状态,
    portList: Partial<PartitionList>[]//口岸分区列表
    postalCodeList: Recordable[]
    countryList: Recordable[]
    partitionList: Partial<PartitionList>[]
    zoningEditData: Recordable
}

// 提示
const { createMessage, createConfirm } = useMessage()
export function useZoningRote(methods: Methods, data?: any, props?: any) {
    // 接收的表单事件
    const { methodsForm, methodsFormTable, methodsTableZoning } = methods
    // 动态表格-表单-DOM节点
    const ruleFormTableRef = ref();
    // 
    // 分区列表
    const zoningData: ZoningData = reactive({
        actionsZoning: EditType.ADD,//分区操作状态-默认添加
        portList: [],//口岸分区列表
        postalCodeList: [],//邮编分区
        countryList: [],//国家/地区分区
        partitionList: [],//处理成后端所需的分区数据
        zoningEditData: {}//正在编辑分区内容
    })

    const partitionList = computed(() => props.partitionList)
    // 编辑、保存状态显示
    const actionsZoningText = computed(() => {
        const text = zoningData.actionsZoning === EditType.ADD ? '新增' : '编辑';
        return text;
    })

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

    // 校验表单
    const { formValidate } = useEleFormValidate();

    // 处理对应分区信息
    const zoningType = inject(zoningKey)
    // 费用编号
    const feeId = inject(feeIdKey)

    // 清除当前其它操作状态
    const currentClear = () => {
        // 重置状态
        zoningData.actionsZoning = EditType.ADD
        methodsForm.resetForm()
        methodsFormTable.clearSelectedRow()
        data.dataSource = [];
        zoningData.portList = []
        zoningData.countryList = []
        zoningData.postalCodeList = []
    }

    // 切换分区时切回新增状态
    watch(() => zoningType?.value, (val) => {
        nextTick(() => {
            if (val) {
                currentClear()
            }
        })
    })

    /**
     * 处理成对应的后端数据
     */
    const dealPartitionInformation = () => {
        switch (zoningType?.value) {
            case BaseZoning.ZONING_PORT:
                zoningData.partitionList = cloneDeep(zoningData.portList)
                // console.log(zoningData.partitionList, ":口岸分区");
                break;
            case BaseZoning.ZONING_COUNTRY:
                const countryList = cloneDeep(zoningData.countryList)
                zoningData.partitionList = countryList
                // console.log(zoningData.partitionList, ":国家/地区分区");
                break;
            case BaseZoning.ZONING_POSTAL_CODE:
                const postalCodeList = cloneDeep(zoningData.postalCodeList)
                zoningData.partitionList = dealCountryInfoList(postalCodeList)
                // console.log(zoningData.partitionList, ":邮编分区");
                break;
            default:
                break;
        }
    }

    // 头部添加行数据
    function hanleAddColumns(typeZoning: string) {
        data.dataSource.push({})
        switch (typeZoning) {
            case BaseZoning.ZONING_PORT:

                break;
            case BaseZoning.ZONING_COUNTRY:

                break;
            case BaseZoning.ZONING_POSTAL_CODE:

                break;
            default:
                break;
        }
    }

    // 行内添加行数据
    function hanleAddColumnsPort(scope) {
        // 当前行合并的字段数据
        const portCode = scope.row.portCode;
        const arr = [...data.dataSource];
        const index = arr.map(item => item.portCode).lastIndexOf(portCode);
        data.dataSource.splice(index, 0, {
            portCode: portCode,
            startZipCode: '',
            endZipCode: "",
            zipCodeRegex: "",
            address: ""
        })
        // console.log(scope, ":行内添加行数据");
        /**
         * 根据口岸添加行内容
         */
    }

    // 编辑/删除-分区列表数据
    function hanleActionColumns(scope, zoningType: string, type: string) {
        const rowData = scope.row;
        // 第几行的索引
        const index = scope.$index;
        // 正在编辑内容
        zoningData.zoningEditData = rowData
        switch (type) {
            // 编辑
            case EditType.EDIT:
                //分区操作状态-编辑
                zoningData.actionsZoning = EditType.EDIT;
                switch (zoningType) {
                    case BaseZoning.ZONING_PORT:
                        data.dataSource = [];
                        // 设置动态表格-表单数据
                        data.dataSource = dealProtTargetTableList(rowData.portWithZipCodeList) //口岸对应列表
                        // 设置基础表单数据
                        methodsForm.setDefaultValue({ ...rowData })
                        // data.dataSource = rowData.portWithZipCodeList //口岸对应列表
                        break;
                    case BaseZoning.ZONING_COUNTRY:
                        const cloneRow = cloneDeep(rowData)
                        if (!isArrayLength(cloneRow.countryInfoList)) return
                        // 默认跳到国家/地区复选框
                        const countryKeys = cloneRow.countryInfoList.map(item => item.countryId)
                        data.countryListKey = countryKeys
                        // if (cloneRow.countryInfoList.length > 1) {
                        //     // 多个国家/地区编辑
                        //     data.radioCountry = 2
                        //     data.countryListKey = countryKeys
                        // } else {
                        //     // 单个国家/地区编辑
                        //     data.downCountryKey = countryKeys[0]
                        // }
                        methodsForm.setDefaultValue({ ...rowData })
                        break;
                    case BaseZoning.ZONING_POSTAL_CODE:
                        data.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
                            // 编辑邮编列表显示
                            data.dataSource = isArrayLength(countryInfo) ? cloneDeep(countryInfo) : []
                            methodsForm.setDefaultValue({ ...rowData, countryId: countryId })

                        } else {
                            const countryInfo = rowData.countryInfoList[0]
                            let countryId = countryInfo.countryId ? countryInfo.countryId : rowData.countryId
                            // 编辑邮编列表显示
                            data.dataSource = isArrayLength(countryInfo.zipCodeBelongAreaList) ? cloneDeep(countryInfo.zipCodeBelongAreaList) : []
                            methodsForm.setDefaultValue({ ...rowData, countryId: countryId })
                        }
                        break;
                    default:
                        break;
                }
                break;
            // 删除
            case EditType.DELETE:
                createConfirm({
                    type: "warning",
                    message: "系统提示",
                    cancelButtonText: "取消",
                    confirmButtonText: "确定",
                    beforeClose: (action, instance, done) => {
                        if (action === "confirm") {
                            deleteActions(index)
                        }
                        done()
                    },
                })
                break;
            default:
                break;
        }
        // console.log(rowData, type, ":编辑/删除-分区列表数据");
    }

    /**
     * 表格数据-删除操作
     * @param index 数组索引
     */
    function deleteActions(index: number) {
        // 获取表格数据
        const dataSource = methodsTableZoning.getDataSource();
        if (dataSource.length === 0) return;
        // console.log(dataSource, ":dataSource");
        // 删除一行数据
        dataSource.splice(index, 1);
        dealPartitionInformation()
        // 更新数据
        methodsTableZoning.setDataSource(dataSource);
        currentClear()
    }

    /**
     * 添加分区内容
     * @param typeZoning 分区类型
     */
    async function dealZoningDataAdd(typeZoning: string) {
        // 动态-表格表单
        const isValidate = await formValidate(ruleFormTableRef.value);
        // 添加口岸分区列表数据
        switch (typeZoning) {
            // 添加-口岸分区数据
            case BaseZoning.ZONING_PORT:
                if (!isValidate) return;
                // 表单基础数据
                const form = await methodsForm.getVaule();
                // 口岸基本数据
                const portDataSource = methodsFormTable.getDataSource();
                // 处理口岸列表
                const portWithZipCodeList = dealZipCodeBelongAreaList(portDataSource)
                const portData = {
                    id: uuidv4(),// 分区编号
                    feeId: feeId?.value,// 费用编号
                    partitionType: BasePartitionTypeEnum.PORT,// 分区类型PartitionType
                    ...unref(form),
                    portWithZipCodeList
                }
                zoningData.portList.push(portData)
                methodsTableZoning.setDataSource(zoningData.portList);
                // 向分区列表添加数据
                dealPartitionInformation()
                // 清空数据
                clearForm();
                break;
            // 添加-国家/地区分区数据
            case BaseZoning.ZONING_COUNTRY:
                // 表单基础数据
                const form2 = await methodsForm.getVaule();
                // 判断是否选中国家/地区
                const isCountry = methodsFormTable.tableElRef()
                if (isCountry) return false
                // 选择的国家/地区
                const dataSource = methodsFormTable.getDataSource()
                const countryInfoList = dataSource.map(item => ({ countryId: item.value, haveZipCodeArea: false }))
                const countryId = dataSource.map(item => item.label).join(',')
                const countryData = {
                    id: uuidv4(),// 分区编号
                    feeId: feeId?.value,// 费用编号
                    partitionType: BasePartitionTypeEnum.COUNTRY,// 分区类型PartitionType
                    ...unref(form2),
                    countryId,
                    countryInfoList//国家/地区分区
                }
                // console.log('国家/地区分区数据', countryData);
                zoningData.countryList.push(countryData)
                // 向分区列表添加数据
                methodsTableZoning.setDataSource(zoningData.countryList);
                dealPartitionInformation()
                // 清空数据
                clearForm();
                methodsFormTable.clearSelectedRow()
                break;
            // 添加-邮编分区数据
            case BaseZoning.ZONING_POSTAL_CODE:
                if (!isValidate) return;
                // 表单基础数据
                const form3 = await methodsForm.getVaule();
                // 邮编基本数据
                const postalCodeDataSource = methodsFormTable.getDataSource();
                const postalCodeData = {
                    id: uuidv4(),// 分区编号
                    feeId: feeId?.value,// 费用编号
                    partitionType: BasePartitionTypeEnum.POSTALCODE,// 分区类型PartitionType
                    ...unref(form3),
                    countryInfoList: postalCodeDataSource
                }
                // console.log(postalCodeData, ":postalCodeData");
                zoningData.postalCodeList.push(postalCodeData);
                // 向分区列表添加数据
                methodsTableZoning.setDataSource(zoningData.postalCodeList);
                dealPartitionInformation()
                // 清空数据
                clearForm();
                break;
            default:
                break;
        }
    }

    async function dealZoningDataEdit(typeZoning: string) {
        // 动态-表格表单
        const isValidate = await formValidate(ruleFormTableRef.value);
        switch (typeZoning) {
            case BaseZoning.ZONING_PORT:
                if (!isValidate) return;
                // 表单基础数据
                const form = await methodsForm.getVaule();
                // 口岸基本数据
                const portDataSource = methodsFormTable.getDataSource();
                // 处理口岸列表
                const portWithZipCodeList = dealZipCodeBelongAreaList(portDataSource)
                zoningData.portList.map(item => {
                    if (item.id === zoningData.zoningEditData.id) {
                        return Object.assign(item, { ...form, portWithZipCodeList })
                    }
                    return item
                })
                dealPartitionInformation()
                // // 清空数据
                clearForm();
                // //分区操作状态-编辑
                zoningData.actionsZoning = EditType.ADD;
                break;
            case BaseZoning.ZONING_COUNTRY:
                console.log('国家/地区分区-编辑');
                // 表单基础数据
                const form2 = await methodsForm.getVaule();
                // 判断是否选中国家/地区
                const isCountry = methodsFormTable.tableElRef()
                if (isCountry) return false
                // 选择的国家/地区
                const dataSource = methodsFormTable.getDataSource()
                const cloneDataSource = cloneDeep(dataSource)
                const cloneForm2 = cloneDeep(form2)
                const countryInfoList = cloneDataSource.map(item => ({ countryId: item.value, haveZipCodeArea: false }))
                const countryId = cloneDataSource.map(item => item.label).join(',')
                zoningData.countryList.map(item => {
                    if (item.id === zoningData.zoningEditData.id) {
                        return Object.assign(item, { ...cloneForm2, countryId, countryInfoList })
                    }
                    return item
                })
                // // 清空数据
                clearForm();
                methodsFormTable.clearSelectedRow()
                //分区操作状态-编辑
                zoningData.actionsZoning = EditType.ADD;
                break;
            case BaseZoning.ZONING_POSTAL_CODE:
                if (!isValidate) return;
                // 表单基础数据
                const form3 = await methodsForm.getVaule();
                const countryForm = cloneDeep(form3)
                const countryDataSource = methodsFormTable.getDataSource()
                const countryDataSourceClone = cloneDeep(countryDataSource)
                const countryInfoList_ = countryDataSourceClone.map(item => ({ ...item, countryId: countryForm.countryId, haveZipCodeArea: true }))
                zoningData.postalCodeList.map(item => {
                    if (item.id === zoningData.zoningEditData.id) {
                        return Object.assign(item, { ...countryForm, countryInfoList: countryInfoList_ })
                    }
                    return item
                })
                dealPartitionInformation()
                // 清空数据
                clearForm();
                //分区操作状态-编辑
                zoningData.actionsZoning = EditType.ADD;
                break;
            default:
                break;
        }
    }

    /**
     * 保存表单数据
     * @param typeZoning 分区类型
     * @param type 操作类型
     */
    async function hanleGetData(typeZoning: string, type: string) {
        // 普通-表单
        const isValidate = await methodsForm.getFieldsValue();
        if (isValidate) {
            // 获取全部表单内容
            switch (type) {
                // 添加
                case EditType.ADD:
                    dealZoningDataAdd(typeZoning)
                    break;
                //编辑
                case EditType.EDIT:
                    dealZoningDataEdit(typeZoning)
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 清空/重置数据
     */
    function clearForm() {
        zoningData.zoningEditData = {}
        methodsForm.resetForm();
        if (data) data.dataSource = [];
    }

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

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

    return {
        hanleAddColumns,
        hanleAddColumnsPort,
        hanleActionColumns,
        hanleGetData,
        hanleDeleteColumnsPort,
        clearForm,
        dealPartitionInformation,
        hanleCancelValida,
        dealWithPortCodeData,
        ruleFormTableRef,
        zoningData,
        actionsZoningText,
        partitionList
    }
}