<template>
    <div>
        <lj-win-editable-mx :title="title" :addable="false" :save-handler="handleSaveButton" :editing.sync="editing">
            <template slot="body_top">
                <lj-dictionary :data="mainObject" :columns="columns1" :editing="editing"
                               @action-row-click="handleMainActionRowClick" @row-button-click="handleRowButtonClick"></lj-dictionary>
                <lj-dictionary v-if="!editing" :data="mainObject" :columns="columns2"
                               @action-row-click="handleMainActionRowClick"></lj-dictionary>
                <lj-dictionary v-if="!editing" :data="mainObject" :columns="columns3"
                               @action-row-click="handleMainActionRowClick"></lj-dictionary>
            </template>
        </lj-win-editable-mx>
        <q5-area-choose ref="areaChooseDialog" @area-chosen="handleAreaChosen"/>
    </div>
</template>

<script>
    import LjDictionary from "components/lj-dictionary";
    import LjWinEditableMx from "components/lj-win-editable-mx";
    import Q5AreaChoose from "components/L1APP/public/Q5-area-choose";

    export default {
        components: {Q5AreaChoose, LjWinEditableMx, LjDictionary},
        created() {
            let user = $lj.getStorage("user");
            if (user) {
                this.username = user.username;
            }
            this.habit = $lj.getEditHabit(this.habitProps);
            let pageParam = $lj.getPageParam();
            if (pageParam && pageParam.mainObject) {
                this.mainObject = pageParam.mainObject;
            } else {
                this.editing = true;
                this.mainObject = Object.assign({}, this.habit);
            }
            this.reloadData();
        },
        mounted () {
            if (!this.mainObject.cusid) {
                //this.$set(this.mainObject, "custype", this.username);
                this.$set(this.mainObject, "state",1);
                this.$refs.areaChooseDialog.open();
            }
        },
        data() {
            return {
                habit: {},
                habitProps: ["state"],
                editing: false,
                menuOpen: false,
                mainObject: {},
                username:"",
                columns1: [
                    {property: "name", label: "客户名称", required: 1},
                    {property: "cuscode", label: "客户编号"},
                    {property: "cusareaname", label: "地区", type: "Action"},
                    {property: "areaname", label: "详细类别", type: "Action"},
                    {label: "业务员", property: "custype",type: "Select", selectOptions: {
                            optionsApi: "GetOutrepList",
                            valueMap: ["outrepname", "outrepname"],
                        }
                    },
                    {property: "tele1", label: "手机", type: "Number"},
                    {property: "rep", label: "联系人",buttonText:"通讯录"},
                    {property: "tele", label: "联系电话", type: "Number"},
                    {property:"moneyid",label:'币种',type: "Select",selectOptions:{
                        optionsApi:'GetQ5Currency',
                        valueMap:["moneyid",'name']
                    }},
                     {property:'banktypeid',label:'结算方式',type: "Select",selectOptions: {
                            optionsApi: "GetQ5BanktypeList",
                              apiParams: {banktype: 0},
                            valueMap: ["banktypeid", "banktypename"],
                        }},
                    {property: "address", label: "地址"},
                    {property: "freight", label: "货运部"},
                    {property: "freight_tele", label: "货运部电话", type: "Number"},
                    {property: "stat_handtel", label: "货运部手机", type: "Number"},
                    {property: "stat_address", label: "货运部地址"},
                    {
                        property: "state", label: "状态", type: "Select", selectOptions: {
                            valueMap: ["value", "display"],
                            options: [
                                {value: 0, display: "公共"},
                                {value: 1, display: "正式"},
                                {value: 2, display: "黑名单"},
                                {value: 3, display: "准客户"}
                            ]
                        }
                    },
                    {property: "dscrp", label: "备注"}
                ],
                columns2: [
                    {label: "在进行", property: "saletask_amt_cnt", type: "AlwaysAction"},
                    {label: "未出库", property: "outware_amt_cnt_noaudit", type: "AlwaysAction"},
                    {label: "历史销售", property: "salePast", type: "AlwaysAction"},
                    {label: "本年", property: "outware_amt_cnt_thisyear"},
                    {label: "累计", property: "outware_amt_cnt_total"}
                ],
                columns3: [
                    {label: "累计欠款", property: "notakeamt", append: "元"},
                    {label: "历史收款", property: "takeamt_cnt", type: "AlwaysAction"},
                    {label: "本年", property: "taskamt_cnt_thisyear"},
                    {label: "累计", property: "taskamt_cnt_total"}
                ],
            }
        },
        methods: {
            reloadData() {
                if (!this.mainObject.cusid) {
                    return;
                }
                if (this.mainObject.opdate) {
                    this.fillData();
                } else {
                    let self = this;
                    $lj.postLJRequest("GetCustList", {
                        token: $lj.getStorage("token"),
                        cusid: this.mainObject.cusid
                    }, function (ret) {
                        if (ret) {
                            if (!ret.custList || ret.custList.length === 0) {
                                alert("查询单据失败：cusid" + self.mainObject.cusid);
                                return;
                            }
                            if (ret.custList.length > 1) {
                                alert("重复的单据：cusid" + self.mainObject.cusid);
                                return;
                            }
                            self.mainObject = ret.custList[0];
                            self.fillData();
                        }
                    })
                }
            },
            fillData() {
                let requestBody = {
                    token: $lj.getStorage("token"),
                    cusid: this.mainObject.cusid
                };
                let self = this;
                $lj.postLJRequest('GetQ5CustDetail', requestBody, function (ret) {
                    if (ret) {
                        let custDetail = ret.cust;
                        self.$set(self.mainObject, "notakeamt", custDetail.notakeamt);
                        self.$set(self.mainObject, "saletask_amt_cnt", custDetail.saletask_amt + "元/" + custDetail.saletask_cnt + "单");
                        self.$set(self.mainObject, "outware_amt_cnt_noaudit", custDetail.outware_amt_noaudit + "元/" + custDetail.outware_cnt_noaudit + "单");
                        self.$set(self.mainObject, "outware_amt_cnt_thisyear", custDetail.outware_amt_thisyear + "元/" + custDetail.outware_cnt_thisyear + "单");
                        self.$set(self.mainObject, "outware_amt_cnt_total", custDetail.outware_amt_total + "元/" + custDetail.outware_cnt_total + "单");
                        self.$set(self.mainObject, "taskamt_cnt_thisyear", custDetail.takeamt_thisyear + "元/" + custDetail.takeamt_thisyear_cnt + "单");
                        self.$set(self.mainObject, "taskamt_cnt_total", custDetail.takeamt_total + "元/" + custDetail.takeamt_total_cnt + "单");
                    }
                })
            },
            handleMainActionRowClick(eventData) {
                if (this.editing) {
                    switch (eventData.field) {
                        case 'cusareaname':
                        case "areaname":
                            this.$refs.areaChooseDialog.open();
                            break;
                        default:
                            break;
                    }
                } else {
                    if (eventData.field === "saletask_amt_cnt") {
                        $lj.openWin("saletask", {queryParams: {cusid: this.mainObject.cusid, status: 1}});
                    }
                    if (eventData.field === "outware_amt_cnt_noaudit") {
                        $lj.openWin("outwaresale", {queryParams: {cusid: this.mainObject.cusid, status: 1}});
                    }
                    if (eventData.field === "salePast") {
                        $lj.openWin("outwaresale", {queryParams: {cusid: this.mainObject.cusid}});
                    }
                    if (eventData.field === "takeamt_cnt") {
                        $lj.openWin("account-rec", {queryParams: {cusid: this.mainObject.cusid}});
                    }
                }
            },
            handleRowButtonClick(eventData){
                let self = this;
                api.openContacts(function(ret,err) {
                    if (ret) {
                        if (ret.status == true) {
                            self.$set(self.mainObject, "rep", ret.name);
                            self.$set(self.mainObject, "tele", ret.phone);
                            if (!self.mainObject.name) {
                                self.$set(self.mainObject, "name", ret.name);
                            }
                        }else{
                            $lj.toast("获取联系人信息失败，请重试")
                        }
                    } else {
                        alert(JSON.stringify(err));
                    }
                });
                // var DVContacts = api.require('DVContacts');
                // DVContacts.allContacts(function(ret,err) {
                //     if (ret) {
                //         alert(JSON.stringify(ret));
                //     } else {
                //         alert(JSON.stringify(err));
                //     }
                // });
            },
            handleAreaChosen(item) {
                if (item && item.CusareaID) {
                    this.$set(this.mainObject, "cusareaname", item.Cusareaname);
                    this.$set(this.mainObject, "areaname", item.areaname);
                    this.$set(this.mainObject, "cusareaid", item.CusareaID);
                }
                this.GetL1AutoCuscode(item.CusareaID);
            },
            GetL1AutoCuscode(value){
                let self = this;
                let requestBody = {
                    token: $lj.getStorage("token"),
                    cusareaid:value,
                };
                $lj.postLJRequest('GetL1AutoCuscode', requestBody, function (ret) {
                    if (ret) {
                        self.$set(self.mainObject, "cuscode", ret.cuscode);
                    }
                })
            },
            handleSaveButton(callback) {
                if(!this.mainObject.moneyid){
                     alert("币种不能为空");
                     return;
                }
                if(!this.mainObject.banktypeid){
                     alert("结算方式不能为空");
                     return;
                }
                let requestBody = {
                    token: $lj.getStorage("token"),
                    cust: this.mainObject
                };
                let self = this;
                $lj.setEditHabit(this.mainObject, this.habitProps);
                $lj.postLJRequest("SaveL1Cust", requestBody, function (ret) {
                    if (ret) {
                        alert("保存成功");
                        callback(true);
                        self.mainObject = {cusid: ret.cusid};
                        // self.reloadData();
                        $lj.closeWin();
                    } else {
                        callback(false);
                    }
                });
            }
        },
        computed: {
            title() {
                if (this.editing) {
                    if (this.mainObject.cusid) {
                        return "编辑客户资料";
                    } else {
                        return "新建客户资料";
                    }
                } else {
                    return "客户资料详细"
                }
            }
        }
    }
</script>