<template>
    <div class="edit-view">
        <page-title :name="pageName"></page-title>
        <div class="edit-view__content-wrapper">
            <div class="edit-view__content-section">
                <divider />
                <el-form
                    :model="formData"
                    :rules="rules"
                    ref="form"
                    label-width="110px"
                    label-position="right"
                    size="small"
                    style="width: 900px;"
                    class="line"
                >
                    <el-form-item prop="type" label="type" v-if="!formData.type">
                        <el-select v-model="formData.type" clearable filterable placeholder="请选择">
                            <el-option
                                v-for="item in typeOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-row type="flex">
                        <el-col :span="12" :offset="0" v-if="formData.id">
                            <el-form-item prop="id" label="序号">
                                <el-input v-model="formData.id" disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="code" :label="`${formData.type === 'CLIENT' ? '客户' : '供应商'}代码`">
                                <el-input v-model="formData.code" placeholder="仅限大写字母，5字以内"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-form-item prop="name" label="个人/企业名称" class="input-pre-zh">
                        <el-input v-model="formData.name" placeholder="请输入中文名称">
                            <template #prepend>中</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item prop="enName" label="" class="input-pre-en">
                        <el-input v-model="formData.enName" placeholder="请输入英文名称">
                            <template #prepend>英</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item prop="address" label="注册地址" class="input-pre-zh">
                        <el-input v-model="formData.address" placeholder="请输入中文地址">
                            <template #prepend>中</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item prop="enAddress" label="" class="input-pre-en">
                        <el-input v-model="formData.enAddress" placeholder="请输入英文地址">
                            <template #prepend>英</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item prop="supplierType" label="供应商类型" v-if="formData.type === 'SUPPLIER'">
                        <el-select v-model="formData.supplierType" clearable filterable placeholder="请选择">
                            <el-option
                                v-for="item in supplierTypeOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="uscc" label="统一社会信用代码" class="input1">
                        <el-input v-model="formData.uscc" placeholder="请输入"></el-input>
                    </el-form-item>
                    <divider>
                        开票信息
                    </divider>
                    <el-row>
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="billingName" label="名称">
                                <el-input v-model="formData.billingName" placeholder="请输入"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="taxID" label="税号">
                                <el-input v-model="formData.taxID" placeholder="请输入"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="billingAddress" label="地址">
                                <el-input v-model="formData.billingAddress" placeholder="请输入"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="billingPhone" label="电话">
                                <el-input v-model="formData.billingPhone" placeholder="请输入"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="accountBank" label="开户行">
                                <el-input v-model="formData.accountBank" placeholder="请输入"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="account" label="账号">
                                <el-input v-model="formData.account" placeholder="请输入"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <divider>
                        指定对接人
                    </divider>

                    <div class="docking-list" v-for="(item, index) in showDockings" :key="index">
                        <div class="docking-name">对接人{{ getNum(index + 1) }}</div>
                        <docking-edit :info.sync="dockings[item.dockingsIndex]"></docking-edit>
                        <el-button @click="delDocking(item.dockingsIndex)" class="del" plain type="danger" size="small"
                            >删除</el-button
                        >
                    </div>
                    <el-form-item style="margin-bottom: 60px;">
                        <el-button type="primary" plain size="mini" @click="addDocking">新增</el-button>
                    </el-form-item>

                    <el-form-item class="form-submit">
                        <el-button @click="onSave" :loading="saving" size="default" type="primary">保存 </el-button>
                        <el-button @click="onDelete" :loading="saving" size="default" type="danger" v-if="formData.id"
                            >删除
                        </el-button>
                        <el-button @click="$router.go(-1)" size="default">取消</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>
