<template>
    <!--新增履约模板-->
    <Drawer :title="`${isUpdate() ? '修改' : '新增'}履约模板`" :placement="'right'" :visible="visible" @cancel="cancel" :class="[position === 'top' ? 'top600' : 'delistingBottom']">
        <a-spin :spinning="loading">
            <div class="listed">
                <a-form class="inlineForm dialogForm" ref="formRef" :model="formState" :rules="rules">
                    <div class="formBar">
                        <a-row :gutter="24">
                            <a-col :span="24">
                                <a-form-item label="模版名称" name="name">
                                    <a-input class="commonInput" v-model:value="formState.name" placeholder="请输入模版名称" style="width: 260px" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row class="tableTitle">
                            <a-col :span="7">步骤类型</a-col>
                            <a-col :span="6">步骤值（%）</a-col>
                            <a-col :span="7">距离上一步天数</a-col>
                            <a-col :span="4">操作</a-col>
                        </a-row>
                        <a-row class="tableContent" v-for="(parent, index) in formState.domains" :key="parent">
                            <a-col :span="7">
                                <a-form-item :name="['domains', index, 'steptypeid']" :rules="rules.domains.steptypeid">
                                    <a-select class="inlineFormSelect dialogTableSelect" style="width: 158px" placeholder="请选择" @change="stepTypeChange(parent)" v-model:value="parent.steptypeid">
                                        <a-select-option v-for="item in list" :key="item.steptypeid" :value="item.steptypeid">{{ item.steptypename }} </a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item :name="['domains', index, 'stepvalue']" :rules="rules.domains.stepvalue">
                                    <a-input-number class="commonInput dialogTableInput" :disabled="isSummary(parent)" :max="100" style="width: 135px" type="number" v-model:value="parent.stepvalue"></a-input-number>
                                </a-form-item>
                            </a-col>
                            <a-col :span="7">
                                <a-form-item :name="['domains', index, 'stepdays']" :rules="rules.domains.stepdays">
                                    <a-input-number class="commonInput dialogTableInput" style="width: 157px" type="number" v-model:value="parent.stepdays"></a-input-number>
                                </a-form-item>
                            </a-col>
                            <a-col :span="4">
                                <svg class="icon svg-icon" @click="deleteTemp(index)" v-if="showDeleteTemp(index)" aria-hidden="true">
                                    <use xlink:href="#icon-shanchu" />
                                </svg>
                                <PlusCircleOutlined v-if="showAddTempBtn(index)" @click="addTemp()" />
                            </a-col>
                        </a-row>
                        <div class="noticeTip">
                            <div>注意事项：</div>
                            <div>1、买方支付汇总值必须为100%；</div>
                            <div>2、卖方收款汇总值必须为100%；</div>
                            <div>3、配置卖方收款之前要有买方支付，且其值不能多于买方支付的值。</div>
                        </div>
                    </div>
                    <a-row :gutter="24">
                        <a-col :span="24" class="fixedBtns">
                            <a-form-item class="btnCenter">
                                <a-button class="listedBtn" @click="submit">确定</a-button>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>
            </div>
        </a-spin>
    </Drawer>
</template>

