<template>
    <div class="business-ETA-list">
        <div class="top-filter-box">
            <div>
                <el-button type="primary" @click="$router.push('/addETABusiness')">新增</el-button>
                <el-input
                    placeholder="商家名称/社会信用码/商家ID"
                    v-model="search_txt"
                    @input="changeSelectOptions('search')"
                    clearable
                    style="maxWidth:500px;float:right">
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
            </div>
            
        </div>
        <div class="table-wrap">
            <div class="select-wrap">
                <el-select 
                    v-model="trade" 
                    placeholder="请选择行业" 
                    clearable 
                    @change="changeSelectOptions('trade')"
                >
                    <el-option
                        v-for="item in tradeArr"
                        :key="item.IndustryId"
                        :label="item.IndustryName"
                        :value="item.IndustryId">
                    </el-option>
                </el-select>
                <el-cascader
                    ref="cascader"
                    v-model="sales"
                    :options="salesArr"
                    :show-all-levels="false"
                    :props="{
                        expandTrigger: 'hover',
                        children: 'Child',
                        emitPath: false,
                        label:'AdminName',
                        value:'AdminId',
                        multiple:true
                    }"
                    collapse-tags
                    filterable
                    clearable
                    placeholder="请选择销售"
                    @change="changeSelectOptions('sales')"
                />
                <el-cascader 
                    v-model="valueLocation" 
                    collapse-tags 
                    :props="locationProps" 
                    clearable 
                    :options="locationOptions"  
                    @change="changeSelectOptions('location')" 
                    placeholder="请选择客户地址" 
                />
                <el-select v-model="nation" placeholder="请选择所属国家" filterable clearable @change="changeSelectOptions('nation')">
                    <el-option :label="item.cnName" :value="item.cnName" v-for="item in countryData" :key="item.code" >
                        <div style="display: flex;justify-content: space-between;">
                            <span>{{ item.cnName }}</span>
                            <span style="color: #8492a6; font-size: 13px">{{ item.code }}</span>
                        </div>
                    </el-option>
                </el-select>
                <el-select 
                    v-model="signStatus" 
                    placeholder="请选择签约状态" 
                    clearable
                    @change="changeSelectOptions('signStatus')"
                >
                    <el-option
                        v-for="item in signStatusOpts"
                        :key="item.val"
                        :label="item.label"
                        :value="item.val">
                    </el-option>
                </el-select>
            </div>
            <el-table
                    ref="userTable"
                    :data="tableData"
                    v-loading="isTableLoadding"
                    element-loading-text="数据加载中..."
                    @sort-change="sortChangeHandle"
                    border
                >
                    <el-table-column
                        v-for="item in tableColOpts"
                        :key="item.key"
                        :prop="item.key"
                        :label="item.label"
                        align="center"
                        :sortable="item.sort"
                    >
                        <template slot-scope="scope">
                            <span v-if="item.key==='SigningStatus'">
                                {{signStatusOpts[scope.row.SigningStatus - 1].label}}{{!scope.row.Enable?'（禁用）':''}}
                            </span>
                            <span v-else-if="item.key==='BusinessName'" class="link" @click="handleShowDetail(scope.row)">
                                {{ scope.row.BusinessName }}
                            </span>
                            <span v-else-if="item.key==='Address'">
                                {{ scope.row.RegionType=='海外'?scope.row.Nation || scope.row.Address:scope.row.Address }}
                            </span>  
                            <span v-else>{{scope.row[item.key]}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        min-width="100"
                        align="center"
                    >
                        <template slot-scope="scope">
                            <div class="table-opt-btns">
                                <span @click="handleEdit(scope.row)">编辑</span>
                                <span @click="handleShowRenewal(scope.row)">添加续约</span>
                                <el-dropdown 
                                    size="medium" 
                                    placement="bottom-start" 
                                    @command="itemclickHandle($event,scope.row)"
                                >
                                    <span class="el-dropdown-link">
                                        <i class="el-icon-more el-icon--right"></i>
                                        <el-dropdown-menu slot="dropdown">
                                            <el-dropdown-item command="setAuth">权限设置</el-dropdown-item>
                                            <el-dropdown-item command="modifySale">修改销售</el-dropdown-item>
                                            <el-dropdown-item command="disable">{{scope.row.Enable?'禁用':'启用'}}</el-dropdown-item>
                                        </el-dropdown-menu>
                                    </span>
                                </el-dropdown>
                            </div>
                        </template>
                    
                    </el-table-column>
            </el-table>
            <div style="text-align:right;margin-top:20px">
                <el-pagination 
                        layout="total,prev,pager,next,jumper" 
                        background 
                        :current-page="page"
                        @current-change="handleCurrentChange"
                        :page-size="pageSize"
                        :total="total"
                        style="display: inline-block"
                    />
            </div>
        </div>

        <!-- 添加续约 -->
        <el-dialog
            title="添加续约"
            :visible.sync="showRenewal"
            :modal-append-to-body="false"
            :close-on-click-modal="false"
            @closed="showRenewal=false"
            width="580px"
        >
            <AddRenewal 
                @addRenewal="handleAddRenewal"
                @close="showRenewal=false"/>
        </el-dialog>

        <!-- 修改销售 -->
        <el-dialog
            title="修改销售"
            :visible.sync="showModifySaller"
            :modal-append-to-body="false"
            :close-on-click-modal="false"
            @closed="showRenewal=false"
            width="580px"
        >
            <ModifySaller 
                :salesArr="salesArr"
                :data="modifyData"
                @modifySaller="handleModifySaller"
                @close="showModifySaller=false"/>
        </el-dialog>
    </div>
</template>

<script>
import { customInterence ,businessCustomInterence , roadshowInterence} from '@/api/api.js'
import {locationOptions} from "@/views/custom_manage/customList/location"
import AddRenewal from './components/AddRenewal.vue'
import ModifySaller from './components/ModifySaller.vue'
import country from "@/utils/countryData"
export default {
    components:{AddRenewal,ModifySaller},
    data() {
        this.countryData = country
        return {
            /* dialog */
            showRenewal:false,//显示添加续约
            showModifySaller:false,//显示修改销售
            modifyData:{},//当前操作的商家数据

            /* select options */
            search_txt:'',
            trade:'',
            tradeArr:[],
            sales:[],
            salesArr:[],//销售
            locationOptions,
            valueLocation:[],
            provinceValue:'',
            cityValue:'',
            nation:'',
            locationProps:{
                multiple: true,
                value:'name',
                children:'city',
                label:'name'
            },
            signStatus:'',
            signStatusOpts:[
                {
                    label:'首次签约',
                    val:1
                },
                {
                    label:'续约中',
                    val:2
                },
                {
                    label:'已终止',
                    val:3
                },
                {
                    label:'待签约',
                    val:4
                }
            ],
            /* sort options */
            sortParam:0,
            sortType:0,

            /* table */
            tableColOpts:[
                {
                    label:'商家名称',
                    key:'BusinessName'
                },
                {
                    label:'商家ID',
                    key:'BusinessCode'
                },
                {
                    label:'商家地址/所属国家',
                    key:'Address'
                },
                {
                    label:'销售',
                    key:'SellerName'
                },
                {
                    label:'签约状态',
                    key:'SigningStatus'
                },
                {
                    label:'运维开始时间',
                    key:'SigningTime',
                    sort:true
                },
                {
                    label:'到期时间',
                    key:'ExpiredTime',
                    sort:true
                },
                {
                    label:'创建时间',
                    key:'CreateTime',
                    sort:true
                },
                {
                    label:'用户上限',
                    key:'UserMax',
                    sort:true
                },
                
            ],
            tableData:[],
            isTableLoadding:false,
            page:1,
            pageSize:20,
            total:0,
        }
    },
    created() {
        this.getIndustry()
        this.getSale()
        this.getBusinessList()
    },
    methods: {
        // 筛选项改变
        changeSelectOptions(option){
            if(option === 'location'){
                const provinceArr = []
                const cityArr = []
                this.valueLocation.forEach(item=>{
                        // 省
                        provinceArr.push(item[0])
                        // 市
                        cityArr.push(item[1])
                })
                //provinceArr需要去重
                this.provinceValue = [...new Set(provinceArr)].join(',')
                this.cityValue = cityArr.join(',')
                this.page = 1;
            }
            this.getBusinessList()
        },
        // 表格排序方式改变
        sortChangeHandle(params){
            const sortParamMap = {
                'SigningTime':1,//签约时间
                'ExpiredTime':2,//到期时间
                'CreateTime':3,//创建时间
                'UserMax':4,//用户上限
            }
            this.sortParam = sortParamMap[params.prop]
            this.sortType = params.order === 'ascending' ? 1 :params.order === 'descending' ? 2 : 0
            this.page = 1
            this.getBusinessList()
        },
        // 获取表格数据
        getBusinessList(){
            this.isTableLoadding = true
            businessCustomInterence.getBusinessList({
                Keyword:this.search_txt,
                SellerIds:this.sales.join(','),
                SigningStatus:Number(this.signStatus),
                Province:this.provinceValue,
                City:this.cityValue,
                IndustryId:Number(this.trade),
                Nation:this.nation,
                PageSize:this.pageSize,
                CurrentIndex:this.page,
                SortParam:this.sortParam,
                SortType:this.sortType
            }).then(res=>{
                if(res.Ret!==200) return 
                this.tableData = res.Data.List
                this.total = res.Data.Paging.Totals
                this.isTableLoadding = false
            })
        },
        // 去详情
        handleShowDetail(data){
            this.$router.push({
                path:'/businessETADetail',
                query:{
                    id:data.EtaBusinessId
                }
            })
        },
        // 前去编辑
        handleEdit(data){
            this.$router.push({
                path:'/editETABusiness',
                query:{
                    id:data.EtaBusinessId
                }
            })
        },

        // 显示添加续约
        handleShowRenewal(e){
            this.modifyData = e
            this.showRenewal=true
        },
        // 商家添加续约
        handleAddRenewal({signDate,expirationDate}){
            businessCustomInterence.addNewContract({
                EtaBusinessId:this.modifyData.EtaBusinessId,
                SigningTime:signDate,
                ExpiredTime:expirationDate
            }).then(res=>{
                if(res.Ret!==200) return 
                this.$message.success('添加续约成功')
                this.showRenewal=false
                this.getBusinessList()
            })
        },
        // 商家修改销售
        handleModifySaller({saller,sallerName}){
            businessCustomInterence.changeBusinessSeller({
                EtaBusinessId:this.modifyData.EtaBusinessId,
                SellerId:saller,
                SellerName:sallerName
            }).then(res=>{
                if(res.Ret!==200) return 
                this.$message.success('修改销售成功')
                this.showModifySaller = false
                this.getBusinessList()
            })
        },
        // 启用禁用商家
        changeBusinessStatus(data){
            businessCustomInterence.changeBusinessStatus({
                EtaBusinessId:data.EtaBusinessId
            }).then(res=>{
                if(res.Ret!==200) return 
                this.$message.success(`${data.Enable?'禁用':'启用'}成功`)
                this.getBusinessList()
            })
        },

        // 操作栏 折叠起来的按钮
        itemclickHandle(type,data){
            if(type==='modifySale'){
                this.modifyData = data
                this.showModifySaller=true
            }else if (type==='disable'){
                this.changeBusinessStatus(data)
            }else if(type==='setAuth'){
                /* let {href} = this.$router.resolve({path:`/businessETAAuth`,query:{id:EtaBusinessId}});
                 window.open(href,'_blank'); */
                 this.$router.push({
                    path:'/businessETAAuth',
                    query:{
                        id:data.EtaBusinessId,
                        name:data.BusinessName
                    }
                })
            }
        },

        /* 根据类型获取行业 */
		getIndustry() {
			customInterence.getindustry({
				Classify:'ficc'
			}).then(res => {
				if(res.Ret === 200) {
					this.tradeArr = res.Data.List || [];
				}
			})
		},
        /* 获取销售 */
        async getSale() {
            const res = await roadshowInterence.getSellerList();
            if(res.Ret!==200) return 
            this.salesArr = res.Data.List||[]
            this.salesArr = this.salesArr.map(i=>{
                if(!i.AdminName){
                    i.AdminName = i.GroupName
                }
                if(!i.AdminId){
                    i.AdminId = i.GroupId
                }
                return i
            })
		},
        handleCurrentChange(page){
            this.page = page
            this.getBusinessList()
        }
    },
}
</script>
<style lang="scss">
.business-ETA-list{
    .top-filter-box{
        .el-cascader__search-input {
            min-width: 30px;
        }
    } 
}

</style>
<style lang="scss" scoped>
.top-filter-box{
    border: 1px solid #ECECEC;
    padding: 20px 30px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
}
.table-wrap{
    margin-top: 30px;
    border: 1px solid #ECECEC;
    padding: 20px 30px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
    .select-wrap{
        display: flex;
        gap:20px;
        align-items: center;
        margin-bottom: 20px;
        .el-select,.el-cascader{
            width:240px;
        }
    }
    .link{
        color:#4099ef;
        cursor: pointer;
        &:hover{
            text-decoration: underline;
        }
        
    }
}
.table-opt-btns{
    color:#4099ef;
    display:flex;
    align-content: center;
    justify-content: center;
    align-items: center;
    span{
        margin: 0 3px;
        cursor: pointer;
    }
}


</style>