<script>
import DockingEdit from '../components/DockingEdit.vue';
export default {
    name: 'PartnerEdit',
    created() {
        if (this.$route.query.id) {
            this.$http
                .get('partner/get/' + this.$route.query.id)
                .then(res => {
                    this.formData = res;
                })
                .catch(e => {
                    console.log(e);
                    this.$message.error(e.error);
                });

            this.$http
                .post(
                    '/docking/all',
                    {
                        query: {
                            partnerId: this.$route.query.id
                        }
                    },
                    { body: 'json' }
                )
                .then(res => {
                    this.dockings = res.content;
                });
        } else {
            this.addDocking();
        }
        this.$nextTick(() => {
            if (this.$route.query.type === 'CLIENT') {
                this.pageName = '客户管理编辑';
            } else {
                this.pageName = '供应商管理编辑';
            }
            this.formData.type = this.$route.query.type || '';
        });
    },
    data() {
        return {
            saving: false,
            formData: {},
            rules: {},
            typeOptions: [
                { label: '供应商', value: 'SUPPLIER' },
                { label: '经销商', value: 'CLIENT' }
            ],
            supplierTypeOptions: [
                { label: '境内', value: 'DOMESTIC' },
                { label: '境外', value: 'ABROAD' }
            ],
            pageName: '',
            dockings: []
        };
    },
    computed: {
        showDockings() {
            let dockings = [...this.dockings];
            return dockings
                .map((item, index) => {
                    return {
                        ...item,
                        dockingsIndex: index
                    };
                })
                .filter(item => {
                    return !item.del;
                });
        }
    },
    methods: {
        onSave() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    this.submit();
                } else {
                    return false;
                }
            });
        },
        submit() {
            let data = { ...this.formData };

            this.saving = true;
            this.$http
                .post('/partner/save', data, { body: 'json' })
                .then(res => {
                    let dockings = [...this.dockings];
                    dockings = dockings.map(item => {
                        return {
                            ...item,
                            partnerId: res.id
                        };
                    });

                    if (dockings.length > 0) {
                        return this.$http.post('/docking/batchSave', {
                            dockings: JSON.stringify(dockings)
                        });
                    } else {
                        return Promise.resolve();
                    }
                })
                .then(() => {
                    this.saving = false;
                    this.$message.success('成功');
                    this.$router.go(-1);
                })
                .catch(e => {
                    console.log(e);
                    this.saving = false;
                    this.$message.error(e.error);
                });
        },
        onDelete() {
            this.$alert('删除将无法恢复，确认要删除么？', '警告', { type: 'error' })
                .then(() => {
                    return this.$http.post(`/partner/del/${this.formData.id}`);
                })
                .then(() => {
                    this.$message.success('删除成功');
                    this.$router.go(-1);
                })
                .catch(e => {
                    if (e !== 'cancel') {
                        console.log(e);
                        this.$message.error((e || {}).error || '删除失败');
                    }
                });
        },
        getNum(num) {
            if (num < 10) {
                return '0' + num;
            } else {
                return num;
            }
        },
        addDocking() {
            let docking = {
                name: '',
                jobTitle: '',
                phone: '',
                email: ''
            };
            if (this.formData.id) {
                docking.partnerId = this.formData.id;
            }
            console.log(docking);
            this.dockings.push(docking);
        },
        delDocking(index) {
            let dockings = [...this.dockings];
            this.$alert('删除将无法恢复，确认要删除么？', '警告', { type: 'error' })
                .then(() => {
                    if (dockings[index].id) {
                        dockings[index] = { ...dockings[index], del: true };
                    } else {
                        dockings.splice(index, 1);
                    }
                    this.dockings = dockings;
                })
                .catch(e => {});
        }
    },
    components: {
        DockingEdit
    }
};
</script>
<style lang="less" scoped>
.docking-list {
    .flex();
    padding-left: 70px;
    position: relative;

    .docking-name {
        align-self: flex-start;
        font-size: 12px;
        color: #c8c9cc;
        line-height: 36px;
        position: absolute;
        left: 70px;
        top: 0;
    }

    .del {
        align-self: flex-start;
        margin-left: 20px;
        min-width: 60px;
    }
}
</style>
