<template>
    <div>
        <el-form :model="form" :rules="rules" ref="ruleForm">
            <el-form-item label="所属分部" prop="organId" :label-width="formLabelWidth">
                <el-select v-model.trim="form.organId" :disabled="formActionTitle === 'update'" placeholder="请选择所属分部">
                    <el-option
                    v-for="item in selects.branchs"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-row :gutter="10" v-for="(service, index) in form.serviceList" :key="index + 1000">
                <el-col :span="9">
                    <el-form-item :label-width="formLabelWidth" :label="`服务收入${index + 1}`" :prop="'serviceList.' + index + '.feeType'" :rules="[{ required: true, message: '请选择收费方式', trigger: 'change' }]">
                    <el-select
                        v-model.trim="service.feeType"
                        placeholder="请选择收费方式"
                        style="width: 100% !important;"
                        disabled
                    >
                        <el-option value="SERVICE" label="服务收入"></el-option>
                        <el-option value="SELL" label="销售收入"></el-option>
                    </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item :prop="'serviceList.' + index + '.organId'" :rules="[
                    { required: true, message: '请选择分润分部', trigger: 'change' },
                    ]">
                    <el-select
                        v-model.trim="service.organId"
                        placeholder="分润分部"
                        clearable
                    >
                        <el-option
                        v-for="(item, index) in calcBranchList"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                        :disabled="item.disabled"
                        ></el-option>
                    </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item :prop="'serviceList.' + index + '.scale'" :rules="[
                        { required: true, validator: validSale, trigger: 'blur, change' },
                        { required: true, message: '比例必须为数字值', trigger: 'blur, change' }
                    ]">
                        <el-input
                            type="number"
                            min="0"
                            max="100"
                            placeholder="分润比例"
                            @mousewheel.native.prevent
                            v-model.number="service.scale"
                        >
                            <i slot="suffix">%</i>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-button icon="el-icon-plus" @click="onAddDomain('SERVICE')" circle></el-button>
                    <el-button icon="el-icon-minus" :disabled="form.serviceList.length <= 1" @click="onRemoveDomain('SERVICE', service)" circle type="danger"></el-button>
                </el-col>
            </el-row>
            <el-divider></el-divider>
            <el-row :gutter="10" v-for="(domain, index) in form.sellList" :key="index">
                <el-col :span="9">
                    <el-form-item :label-width="formLabelWidth" :label="`销售收入${index + 1}`" :prop="'sellList.' + index + '.feeType'" :rules="[
                    { required: true, message: '请选择收费方式', trigger: 'change' },
                    ]">
                    <el-select
                        v-model.trim="domain.feeType"
                        placeholder="请选择收费方式"
                        style="width: 100% !important;"
                        disabled
                    >
                        <el-option value="SERVICE" label="服务收入"></el-option>
                        <el-option value="SELL" label="销售收入"></el-option>
                    </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item :prop="'sellList.' + index + '.organId'" :rules="[
                    { required: true, message: '请选择分润分部', trigger: 'change' },
                    ]">
                    <el-select
                        v-model.trim="domain.organId"
                        placeholder="分润分部"
                        clearable
                    >
                        <el-option
                        v-for="(item, index) in calcBranchList"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                        :disabled="item.disabled"
                        ></el-option>
                    </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item :prop="'sellList.' + index + '.scale'" :rules="[
                        { required: true, validator: validSale, trigger: 'blur, change' },
                        { required: true, message: '比例必须为数字值', trigger: 'blur, change' }
                    ]">
                        <el-input
                            type="number"
                            v-number
                            min="0"
                            max="100"
                            placeholder="分润比例"
                            @mousewheel.native.prevent
                            v-model.number="domain.scale"
                        >
                            <i slot="suffix">%</i>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-button icon="el-icon-plus" @click="onAddDomain('SELL')" circle></el-button>
                    <el-button icon="el-icon-minus" :disabled="form.sellList.length <= 1" @click="onRemoveDomain('SELL', domain)" circle type="danger"></el-button>
                </el-col>
            </el-row>
        </el-form>

        <span slot="footer" class="dialog-footer">
            <el-button @click="close">取 消</el-button>
            <el-button @click="onChargeSubmit('ruleForm')" type="primary">确 定</el-button>
        </span>
    </div>
</template>