<script lang="ts">
import { Des } from '@/common/components/commonDes';
import Drawer from '@/common/components/drawer/index.vue';
import { requestResultLoadingAndInfo } from '@/common/methods/request/resultInfo';
import { validateAction } from '@/common/setup/form';
import { _closeModal } from '@/common/setup/modal/modal';
import { useQueryData } from '@/common/setup/request';
import { getUserId } from '@/services/bus/user';
import { geLoginID_number } from '@/services/bus/login';
import { queryWrPerformanceStepType } from '@/services/go/wrtrade';
import { QueryPermancePlanTmpRsp, QueryWrPerformanceStepTypeRsp } from '@/services/go/wrtrade/interface';
import { addPerformanceTemp } from '@/services/proto/performance';
import { AddPerformanceTemp, PerfomanceStempTempInfo } from '@/services/proto/performance/interface';
import { MinusOutlined, PlusCircleOutlined, PlusOutlined, SearchOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { defineComponent, PropType, reactive, Ref, ref, UnwrapRef } from 'vue';
import { PermanceTemp, PermanceTempForm } from './interface';

// 初始化 模板
const initTemp = (): PermanceTemp => {
    return { steptypeid: undefined, stepindex: 1, stepvalue: null, isauto: 0, remark: '', stepdays: null, steptypename: '' };
};

// 新增 模板
const useAddTemp = (formState: UnwrapRef<PermanceTempForm>) => {
    function addTemp() {
        const temp = initTemp();
        formState.domains.push(temp);
    }
    function showAddTempBtn(index: number) {
        return index === formState.domains.length - 1;
    }
    return { addTemp, showAddTempBtn };
};

// 删除 模板
const useDeleteTemp = (formState: UnwrapRef<PermanceTempForm>) => {
    function deleteTemp(index: number) {
        formState.domains.splice(index, 1);
    }
    function showDeleteTemp(index: number) {
        return index !== 0;
    }
    return { deleteTemp, showDeleteTemp };
};

// 编辑 模板
const useEditeTemp = (typeList: Ref<QueryWrPerformanceStepTypeRsp[]>) => {
    function findTemp(item: PermanceTemp) {
        return typeList.value.find((el) => el.steptypeid === item.steptypeid);
    }
    // 汇总
    function isSummary({ steptypename }: PermanceTemp) {
        return steptypename === '买方支付' || steptypename === '卖方收款' ? false : true;
    }
    // 切换步骤类型
    function stepTypeChange(item: PermanceTemp) {
        const stepType = findTemp(item)!;
        item.steptypename = stepType.steptypename;
        item.stepvalue = null;
        // 卖方收款汇总值必须为100%；
        // if (!isSummary(item)) {
        //     item.stepvalue = 100;
        // }
    }
    // function isDisable(temp: PermanceTemp) {
    //     const { steptypename } = findTemp(temp)!;
    //     return steptypename === '买方支付' || steptypename === '卖方收款';
    // }
    return { isSummary, stepTypeChange };
};

// 表单
const userForm = (selectedRow: QueryPermancePlanTmpRsp) => {
    const formRef = ref();
    const formState: UnwrapRef<PermanceTempForm> = reactive({ domains: [initTemp()], name: '' });
    function isUpdate() {
        return !!selectedRow.autoid;
    }
    if (isUpdate()) {
        // 有值代表 修改,无值是新增
        formState.name = selectedRow.templatename;
        formState.domains = selectedRow.LstStep.map((el) => {
            const stepvalue = el.stepvalue ? +(el.stepvalue * 100).toFixed(0) : el.stepvalue;
            return { ...el, stepvalue };
        });
    }
    const findIndex = (name: string): number => formState.domains.findIndex((temp) => temp.steptypename === name);
    const total = (name: string): number =>
        formState.domains
            .filter((temp) => temp.steptypename === name)
            .reduce((acc, cur) => {
                const { stepvalue } = cur;
                return stepvalue ? acc + stepvalue : acc;
            }, 0);
    // 配置卖方收款之前要有买方支付
    function validateSepeTypeId(value: any) {
        const sellIndex = findIndex('卖方收款');
        if (sellIndex !== -1) {
            const buyIndex = findIndex('买方支付');
            if (buyIndex > sellIndex) {
                return Promise.reject('配置卖方收款之前要有买方支付');
            }
        }
        return Promise.resolve();
    }

    function validateStepValue(rule: any, value: number) {
        if (rule.field) {
            const arr = rule.fullField.split('.');
            if (Array.isArray(arr) && arr.length === 3) {
                const index = +arr[1];
                const item = formState.domains[index];
                const steptypename = item.steptypename;
                if (steptypename === '买方支付' || steptypename === '卖方收款') {
                    if (!value) {
                        return Promise.reject('请输入步骤值');
                    }
                    const buyTotal = total('买方支付');
                    const sellTotal = total('卖方收款');
                    if (findIndex('买方支付') !== -1) {
                        if (buyTotal !== 100) {
                            return Promise.reject('买方支付汇总值必须为100%');
                        }
                    }
                    if (findIndex('卖方收款') !== -1) {
                        if (sellTotal !== 100) {
                            return Promise.reject('卖方收款汇总值必须为100%');
                        }
                    }

                    if (sellTotal > buyTotal) {
                        return Promise.reject('卖方收款不能多于买方付款');
                    }
                }
            }
        }

        return Promise.resolve();
    }
    const rules = {
        name: { required: true, message: '请输入模版名称', trigger: 'blur' },
        domains: {
            steptypeid: [
                { required: true, message: '请选择步骤类型' },
                { required: true, validator: validateSepeTypeId },
            ],
            stepvalue: [
                // { required: true, message: '请输入步骤值', trigger: 'blur', type: 'number' },
                { required: true, validator: validateStepValue, type: 'number' },
            ],
            stepdays: { required: true, message: '请输入距离上一步天数', trigger: 'blur', type: 'number' },
        },
    };

    return { formRef, formState, rules, isUpdate, findIndex };
};

export default defineComponent({
    emits: ['cancel', 'update'],
    name: 'warehouse_receipt_trade_blocs_delisting',
    props: {
        selectedRow: {
            type: Object as PropType<QueryPermancePlanTmpRsp>,
            default: {},
        },
        position: {
            type: String,
            default: 'top',
        },
    },
    components: { Des, Drawer, PlusOutlined, MinusOutlined, SearchOutlined, PlusCircleOutlined },
    setup(props, context) {
        const { visible, cancel } = _closeModal(context);
        const loading = ref<boolean>(false);
        // 步骤类型
        const { list } = useQueryData<QueryWrPerformanceStepTypeRsp>(queryWrPerformanceStepType);
        const { formRef, formState, rules, isUpdate, findIndex } = userForm(props.selectedRow);

        function submit() {
            validateAction<PermanceTempForm>(formRef, formState).then((res) => {
                if (findIndex('仓单转移') == -1) {
                    message.error('未配置仓单转移步骤');
                    return;
                }
                const performancesteps: PerfomanceStempTempInfo[] = res.domains.map((el, i) => {
                    const { steptypeid, stepvalue, stepdays, remark } = el;
                    return {
                        steptypeid: steptypeid as number,
                        stepvalue: stepvalue as number,
                        stepdays: stepdays as number,
                        isauto: 1,
                        remark,
                        stepindex: i + 1,
                    };
                });
                const param: AddPerformanceTemp = {
                    autoid: isUpdate() ? props.selectedRow.autoid : 0,
                    templatename: res.name,
                    userid: getUserId(),
                    performancesteps,
                    creatorid: geLoginID_number()!,
                };
                const msg: [string, string] = isUpdate() ? ['修改履约模板成功', '修改履约模板失败:'] : ['新增履约模板成功', '新增履约模板失败:'];
                requestResultLoadingAndInfo(addPerformanceTemp, param, loading, msg).then(() => {
                    cancel(true);
                });
            });
        }
        return {
            loading,
            list,
            formRef,
            formState,
            rules,
            submit,
            ...useAddTemp(formState),
            ...useDeleteTemp(formState),
            ...useEditeTemp(list),
            cancel,
            visible,
            isUpdate,
        };
    },
});
</script>

<style lang="less" scoped>
.listed {
    padding: 18px 10px 0;
    .formBar {
        height: calc(100% - 70px);
        padding: 0;
        .ant-row.tableTitle {
            .ant-col {
                height: 40px;
                line-height: 40px;
                white-space: nowrap;
                text-align: center;
                color: @m-grey1;
                font-size: 14px;
                border-right: 1px solid @m-black6;
                border-top: 1px solid @m-black6;
                border-bottom: 1px solid @m-black6;
            }
            .ant-col:first-child {
                border-left: 1px solid @m-black6;
            }
        }
        .ant-row.tableContent {
            .ant-col {
                // height: 40px;
                line-height: 40px;
                text-align: center;
                border-right: 1px solid @m-black6;
                border-bottom: 1px solid @m-black6;
                .icon {
                    color: @m-yellow8;
                    font-size: 20px;
                    cursor: pointer;
                }
                .anticon {
                    font-size: 20px;
                    color: @m-blue0;
                    margin-left: 14px;
                    cursor: pointer;
                }
            }
            .ant-col:first-child {
                border-left: 1px solid @m-black6;
            }
        }
        .noticeTip {
            width: 100%;
            margin-top: 15px;
            .flex;
            flex-direction: column;
            > div {
                height: 30px;
                line-height: 30px;
                font-size: 14px;
                color: @m-grey1;
            }
        }
    }
    .ant-form.inlineForm {
        .ant-row.ant-form-item {
            margin-bottom: 5px;
        }
        .ant-row.ant-form-item.ant-form-item-with-help {
            white-space: nowrap;
            margin-left: 2px;
        }
    }
    .dialogTableSelect,
    .dialogTableInput {
        margin-left: 2px;
    }
}
</style>