<template>
    <!-- 分销设置 -->
    <div class="distributionDetailIdx">
        <s-header name="分销设置" :noback="false"></s-header>
        <div class="cust_vantBorder">
            <div class="kBordBott">
                <van-field disabled colon :border="false" v-model="cofficentForm.terminalNo" clearable label-width="110"
                    name="terminalNo" label="终端编号" />
                <div class="l-flex-RC o-p-5 c-text-13 c-text-b">
                    <div v-if="proportionCheck"
                        style="padding: var(--van-cell-vertical-padding) var(--van-cell-horizontal-padding);">
                        {{ $t('distributionSet.addDist.pendingRecord') }}
                    </div>
                    <div v-else style="padding: var(--van-cell-vertical-padding) var(--van-cell-horizontal-padding);">
                        {{ $t('distributionSet.addDist.distInof') }}
                    </div>
                </div>
            </div>
            <div v-if="proportionCheck">
                <div class="l-flex-RC"
                    style="padding: var(--van-cell-vertical-padding) var(--van-cell-horizontal-padding);">
                    <div class="c-text-13">
                        &nbsp;&nbsp;手续费比例：
                    </div>
                    <div class="c-text-14 c-text-b c-text-color">{{ proportionCheck.proportion }}%</div>
                </div>
                <div class="l-flex-RC"
                    style="padding: var(--van-cell-vertical-padding) var(--van-cell-horizontal-padding);">
                    <div class="c-text-13">
                        &nbsp;&nbsp;{{ $t('distributionSet.addDist.myDistProport') }}：
                    </div>
                    <div class="c-text-14 c-text-b c-text-color">{{ proportionCheck.adminProportion }}%</div>
                </div>
                <div v-if="proportionCheck.agencyId" class="l-flex-RC"
                    style="padding: var(--van-cell-vertical-padding) var(--van-cell-horizontal-padding);">
                    <div class="l-flex-RC o-pr-20">
                        <div class="c-text-13">
                            &nbsp;&nbsp;{{ $t('device.accountNoOfDistributorLabel') }}：
                        </div>
                        <div class="c-text-14 c-text-b c-text-color">{{ proportionCheck.agencyName }}</div>
                    </div>
                    <div class="l-flex-RC">
                        <div class="c-text-13">
                            &nbsp;&nbsp;{{ $t('device.distributionProportionLabel') }}：
                        </div>
                        <div class="c-text-14 c-text-b c-text-color">{{ proportionCheck.agencyProportion }}%</div>
                    </div>
                </div>
                <div v-if="proportionCheck.merchantId" class="l-flex-RC"
                    style="padding: var(--van-cell-vertical-padding) var(--van-cell-horizontal-padding);">
                    <div class="l-flex-RC o-pr-20">
                        <div class="c-text-13">
                            &nbsp;&nbsp;{{ $t('device.accountNoOfDistributorLabel') }}：
                        </div>
                        <div class="c-text-14 c-text-b c-text-color">{{ proportionCheck.merchantName }}</div>
                    </div>
                    <div class="l-flex-RC">
                        <div class="c-text-13">
                            &nbsp;&nbsp;{{ $t('device.distributionProportionLabel') }}：
                        </div>
                        <div class="c-text-14 c-text-b c-text-color">{{ proportionCheck.merchantProportion }}%</div>
                    </div>
                </div>
                <div v-if="proportionCheck.personageId" class="l-flex-RC"
                    style="padding: var(--van-cell-vertical-padding) var(--van-cell-horizontal-padding);">
                    <div class="l-flex-RC o-pr-20">
                        <div class="c-text-13">
                            &nbsp;&nbsp;{{ $t('device.accountNoOfDistributorLabel') }}：
                        </div>
                        <div class="c-text-14 c-text-b c-text-color">{{ proportionCheck.personageName }}</div>
                    </div>
                    <div class="l-flex-RC">
                        <div class="c-text-13">
                            &nbsp;&nbsp;{{ $t('device.distributionProportionLabel') }}：
                        </div>
                        <div class="c-text-14 c-text-b c-text-color">{{ proportionCheck.personageProportion }}%</div>
                    </div>
                </div>
                <div style="margin: 50px;">
                    <van-button round block type="primary" @click="cancelDistri(proportionCheck.id)">
                        {{ $t('device.cancelForApproval') }}
                    </van-button>
                </div>
            </div>
            <div v-else>
                <van-form show-error-message @submit="onSubmit">
                    <div class="noPaddingTopCell l-flex-RC">
                        <div class="c-text-13 c-text-b c-text-color" style="padding: 15px">
                            &nbsp;&nbsp;手续费比例:
                        </div>
                        <div class="c-text-13 c-text-b c-text-color">{{ cofficentForm.distProp }}%</div>
                    </div>
                    <div class="l-flex-RC">
                        <div class="c-text-13 c-text-b c-text-color" style="padding: 15px">
                            &nbsp;&nbsp;{{ $t('distributionSet.addDist.myDistProport') }}:
                        </div>
                        <div class="c-text-13 c-text-b c-text-color">{{ myDistProp }}%</div>
                    </div>
                    <div v-for="(item, index) in distPropList" :key="index" class="kBordBott">
                        <van-field colon :border="false" required v-model="item.name1" clearable label-width="110"
                            name="name1" :label="$t('device.accountNoOfDistributorLabel')"
                            :placeholder="$t('device.accountNoOfDistributorPlaceholder')"
                            :rules="[{ required: true, message: $t('device.accountNoOfDistributorPlaceholder') }]" />
                        <div class="l-flex-between noPaddingRCell">
                            <div class="l-flex-RC">
                                <van-field type="digit" colon :border="false" required v-model="item.name2" clearable
                                    label-width="110" name="name2" :label="$t('device.distributionProportionLabel')"
                                    :placeholder="$t('device.distributionProportionPlaceholder')"
                                    @update:model-value="checkRatio(index)"
                                    :rules="[{ required: true, message: $t('device.distributionProportionPlaceholder') }, { required: true, validator: distPropVali, message: $t('distributionSet.addDist.distPropRange'), trigger: ['onChange', 'onBlur', 'onSubmit'] }]" />
                                <span class="o-pl-10 c-text-18 c-text-b" style="color: #434D74;">%</span>
                            </div>
                            <div @click="toDele(index)" class="l-flex-RC" style="color: #FE5D55;">
                                <van-icon size="18" name="delete-o" />
                                <span class="c-text-12">{{ $t('device.delete') }}</span>
                            </div>
                        </div>
                    </div>
                    <div v-if="distPropList.length <= 2" @click="toAdd"
                        class="kBordBott l-flex-center o-ptb-20 c-text-14 c-text-w6">
                        +{{ $t('device.continueToAddDistributors') }}
                    </div>
                    <div style="margin: 50px;">
                        <van-button round block type="primary" native-type="submit">
                            {{ $t('device.submitForApproval') }}
                        </van-button>
                    </div>
                </van-form>
            </div>
        </div>
    </div>
