<template>
    <div>
        <Row class="search-row">
            <i-col span="24" class="search-col">
                <Row class="row-style">
                    <i-input placeholder="搜索店铺编码/名称" class="left-15 search-select" @on-enter="onEnterLister" v-model="searchContent"/>
                    <span class="search-span">大区</span>
                    <Select filterable clearable placeholder="请选择大区" v-model="regionId" @on-change="regionSelect" @on-clear="onClickClearBtnLister(0)" class="search-select">
                        <Option v-for="item in regionList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                    <span class="search-span">零售公司</span>
                    <Select filterable clearable placeholder="请选择零售公司" v-model="companyId" @on-change="companySelect" @on-clear="onClickClearBtnLister(1)" class="search-select">
                        <Option v-for="item in companyList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                    <span class="search-span">客户</span>
                    <Select filterable clearable placeholder="请选择客户" v-model="customerId" class="search-select" @on-clear="onClickClearBtnLister(2)">
                        <Option v-for="item in customerList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                    <Button type="primary" @click="onClickGetDataLister" class="search-btn">查询</Button>
                    <div class="search-div-btn">
                        <Button type="primary" @click="open(0,null)">添加</Button>
                    </div>
                </Row>
            </i-col>
        </Row>


        <Table :loading="loading" ref="table" :columns="columns1" :data="data1" class="table-margin-top"
               size="small">
            <template slot-scope="{row}" slot="action">
                <Button
                        ghost
                        type="primary"
                        size="small"
                        style="border: 0px;color:#2074E2"
                        @click="open(1,row)"
                >修改
                </Button>
                <Button
                        ghost
                        type="error"
                        size="small"
                        style="border: 0px"
                        @click="remove(row)"
                >删除</Button>
            </template>

        </Table>
        <Page :total="totalSize" :current="pageNum" :page-size="pageSize" show-elevator show-total
              placement="top" @on-change="handlePage" class-name="ks-page"></Page>

        <!-- 添加/修改 店铺 -->
        <Modal v-model="isShow" :footer-hide="true">
            <div slot="header">{{type === 0 ? '添加' : '修改'}}店铺</div>
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                <FormItem label="店铺全称" prop="name">
                    <i-input type="text" v-model="formValidate.name" placeholder="请输入店铺全称"></i-input>
                </FormItem>
                <FormItem label="店铺编码" prop="code">
                    <i-input v-model="formValidate.code"
                             placeholder="请输入店铺编码">
                    </i-input>
                </FormItem>
                <FormItem label="店铺简称" prop="abbreviation">
                    <i-input v-model="formValidate.abbreviation"
                             placeholder="请输入店铺简称">
                    </i-input>
                </FormItem>
                <FormItem label="所属客户" prop="parentId">
                    <Select filterable clearable v-model="formValidate.parentId"
                            placeholder="选择客户">
                        <Option v-for="item in customerList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                </FormItem>
                <FormItem style="text-align: left;">
                    <Button :loading="btnLoading" type="primary" @click="handleSubmit(formValidate)">{{type === 0 ? '保存' : '修改'}}</Button>
                    <Button @click="handleReset('formValidate')" style="margin-left: 10px">取消</Button>
                </FormItem>
            </Form>
        </Modal>

        <Modal v-model="isModelShow" title="删除提示" align="center">
            <p style="margin-top: 20px;margin-bottom: 20px">
                确定要删除此客户吗？删除后不可恢复
            </p>
            <div slot="footer"
                 style="text-align: center;margin-bottom: 10px;margin-top: 10px">
                <Button style="width: 100px;" @click="isModelShow = false">取消</Button>
                <Button :loading="btnLoading" type="error" style="width: 100px;margin-left: 20px" @click="deleteOrganizational">确认</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import service from "../../services/organization/OrganizationService";
    import zeroExtend from "../../services/customer/zeroExtend";

    export default {
        name: "OrganizationStore",
        data() {
            return {
                userId: "",
                loading: false,
                btnLoading: false,// 添加修改加载中
                columns1: [
                    {
                        title: '序号',
                        key: 'index'
                    },
                    {
                        title: '店铺名称',
                        key: 'name'
                    },
                    {
                        title: '店铺简称',
                        key: 'abbreviation'
                    },
                    {
                        title: '店铺编码',
                        key: 'code'
                    },
                    {
                        title: '客户名称',
                        key: 'customerName'
                    },
                    {
                        title: '客户编码',
                        key: 'customerCode'
                    },
                    {
                        title: '所属零售公司',
                        key: 'companyName'
                    },
                    {
                        title: '所属零售公司编码',
                        key: 'companyCode'
                    },
                    {
                        title: '所属大区',
                        key: 'regionName'
                    },
                    {
                        title: '操作',
                        slot: 'action',
                        width: '200px'
                    }
                ],
                data1: [
                ],
                //分页内容
                totalSize: 0,
                pageNum: 1,
                pageSize: 10,
                isShow: false,
                type: 0, // 0添加 1修改
                formValidate: {
                    name: '',
                    code: '',
                    abbreviation: '',
                    parentId: 0
                },
                ruleValidate: {
                    name: [
                        {required: true, message: '店铺全称不能为空', trigger: 'blur'}
                    ],
                    code: [
                        {required: true, message: '店铺编码不能为空', trigger: 'blur'}
                    ],
                    detailName: [
                        {required: true, message: '店铺简称不能为空', trigger: 'blur'}
                    ],
                    parentId: [
                        { required: true, type: 'number', message: '请选择客户', trigger: 'change' }
                    ]
                },
                isModelShow: false,
                currentId: 0, // 当前记录ID
                companyId: 0,// 大区下拉选择
                regionList: [], // 大区数据
                searchContent: '', // 搜索内容
                regionId: 0, // 当前选择大区的ID
                companyList: [], //零售公司list
                customerId: 0, // 当前选择客户ID
                customerList: [], // 客户list
            }
        },
        created() {
            this.userId = JSON.parse(sessionStorage.getItem("loginInfo")).userId;
            this.getSelectList();
            this.getData();
        },
        methods: {
            remove: function (row) {
                this.isModelShow = true;
                this.currentId = row.id;
            },
            open: function (type, item) {
                this.isShow = true;
                this.type = type;
                if(type === 0){
                    // 添加
                    this.formValidate =  {
                        name: "",
                        code: '',
                        abbreviation: '',
                        parentId: 0
                    }
                }else{
                    this.formValidate =  {
                        id: item.id,
                        name: item.name,
                        code: item.code,
                        abbreviation: item.abbreviation,
                        parentId: item.customerId
                    }
                }
            },
            show: function () {
                this.isShow = true;
            },
            hide: function () {
                this.isShow = false;
            },
            handleSubmit(value) {
                if (value) {
                    if(!value.parentId){
                        this.$Message.info('请输入表单内容');
                        return;
                    }
                    if(this.type === 0){
                        // 添加
                        this.addCustomer(value);
                    }else{
                        // 调用修改接口
                        this.modifyCustomer(value);
                    }
                } else {
                    this.$Message.info('请输入表单内容');
                }
            },
            handleReset(name) {
                this.$refs[name].resetFields();
                this.isShow = false;
            },
            /**
             * 切页处理
             */
            handlePage: function (value) {
                this.pageNum = value;
                this.getData();
            },
            deleteOrganizational: function () {
                // 删除组织
                let that = this;
                if(that.currentId === 0){
                    return;
                }
                that.btnLoading = true;
                let request = {
                    id: that.currentId
                };
                service.postOrganizationStoreRemoveId(request, function (res) {
                    that.btnLoading = false;
                    let data = res.data;
                    if(data.code === "0000"){
                        that.$Message.success("删除成功");
                        that.isModelShow = false;
                        that.getData();
                    }else{
                        that.$Message.error(data.msg);
                    }
                }, function () {
                    that.btnLoading = false;
                });

            },
            /**
             * 查询列表
             */
            getData: function () {
                let that = this;
                that.loading = true;

                let request = {
                    userId: that.userId,
                    searchVal: that.searchContent,
                    companyId: that.companyId,
                    regionId: that.regionId,
                    customerId: that.customerId,
                    pageNum: that.pageNum,
                    pageSize: that.pageSize
                };
                service.postOrganizationStoreList(request, function (res) {
                    that.loading = false;
                    let data = res.data;

                    that.data1 = [];
                    for (let i=0;i<data.results.records.length;i++) {
                        let item = data.results.records[i];
                        item.index = that.pageSize * (that.pageNum-1)  + i+1 ;
                        that.data1.push(item);
                    }

                    that.totalSize = data.results.total;
                }, function () {
                    that.loading = false;
                });
            },
            /**
             * 添加客户
             */
            addCustomer: function (val) {
                let that = this;
                let request = {
                    name: val.name,
                    code: val.code,
                    abbreviation: val.abbreviation,
                    customerId: val.parentId
                };
                that.btnLoading = true;
                service.postOrganizationStoreAdd(request, function (res) {
                    that.btnLoading = false;
                    let data = res.data;
                    if(data.code === "0000"){
                        that.$Message.success("添加成功");
                        that.hide();
                        that.getData();
                    }else{
                        that.$Message.error(data.msg);
                    }
                }, function () {
                    that.btnLoading = false;
                });
            },
            /**
             * 修改客户
             */
            modifyCustomer: function (val) {
                let that = this;
                let request = {
                    id: val.id,
                    name: val.name,
                    code: val.code,
                    abbreviation: val.abbreviation,
                    customerId: val.parentId
                };
                service.postOrganizationStoreModify(request, function (res) {
                    that.btnLoading = false;
                    let data = res.data;
                    if(data.code === "0000"){
                        that.$Message.success("修改成功");
                        that.hide();
                        that.getData();
                    }else{
                        that.$Message.error(data.msg);
                    }
                }, function () {
                    that.btnLoading = false;
                });
            },
            /**
             * 回车事件
             */
            onEnterLister: function () {
                this.pageNum = 1;
                this.getData();
            },
            /**
             * 大区选择改变事件
             */
            regionSelect: function(){
                let regionId = this.regionId;
                if(regionId === 0){
                    this.companyList = this.organizationalList.filter(item => item.level === 2);
                    this.customerList = this.organizationalList.filter(item => item.level === 3);
                }else{
                    this.companyList = this.organizationalList.filter(item => item.parentId === regionId && item.level === 2);
                    let companyIds = this.companyList.map(item => item.id);
                    this.customerList = this.organizationalList.filter(item => companyIds.indexOf(item.parentId) !== -1 && item.level === 3);
                }
            },
            /**基础数据：区域list、零售公司list、客户list*/
            getSelectList:function(){
                let that = this;
                let request = {
                    userId: this.userId
                };
                zeroExtend.getSelectListRequest(request,function (data) {
                    if(data.data.code !== "0000"){
                        that.$Message.error("系统异常");
                    }
                    data = data.data.results;
                    if(data){
                        that.organizationalList = data;
                        // 大区
                        that.regionList = that.organizationalList.filter(item => item.level === 1);
                        // 零售公司
                        that.companyList = that.organizationalList.filter(item => item.level === 2);
                        // 客户
                        that.customerList = that.organizationalList.filter(item => item.level === 3);
                    }
                    //插入全部选项
                    // that.insertAllOption();
                });
            },
            //零售公司选择
            companySelect: function(){
                let companyId = this.companyId;
                if(companyId === 0){
                    let companyIds = this.companyList.map(item => item.id);
                    this.customerList = this.organizationalList.filter(item => companyIds.indexOf(item.parentId) !== -1 && item.level === 3);
                }else{
                    this.customerList = this.organizationalList.filter(item => item.parentId === companyId && item.level === 3);
                }
                // this.insertAllOption();
                // this.customerId = 0;
            },
            /**
             * 点击查询按钮事件
             */
            onClickGetDataLister: function () {
                this.pageNum = 1;
                this.getData();
            },
            /**
             * 点击清除按钮事件处理
             * @param type
             */
            onClickClearBtnLister: function (type) {
                if (type === 0) {
                    // 大区
                    this.regionId = 0;
                }else if(type === 1){
                    // 零售公司
                    this.companyId = 0;
                }else if(type === 2){
                    // 客户
                    this.customerId = 0;
                }
            }

        }
    }
</script>

<style scoped>

</style>
