import { ref, computed, watch } from "vue";
import { auditorOrderSettlement,sendCode } from "@/api/finance/settlement.js";
import useUserStore from '@/store/modules/user'
import { takeList, paymentList, takeApproval, careatPayment,payoutCheck } from "@/api/finance/withdrawal.js";
//功能
export default ({ proxy, jlzj_area_type }) => {
    const router = useRouter();
    const dialogFormRef = ref(null);
    const userTableRef = ref(null);
    const dialogVerifyRef =ref(null);
    const verifyCode =ref('');
   


    const tabkey = ref('0');
    const {
        pay_type,
        is_pay,
        volunteer_app_status,
        is_verified,
        payment_status
    } = proxy.useDict("pay_type", "is_pay", "volunteer_app_status","payment_status","is_verified");

    const dialogPlay = ref(false); //打款单详情
    const dialogRow = ref({});
    const dialogVerify =ref(false);

    //打开弹窗
    const openDialog = (data, type) => {
        try {
            const disabledData = {
                alipayAccountNo: true,
                alipayName: true,
                takeAmount: true,
                createTime: true,

            }
            //审核
            if (type === 'examine') {

                dialogFormRef.value.initForm(data, disabledData)
            }
            if (type === 'details') {
                disabledData['appStatus'] = true;
                disabledData['rejectReason'] = true;
                dialogFormRef.value.initForm(data, disabledData)
            }

        } catch (error) {
            console.log('error', error);
        } finally {
            dialogFormRef.value.handleDialog(true);
        }
    }
    //导出
    const exportFile = async (parmas) => {
        // try {
        //     proxy.download("core/orderSettlementApplication/export",{
        //         ...queryParams.value,
        //     }, `订单费用结算_${new Date().getTime()}.xlsx`);
        // } catch (error) { 
        // }
    }

    //审核提交
    const submitForm = async (data) => {

        try {
            const parmas = {
                volunteerTakeRecordId: data.volunteerTakeRecordId,
                appStatus: data.appStatus,
                rejectReason: data.rejectReason
            }
            const res = await takeApproval(parmas);
            if (res.code === 200) {
                proxy.$modal.msgSuccess("审核成功");
                return;
            }
            proxy.$modal.msgSuccess(res.msg);
        } catch (error) {
            console.log('error', error);
        } finally {
            userTableRef.value.resetForm();
            dialogFormRef.value.handleDialog(false);
        }
    }


    const getList = (data) => {
        const parmasData = JSON.parse(JSON.stringify(data));
        if (parmasData.tabkeys) {
            delete parmasData.tabkeys;
        }
        tabkey.value = data.tabkeys;
        return data.tabkeys === '4' ? paymentList(parmasData):takeList({ ...parmasData });
    }

    const paymentSubmit = async (ids) => {
        try {

            const res = await careatPayment({
                ids,
                payType: '2'
            })
            if (res.code === 200) {
                proxy.$modal.msgSuccess("创建成功!");
                return;
            }
            proxy.$modal.msgSuccess(res.msg);
        } catch (error) {
            console.log('error', error);
        } finally {
            userTableRef.value.resetForm();
        }
    }

    const openVerify = (data,type) => {
        try {
            const disabledData = {
                volunteerPaymentRecordsId: true,
                paymentOrderNumber:true,
                payType:true
            }
            if(type === 'details'){
                disabledData['payPassword'] = true;
            }
            dialogVerifyRef.value.initForm(data, disabledData)
        } catch (error) {
            console.log('error', error);
        } finally {
            userTableRef.value.resetForm();
            dialogVerifyRef.value.handleDialog(true);
        }
    }
    const submitVerify = async() => {
        try {
            const data =dialogRow.value;
            const parmas = {
                volunteerPaymentRecordsId: data.volunteerPaymentRecordsId,
                paymentOrderNumber: data.paymentOrderNumber,
                payPassword:verifyCode.value
            }
            const res = await payoutCheck(parmas);
            if (res.code === 200) {
                proxy.$modal.msgSuccess("操作成功");
                verifyCancel();
                userTableRef.value.resetForm();
                return;
            }
            proxy.$modal.msgSuccess(res.msg);
        } catch (error) {
            console.log('error', error);
        }
    }
    const verifyCancel =()=>{
        dialogVerify.value = false;
        dialogRow.value = {};
        verifyCode.value ='';
        clearInterval(timer);
        timer = null;
        code.value = 60;
    }

    const getVerList = async (data) => {
        return takeList({ ...data,paymentRecordId: dialogRow.value.volunteerPaymentRecordsId})
    }

    const verifyClose = ()=>{
        dialogPlay.value = false;
        dialogRow.value = {};
    }
    const code = ref(60);
    let timer=null;
    watch(()=>code.value,()=>{
        if(code.value === 0){
            clearInterval(timer);
            timer = null;
            code.value = 60;
        }
    })
    const getCode = async() => {
        const userStore = useUserStore();
        if(code.value < 60){
            proxy.$modal.msgError('请勿重复获取！');
            return;
        }
        if(userStore.phonenumber && code.value === 60){
            try {
                const res =await sendCode(userStore.phonenumber);
                if(res.code === 200){
                    proxy.$modal.msgSuccess(res.msg);
                    timer = setInterval(()=>{
                        code.value--;                        
                    },1000)
                }else{
                    proxy.$modal.msgError(res.msg);
                }
            } catch (error) {
                console.log("TCL: exportFile -> error", error)
            }
        }
    }

    return {
        dialogFormRef,
        userTableRef,                                                     
        dialogVerifyRef,
        dialogPlay,
        tabkey,
        dialogRow,
        dialogVerify,
        verifyCode,
        code,
        openDialog,
        exportFile,
        submitForm,
        getList,
        submitVerify,
        verifyClose,
        getVerList,
        verifyCancel,
        getCode,
        tabList: [
            // {
            //     title: '支付宝提现审核',
            //     name: '1'
            // },
            // {
            //     title: '审核驳回',
            //     name: '3'
            // },
            {
                title: '支付宝提现申请单',
                name: ''
            },
            {
                title: '打款单记录',
                name: '4'
            },
        ],
        talkeColumn:ref([
            {
                label: '支付宝账号',
                prop: 'alipayAccountNo',
                type: 'input',
                isSearch: true
            },
            {
                label: '支付宝户名',
                prop: 'alipayName',
                type: 'input',
                isSearch: true
            },
            {
                label: '提现申请金额',
                prop: 'takeAmount',
            },
            {
                label: '账户类型',
                prop: 'payType',
                type: 'dict',
                dict: pay_type,
                isSearch: true,
            },
            {
                label: '申请时间',
                prop: 'createTime',
                type: 'date',
                isSearch: true,
                keys: ['start', 'end'],
            },
            {
                label: '数据情况',
                prop: 'isPay',
                type: 'dict',
                dict: is_pay,
                isSearch: true,
            },
            {
                label: '审核状态',
                prop: 'appStatus',
                type: 'dict',
                dict: volunteer_app_status,
                isSearch: true,
            }
        ]),
        paymentColumn: ref([
            {
                label: '打款单单号',
                prop: 'paymentOrderNumber',
                type: 'input',
                isSearch: true
            },
            {
                label: '打款单总金额',
                prop: 'totalPaymentAmount',
                type: 'input',
                isSearch: true
            },
            {
                label: '实际打款金额',
                prop: 'actualPaymentAmount',
                type: 'input',
                isSearch: true
            },
            {
                label: '验证状态',
                prop: 'isVerified',
                type: 'dict',
                dict: is_verified,
                isSearch: true
            },
            {
                label: '打款状态',
                prop: 'paymentStatus',
                type: 'dict',
                dict: payment_status,
                isSearch: true
            },
            {
                label: '打款结果',
                prop: 'appStatus',
                type: 'render',
                render:(row) => {
					console.log("TCL: exportFile -> row", row)
                    return `成功：${row.successfulPaymentAmount}; 失败：${row.failedPaymentAmount}`
                }
            },
            {
                label: '生成时间',
                prop: 'createTime',
                type: 'date',
                isSearch: true,
                keys: ['createTimeStart', 'createTimeEnd'],
            },
            {
                label: '打款时间',
                prop: 'paymentTime',
                type: 'date',
                isSearch: true,
                keys: ['paymentTimeStart', 'paymentTimeEnd'],
            },
        ]),
        dialogColumn:ref([
            {
                label: '业务编码',
                prop: 'takeSn',
                type: 'input',
            },
            {
                label: '用户信息',
                prop: 'alipayName',
                type: 'input',
            },
            {
                label: '提现金额',
                prop: 'receiveAmount',
            },
            {
                label: '扣除的税额',
                prop: 'taxAmount',
            },
            {
                label: '应打款金额',
                prop: 'shoudAmount',
            },
            {
                label: '实际打款金额',
                prop: 'shoudAmount',
            },
        ]),
        dialogData: {
            title: '结算申请',
            column: [
                {
                    label: '支付宝账号：',
                    prop: 'alipayAccountNo',
                    type: 'text',
                },
                {
                    label: '支付宝户名：',
                    prop: 'alipayName',
                    type: 'text',
                },
                {
                    label: '提现申请金额：',
                    prop: 'takeAmount',
                    type: 'text',
                },
                {
                    label: '申请时间：',
                    prop: 'createTime',
                    type: 'text',
                },
                {
                    label: '审核状态：',
                    prop: 'appStatus',
                    type: 'radio',
                    rules: [
                        { required: true, message: '请选择审核状态', trigger: 'blur' }
                    ],

                    options: [
                        {
                            label: '通过',
                            value: '2'
                        },
                        {
                            label: '不通过',
                            value: '3'
                        }
                    ]
                },
                {
                    label: '驳回原因：',
                    prop: 'rejectReason',
                    type: 'textarea',
                    show: (form) => {
                        console.log('驳回原因', form);
                        return form.appStatus === '3'
                    }
                },
            ]
        },
        searchBtns: [
            {
                label: '创建打款单',
                func: () => {
                    const ids = userTableRef.value.ids;
                    console.log('批量删除', ids)
                    ids.length > 0 && paymentSubmit(ids)
                },
                key: 'applicant',
                type: 'primary',
                show: (row) => {
                    return tabkey.value !== '4'
                }
            },
        ],
        scopeBtns: [
            {
                label: '审核',
                type: 'primary',
                key: 'examine',
                func: (row) => {
                    console.log(row)
                    openDialog(row, 'examine')
                },
                show: (row) => {
                    
                    return row.appStatus === '1'
                }
            },
            {
                label: '查看详情',
                type: 'primary',
                key: 'details',
                func: (row) => {
                    console.log(row)
                    openDialog(row, 'details')
                },
                show: (row) => {
                    return tabkey.value !== '4'
                }
            },
            {
                label: '打款验证',
                type: 'primary',
                key: 'details',
                func: async(row) => {
                    console.log(row)
                    dialogRow.value = row;
                    dialogVerify.value = true;
                    
                },
                show: (row) => {
                    return tabkey.value === '4' && row.paymentStatus === '1'
                }
            },
            {
                label: '创建打款单',
                type: 'primary',
                key: 'details',
                func: (row) => {
                    console.log(row)
                    paymentSubmit([row.volunteerTakeRecordId])
                },
                show: (row) => {
                    return tabkey.value === '' && row.appStatus === '2'
                }
            },
            {
                label: '查看打款结果',
                type: 'primary',
                key: 'see',
                func: (row) => {
					console.log("TCL: exportFile -> row", row)
                    dialogPlay.value = true;
                    dialogRow.value = row;
                },
                show: (row) => {
                    return tabkey.value === '4'
                }
            },
        ],
        dialogVerifyData: ref({
            title: '结算申请',
            column: [
                {
                    label: '打款id',
                    prop: 'volunteerPaymentRecordsId',
                    type: 'text',
                },
                {
                    label: '打款单单号',
                    prop: 'paymentOrderNumber',
                    type: 'text',
                },
                {
                    label: '打款方式',
                    prop: 'payType',
                    type: 'dict',
                    dict: pay_type
                },
                {
                    label: '打款验证密码',
                    prop: 'payPassword',
                    type: 'input',
                    dese:'发送验证码',
                    deseClick:(data)=>{
						console.log("TCL: exportFile -> data", data)
                    }
                },
            ]
        }),

    }
}