</template>
<script>
import sHeader from "../../../components/SimpleHeader.vue";
import { onMounted, reactive, computed, ref } from "vue";
import { getTerminalProportion, submitProportion, getProportionCheck, checkProportion } from "../../../service/terminal";
import { useRoute, useRouter } from "vue-router";
import { showFailToast, showNotify, showSuccessToast, showConfirmDialog } from "vant";
import { getLoginUser } from "@/common/js/utils";

export default {
    components: {
        sHeader
    },
    setup() {
        const user = getLoginUser();
        const route = useRoute();
        const router = useRouter();
        const cofficentForm = reactive({
            terminalNo: '',
            distProp: 1,
        });
        // 分销人列表
        const distPropList = reactive([]);
        // 待审核记录
        const proportionCheck = ref({});
        // 获取是否有待审核记录
        const getCheckPending = async () => {
            const { data } = await getProportionCheck({ terminalId: route.query.terminalId });
            if (data.code === '00000') {
                // 存在审核记录，则不能再提交
                proportionCheck.value = data.data;
            }
        }
        // 获取分销比例
        const getProportion = async () => {
            const { data } = await getTerminalProportion(
                Object.assign({}, { terminalId: route.query.terminalId })
            );
            if (data.code === "00000") {
                cofficentForm.clientId = data.data.clientId;
                cofficentForm.distProp = data.data.proportion;
                // 存在第一个分销人账号和分销比，填充
                if (data.data.agencyId && data.data.agencyProportion !== '') {
                    distPropList[0] = {};
                    distPropList[0]['name1'] = data.data.agencyId;
                    distPropList[0]['name2'] = data.data.agencyProportion;
                }// 存在第二个分销人账号和分销比，填充
                if (data.data.merchantId && data.data.merchantProportion !== '') {
                    distPropList[1] = {};
                    distPropList[1]['name1'] = data.data.merchantId;
                    distPropList[1]['name2'] = data.data.merchantProportion;
                }// 存在第三个分销人账号和分销比，填充
                if (data.data.personageId && data.data.personageProportion !== '') {
                    distPropList[2] = {};
                    distPropList[2]['name1'] = data.data.personageId;
                    distPropList[2]['name2'] = data.data.personageProportion;
                }
            }

        };
        // 我的分销比例
        const myDistProp = computed(() => {
            // 计算出分销人的总分销
            const totalProp = distPropList.reduce((pre, cur) => {
                return Number(cur.name2 || 0) + pre;
            }, 0);
            const scaleValue = (100 - Number(cofficentForm.distProp || 0) - Number(totalProp));
            return scaleValue;
        });
        // 点击添加分销人
        const toAdd = () => {
            distPropList.push({
                name1: '',
                name2: ''
            })
        }
        // 点击删除
        const toDele = (idx) => {
            distPropList.splice(idx, 1);
        }
        // 分销比例规则
        const distPropVali = (val) => /^(?:[1-9]|[1-9]\d)$/.test(val);
        // 校验填写比例
        const checkRatio = (index) => {
            console.log(index);
            if (myDistProp.value < 0) {
                distPropList[index]['name2'] = 0;
                showNotify({
                    message: "分销总比例不能大于100",
                    duration: 2000,
                    background: '#f0ad4e',
                });
            }
        }
        // 提交
        const onSubmit = async () => {
            let param = {
                adminId: user.id,
                terminalId: route.query.terminalId,
                terminalNo: cofficentForm.terminalNo,
                type: distPropList.length + 1,
                proportion: cofficentForm.distProp,
                agencyName: distPropList[0] ? distPropList[0]['name1'] : '',
                merchantName: distPropList[1] ? distPropList[1]['name1'] : '',
                personageName: distPropList[2] ? distPropList[2]['name1'] : '',
                agencyProportion: distPropList[0] ? distPropList[0]['name2'] : '',
                merchantProportion: distPropList[1] ? distPropList[1]['name2'] : '',
                personageProportion: distPropList[2] ? distPropList[2]['name2'] : '',
                adminProportion: myDistProp.value,
            }
            const { data } = await submitProportion(
                Object.assign({}, param)
            );
            if (data.code === "00000") {
                showSuccessToast("提交成功");
                setTimeout(() => {
                    router.go(0);
                }, 500);
            } else {
                showFailToast(data.message);
            }
        }
        // 撤销审核
        const cancelDistri = async (value) => {
            showConfirmDialog({
                title: '提醒',
                message: '确认撤销此条分销申请吗？',
            }).then(async () => {
                const { data } = await checkProportion({ id: value, status: 2 });
                if (data.code == "00000") {
                    showSuccessToast('撤销成功');
                    setTimeout(() => {
                        router.go(0);
                    }, 1000);
                } else {
                    showFailToast(data.message);
                }
            }).catch((error) => {
                console.error(error);
            })
        }
        onMounted(async () => {
            cofficentForm.terminalNo = route.query.terminalNo;
            getProportion();
            getCheckPending();
        });
        return {
            cofficentForm,
            distPropList,
            myDistProp,
            toAdd,
            toDele,
            distPropVali,
            checkRatio,
            onSubmit,
            proportionCheck,
            cancelDistri
        };
    }
};
</script>
<style lang="less" scoped>
@import "../../../common/style/common.less";