<script>
import { getPaymentConfigs, addTypeRoute, updateTypeRoute } from "./api";
import cleanDeep from 'clean-deep'
const validSale = (rule, value, callback) => {
  if (value != 0 && typeof value === 'string') {
    callback(new Error("请输入分润比例"));
  } else if (value < 0) {
    callback(new Error("分润比例不能小于0"));
  } else if (value > 101) {
    callback(new Error("分润比例不能大于100"));
  } else {
    callback();
  }
};
export default {
    props:['detail', 'close', 'getList', 'formActionTitle'],
    data() {
        return {
            formLabelWidth: "100px",
            form: {
                id: null,
                organId: null,
                serviceList: [{
                    feeType: 'SERVICE',
                    organId: null,
                    scale: null,
                }],
                sellList: [{
                    feeType: 'SELL',
                    organId: null,
                    scale: null
                }]
            },
            validSale: validSale,
            rules: {
                organId: [
                    { required: true, message: "请选择所属分部", trigger: "change" }
                ]
            },
            calcBranchList: [], // 可选比例分部
        }
    },
    mounted() {
        this.getPaymentBranchList()
        let detail = this.detail
        if(detail && this.formActionTitle == 'update') {
            this.form = {
                id: detail.id,
                organId: detail.organId,
                serviceList: [],
                sellList: []
            }
            const routeScale = detail.typeRouteScale ? detail.typeRouteScale : []
            routeScale.forEach(item => {
                if(item.feeType === 'SERVICE') {
                    this.form.serviceList.push({
                        feeType: 'SERVICE',
                        organId: item.organId,
                        scale: item.scale,
                    })
                } else if(item.feeType === 'SELL') {
                    this.form.sellList.push({
                        feeType: 'SELL',
                        organId: item.organId,
                        scale: item.scale,
                    })
                }
            })
        }
    },
    methods: {
        onChargeSubmit(formName) {
            this.$refs[formName].validate(valid => {
                const form = this.form
                let serviceCount = 0
                form.serviceList.forEach(item => {
                    serviceCount += item.scale
                })
                if(Number(serviceCount.toFixed(5)) !== 100) {
                    this.$message.error('服务收入分润比例总和必须为100')
                    return
                }
                let sellCount = 0
                form.sellList.forEach(item => {
                    sellCount += item.scale
                })
                if(Number(sellCount.toFixed(5)) !== 100) {
                    this.$message.error('销售收入分润比例总和必须为100')
                    return
                }
                if (valid) {
                    const params = {
                        id: form.id,
                        organId: form.organId,
                        typeRouteScale: JSON.stringify((form.serviceList).concat(form.sellList))
                    }
                    if (this.formActionTitle == "create") {
                        addTypeRoute(cleanDeep(params)).then(res => {
                            this.messageTips("添加", res);
                        });
                    } else if (this.formActionTitle == "update") {
                        updateTypeRoute(cleanDeep(params)).then(res => {
                            this.messageTips("修改", res);
                        });
                    }
                } else {
                    return;
                }
            });
        },
        messageTips(title, res) {
            if (res.code == 200) {
                this.$message.success(title + "成功");
                this.chargeStatus = false;
                this.close()
                this.getList();
            } else {
                this.$message.error(res.msg);
            }
        },
        async getPaymentBranchList() {
            await getPaymentConfigs(cleanDeep({ payType: 'ADAPAY' })).then(res => {
                if (res.code == 200 && res.data) {
                    res.data.forEach(item => {
                        this.calcBranchList.push({
                            label: item.organName,
                            value: item.organId,
                            payType: item.payType
                        });
                    });
                }
            });
        },
        onAddDomain(type) { // 添加
            const tempObj = {
                organId: null,
                scale: null
            }
            if(type === 'SERVICE') {
                tempObj['feeType'] = 'SERVICE'
                this.form.serviceList.push(tempObj)
            } else if(type === 'SELL') {
                tempObj['feeType'] = 'SELL'
                this.form.sellList.push(tempObj)
            }

        },
        onRemoveDomain(type, item) { // 删除
            let form = this.form
            if(type === 'SERVICE') {
                const index = form.serviceList.indexOf(item)
                if (index !== -1) {
                    form.serviceList.splice(index, 1)
                }
            } else if(type === 'SELL') {
                const index = form.sellList.indexOf(item)
                if (index !== -1) {
                    form.sellList.splice(index, 1)
                }
            }
        }
    }
}
</script>

<style lang="less" scoped>
.dialog-footer{
    display: block;
    text-align: right;
    margin-top: 20px;
  }
</style>