import { shallowRef, reactive, computed } from 'vue'
import { v4 } from 'uuid'
import { useDataTable } from '@/hooks/datatable'
import { getTableColumns } from '@/business/table'
import { formatDecimal } from '@/filters'
import { ClientType } from '@/constants/client'
import { Market } from '@/constants/market'
import { queryWarehouseInfo } from '@/services/api/warehouse'
import { addDiamond, queryDiamondList, queryDiamondDetails, goodsFavoriteOperate, receiptZSOutApply } from '@/services/api/goods'
import { useLoginStore } from '@/stores'
import {
    Category,
    getCurrencyTypeList,
    getShapeTypeList,
    getColorTypeList,
    getCutTypeList,
    getClarityTypeList,
    getPolishTypeList,
    getSymmetryTypeList,
    getFluorescenceTypeList,
    getCurrencyTypeInfo,
    getCertTypeList,
    getCrystalTypeList,
    getStyleTypeList,
    getFancyColorType1List,
    getFancyColorType2List,
    getFancyColorType3List,
} from '@/constants/diamond'
import Long from 'long'

// 钻石列表相关
export function useDiamond() {
    const { getUserId } = useLoginStore()
    const { dataList, total, pageIndex, pageSize, inputList, selectList, buttonList, filterMethod, getQueryParam } = useDataTable<Ermcp.MyWRPositionRsp>()
    const loading = shallowRef(false)
    const columns = shallowRef(getTableColumns('warehousing_diamond'))

    const categoryList = [
        { label: '单颗裸钻', value: Category.Diamond },
        { label: '单颗彩钻', value: Category.Fancy },
        { label: '钻石首饰', value: Category.Jewelry }
    ]

    selectList.value = [
        {
            label: '商品分类',
            key: 'zscategory',
            selectedValue: Category.Diamond,
            options: categoryList,
            noClear: true,
        },
        {
            label: '仓库',
            key: 'warehouseid',
            options: [],
        },
    ]

    inputList.value = [
        { label: '商品', keys: ['goodsno'] },
    ]

    filterMethod.onReset = () => {
        getDiamondList()
    }

    filterMethod.onSearch = () => {
        getDiamondList()
    }

    const getDiamondList = () => {
        const param = getQueryParam()
        loading.value = true
        return queryDiamondList({
            data: {
                page: pageIndex.value,
                pagesize: pageSize.value,
                wruserid: getUserId(),
                zscategorys: param.zscategory ? param.zscategory.toString() : categoryList.map((e) => e.value).join(','),
                zsallproperties: param.goodsno,
                warehouseid: param.warehouseid,
            },
            success: (res) => {
                total.value = res.total
                dataList.value = res.data
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    // 获取仓库列表
    queryWarehouseInfo({
        data: {
            userid: getUserId(),
            status: 1,
            isincludeexchange: true,
        },
        success: (res) => {
            const warehouse = selectList.value[1]
            res.data.forEach((e) => {
                warehouse.options.push({
                    label: e.warehousename,
                    value: e.autoid
                })
            })
        }
    })

    return {
        loading,
        dataList,
        total,
        pageIndex,
        pageSize,
        columns,
        inputList,
        selectList,
        buttonList,
        getDiamondList,
    }
}

// 钻石详情相关
export function useDiamondDetails(goodsno: string) {
    const loading = shallowRef(false)
    const details = shallowRef<Ermcp.DiamondDetailsRsp>()

    const getDiamondDetails = async () => {
        loading.value = true
        return queryDiamondDetails({
            data: {
                goodsno,
            },
            success: (res) => {
                details.value = res.data
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        details,
        getDiamondDetails,
    }
}

// 钻石上架相关
export function useDiamondForm(category: Category) {
    const { loginInfo } = useLoginStore()
    const { UserID, AccountIDs } = loginInfo.value
    const loading = shallowRef(false)
    const warehouseList = shallowRef<Ermcp.WarehouseInfoRsp[]>([]) // 仓库列表
    const performanceId = shallowRef<number>() // 选中的履约模板ID
    const shapeId = shallowRef<number>() // 选中的形状ID
    const formData = reactive<Partial<Proto.GZWRStandardExInfo>>({
        ZSCategory: category,
    })

    // 选中的枚举类型
    const selectedType = reactive({
        colorType: computed({
            get: () => [formData.ZSColorType1, formData.ZSColorType2],
            set: (val) => {
                formData.ZSColorType1 = val[0]
                formData.ZSColorType2 = val[1]
            }
        }),
        cutType: computed({
            get: () => [formData.ZSCutType1, formData.ZSCutType2],
            set: (val) => {
                formData.ZSCutType1 = val[0]
                formData.ZSCutType2 = val[1]
            }
        }),
        clarityType: computed({
            get: () => [formData.ZSClarityType1, formData.ZSClarityType2],
            set: (val) => {
                formData.ZSClarityType1 = val[0]
                formData.ZSClarityType2 = val[1]
            }
        }),
        polishType: computed({
            get: () => [formData.ZSPolishType1, formData.ZSPolishType2],
            set: (val) => {
                formData.ZSPolishType1 = val[0]
                formData.ZSPolishType2 = val[1]
            }
        }),
        symmetryType: computed({
            get: () => [formData.ZSSymmetryType1, formData.ZSSymmetryType2],
            set: (val) => {
                formData.ZSSymmetryType1 = val[0]
                formData.ZSSymmetryType2 = val[1]
            }
        }),
        fluorescenceType: computed({
            get: () => [formData.ZSFluorescenceType1, formData.ZSFluorescenceType2],
            set: (val) => {
                formData.ZSFluorescenceType1 = val[0]
                formData.ZSFluorescenceType2 = val[1]
            }
        }),
    })

    // 枚举类型列表
    const enums = {
        currencyTypeList: getCurrencyTypeList(),
        shapeTypeList: getShapeTypeList(),
        colorTypeList: getColorTypeList(),
        cutTypeList: getCutTypeList(),
        clarityTypeList: getClarityTypeList(),
        polishTypeList: getPolishTypeList(),
        symmetryTypeList: getSymmetryTypeList(),
        fluorescenceTypeList: getFluorescenceTypeList(),
        certTypeList: getCertTypeList(),
        crystalTypeList: getCrystalTypeList(),
        styleTypeList: getStyleTypeList(),
        fancyColorType1List: getFancyColorType1List(),
        fancyColorType2List: getFancyColorType2List(),
        fancyColorType3List: getFancyColorType3List(),
    }

    if (enums.currencyTypeList.length) {
        formData.ZSCurrencyType = enums.currencyTypeList[0].value
    }

    // 克拉单位
    const caratUnit = computed(() => {
        const { Price, Weight } = formData
        if (Price && Weight) {
            return formatDecimal(Price / Weight)
        }
        return '0.00'
    })

    // 货币信息
    const currencyInfo = computed(() => getCurrencyTypeInfo(formData.ZSCurrencyType ?? 0))

    const addOrUpdate = () => {
        loading.value = true
        return addDiamond({
            data: {
                UserID,
                AccountID: AccountIDs[0],
                AddType: performanceId.value ? 2 : 1,
                MarketID: Market.GZ,
                OrderSrc: 1,
                ClientType: ClientType.Web,
                ClientSerialNo: v4(),
                GZ_WRStandardExInfo: formData,
                PerformanceTemplateID: performanceId.value,
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    // 获取仓库列表
    queryWarehouseInfo({
        data: {
            userid: UserID,
            status: 1,
            isincludeexchange: true,
        },
        success: (res) => {
            warehouseList.value = res.data
        }
    })

    return {
        loading,
        formData,
        performanceId,
        shapeId,
        caratUnit,
        enums,
        selectedType,
        warehouseList,
        currencyInfo,
        addOrUpdate,
    }
}

// 钻石收藏相关
export function useDiamondFavorite(selectedRow: Ermcp.MyWRPositionRsp | Ermcp.SellOrderRsp) {
    const { getUserId } = useLoginStore()
    const loading = shallowRef(false)

    // 钻石收藏操作
    const formSubmit = (operateType: number) => {
        loading.value = true
        return goodsFavoriteOperate({
            data: {
                UserID: getUserId(), // 用户ID，必填
                WRTradeOrderID: Long.fromString(selectedRow.wrtradeorderid), // 委托单ID，必填
                OperateType: operateType, // 操作类型，1:添加2:删除,必填
                ClientType: ClientType.Web, // 终端类型
                MarketID: Market.GZ, // 市场ID,必填
                ClientSerialNo: v4() // 客户端流水号
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        formSubmit
    }
}

// 钻石删除相关
export function useDiamondDelete(selectedRow: Ermcp.MyWRPositionRsp) {
    const { loginInfo } = useLoginStore()
    const { UserID, AccountIDs } = loginInfo.value
    const loading = shallowRef(false)

    const formSubmit = () => {
        loading.value = true
        return receiptZSOutApply({
            data: {
                Common: {
                    UserID,
                    AccountID: AccountIDs[0],
                    RelatedOrderID: new Date().getTime(),
                    TradeID: new Date().getTime(),
                },
                UserID,
                AccountID: AccountIDs[0],
                LadingBillID: Long.fromString(selectedRow.ladingbillid),
                SubNum: selectedRow.subnum,
                Qty: selectedRow.weight,
                ApplyType: 1,
                ClientType: ClientType.Web, // 终端类型
                ClientTicket: v4() // 客户端流水号
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        formSubmit
    }
}