.distributionSetIdx {
    .van-tabs--line .van-tabs__wrap {
        height: 30px;
    }

    .van-pull-refresh {
        height: calc(100vh - 120px);
        overflow: auto;
    }

    .headCon {
        .leftImg {
            width: 19px;
            height: 19px;
            background: url('../../../assets/distributionSet/leftIcon.png') top center no-repeat;
            background-size: 100%;
        }

        .leftTxt {
            color: #434d74;

            .leftNum {
                padding-left: 5px;
                color: #df5e4c;
            }
        }

        .rightCon {
            color: #4d6add;
        }
    }

    .van-tabs__line {
        background-color: #4d6add !important;
    }

    .van-tab--active .van-tab__text--ellipsis {
        color: #4d6add;
    }

    .contentCon {
        height: calc(100% - 120px);

        .content {
            margin-top: 6px;

            .titleName {
                color: #8787a6;
            }

            .valueName {
                color: #404d74;
            }

            .valueName1 {
                width: 90px;
                display: inline-block;
            }

            .effective {
                color: #4dc193;
            }

            .cancel {
                color: #f5b33a;
            }

            .rejected {
                color: #df5e4c;
            }
        }

        .approval {
            color: #f5b33a;
        }

        .cancelBtn {
            height: 25px;
            padding: 0 5px;
        }
    }
}

.distributionDetailIdx {
    overflow: auto;

    .kBordBott {
        color: #404d74;
    }

    .noPaddingTopCell {
        .van-cell {
            padding-right: 0;
            width: 250px;
        }
    }

    .noPaddingRCell {
        padding-right: var(--van-cell-horizontal-padding);

        .van-cell {
            padding-right: 0;
            width: 250px;
        }
    }

    .van-button--primary {
        border-color: #4d6add;
        background-color: #4d6add;
    }
}
</style>