<template>
    <div class="overseas-custom-list-wrap">
        <div class="top-box" v-show="isDataSelectBtnShow">
            <div class="switch-box">
                <el-radio-group v-model="pageSelect" >
                    <el-radio-button :label="1">海外客户</el-radio-button>
                    <el-radio-button :label="2">已隐藏客户</el-radio-button>
                </el-radio-group>
            </div>
            <div class="select-box">
                <el-select placeholder="请选择销售" v-if="pageSelect===1"
                    v-model="tableParams.SellerId" 
                    @change="handlePageChange(1)"
                    multiple collapse-tags clearable>
                    <el-option
                        v-for="item in salesArr"
                        :key="item.SellerId"
                        :label="item.RealName"
                        :value="item.SellerId"
                    />
                </el-select>
                <el-input 
                    prefix-icon="el-icon-search" 
                    placeholder="客户名称/社会信用码/手机号码/邮箱" 
                    style="width:317px;" clearable
                    v-model="tableParams.Keywords"
                    @input="handlePageChange(1)"
                />
            </div>
        </div>
        <div class="data-box" v-loading="tableLoading">
            <div class="data-select-box">
                <div class="table-select-box">
                    <ul class="status-box">
                        <li v-for="item in tableTabs" :key="item.Status"
                            :class="['tab',{'act':tableParams.CompanyStatus === item.CompanyStatus}]"
                            @click="changeStatus(item)"
                        >
                            {{`${item.CompanyStatus}(${item.Total})`}}
                        </li>
                    </ul>
                    <!-- 试用小分类 -->
                    <ul class="try-status-box" v-if="tableParams.CompanyStatus==='试用'">
                        <li v-for="item in tryTabs" :key="item.TryStatus"
                            :class="['trial-item',{'act':tableParams.tagStatusSelect === item.TryStatus}]" 
                            @click="changeTagStatus(item)"
                        >
                            {{item.TryStatus+'('+item.Total+')'}}
                        </li>
                    </ul>
                </div>
                <!-- 管理员-选择销售 -->
                <div class="data-select" v-if="isDataSelectBtnShow&&this.salesArr.length">
                    <el-button v-if="pageSelect===1" type="text" @click="isSelectSaleShow=true"><i class="el-icon-plus"  style="font-weight: bold;margin-right: 5px;"/>选择销售</el-button>
                </div>
                <!--非管理员 筛选-->
                <div class="data-select" v-if="!isDataSelectBtnShow" style="flex:1;">
                    <div class="select-box" style="display: flex;justify-content: flex-end;gap: 30px;">
                        <el-select placeholder="请选择销售" v-if="pageSelect===1"
                            v-model="tableParams.SellerId" 
                            @change="handlePageChange(1)"
                            multiple collapse-tags clearable>
                            <el-option
                                v-for="item in salesArr"
                                :key="item.SellerId"
                                :label="item.RealName"
                                :value="item.SellerId"
                            />
                        </el-select>
                        <el-input 
                            prefix-icon="el-icon-search" 
                            placeholder="客户名称/社会信用码/手机号码/邮箱" 
                            style="width:317px;" clearable
                            v-model="tableParams.Keywords"
                            @input="handlePageChange(1)"
                        />
                    </div>
                </div>
            </div>
            <div class="table-box">
                <el-table
                    ref="overseasTable"
                    :data="tableData"
                    border
                    @sort-change="handleSortChange"
                >
                    <el-table-column 
                        align="center"
                        v-for="item in columns" :key="item.key"
                        :prop="item.key" :label="item.label"
                        :min-width="item.minWidth"
                        :sortable="item.sortable?'custom':false"
                    >
                        <template slot-scope="{row}">
                            <!-- 客户名称 -->
                            <div v-if="item.key==='CompanyName'" class="editor" @click="toCustomDetail(row)">{{row[item.key]}}</div>
                            <!-- 状态 -->
                            <div  v-else-if="item.key==='OverseasStatus'" class="status-box">
                                    <span>{{row[item.key]}}</span>
                                    <div class="select" v-if="row[item.key]==='试用'">
                                        <el-select 
                                            v-model="row.OverseasLabel"
                                            size="mini" 
                                            style="width: 50px" 
                                            placeholder=""
                                            @change="handleChangeTryStatus(row)"
                                        >
                                            <el-option
                                                v-for="item in trialTags"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value">
                                            </el-option>
                                        </el-select>
                                    </div>
                            </div>
                            <span v-else-if="item.key==='ViewTotal'" :class="{'editor':row[item.key]>0}" @click="handleDialogShow('click',row)">{{row[item.key]}}</span>
                            <span v-else-if="item.key==='RoadShowTotal'" :class="{'editor':row[item.key]>0}" @click="handleDialogShow('road',row)">{{row[item.key]}}</span>
                            <span v-else-if="['LastViewTime','CreateTime'].includes(item.key)">
                                {{
                                    row[item.key].slice(0,10)==='0000-00-00'?'':row[item.key].slice(0,10)
                                }}
                            </span>
                            <span v-else>{{row[item.key]}}</span>
                        </template>
                    </el-table-column>
                    <!-- 操作列 -->
                    <el-table-column label="操作" align="center">
                        <template slot-scope="{row}">
                            <el-button type="text" v-if="pageSelect===1&&row.IsHide===0" @click="handleSetCustomHide(row)">隐藏</el-button>
                            <el-button type="text" v-if="pageSelect===2&&row.IsHide===1" @click="handleSetCustomHide(row)">取消隐藏</el-button>
                            <!--英文客户且状态为试用-->
                            <el-button type="text" v-if="pageSelect===1&&row.Source===1&&row.OverseasStatus==='试用'" @click="handleSetCustomStatus(row,'change')">转正式</el-button>
                            <!--英文客户且状态为正式且可以重置-->
                            <el-button type="text" v-if="pageSelect===1&&row.Source===1&&row.OverseasStatus==='正式'&&row.ResetBtn===2" @click="handleSetCustomStatus(row,'reset')">重置</el-button>
                            
                            <el-button type="text" @click="handleShowShareRecode(row)">沟通记录</el-button>
                        </template>
                    </el-table-column>
                    <template slot="empty">
                        <!-- 管理员展示按钮 -->
                        <div class="data-select" v-if="isDataSelectBtnShow&&!salesArr.length">
                            <el-button type="text" @click="isSelectSaleShow=true"><i class="el-icon-plus"  style="font-weight: bold;margin-right: 5px;" />选择销售</el-button>
                        </div>
                        <!-- 非管理员显示暂无数据 -->
                        <div v-else>暂无数据</div>
                    </template>
                    
                </el-table>
                <el-pagination 
                    layout="total,prev,pager,next,jumper" 
                    background 
                    :current-page="currentPage"
                    @current-change="(page)=>handlePageChange(page,'sort')"
                    :page-size="pageSize"
                    :total="total"
                    style="text-align: right;margin-top:20px"/>
            </div>
        </div>
        <!-- 选择销售弹窗 -->
        <SelectSaleDialog 
            ref="selectDialog"
            :isSelectSaleShow="isSelectSaleShow"
            :selectedSalesArr="salesArr"
            @close="isSelectSaleShow=false"
            @saveSales="saveSales"
        />
        <!-- 累计点击量弹窗 -->
        <TotalClicksDialog 
            :isTotalClickShow="isTotalClickShow"
            :customData="customData"
            @close="isTotalClickShow = false"
        />
        <!-- 路演数量弹窗 -->
        <RoadShowsDialog 
            :isRoadDetailShow="isRoadDetailShow"
            :customData="customData"
            @close="isRoadDetailShow = false"
        />

         <!-- 服务记录弹窗 -->
        <ShareListDialog
            :isShareRecodeDialogShow.sync="isShareRecodeDialogShow"
            :customInfo="customInfo"
            :allowEdit="allowEdit"
            @close="()=>{isShareRecodeDialogShow=false;}"
        />
    </div>
</template>

<script>
import { overseasCustomInterence} from '@/api/modules/overseasCustom.js'
import SelectSaleDialog from './components/selectSaleDialog';
import TotalClicksDialog from './components/totalClicksDialog';
import RoadShowsDialog from './components/roadShowsDialog';
import ShareListDialog from '../customList/components/shareListDialog.vue';
import mixin from '../customList/mixins/customlistMixin';
const tryArr = ['','未分类','推进','跟踪','预备']
export default {
    mixins: [ mixin ],
    components: { SelectSaleDialog, TotalClicksDialog, RoadShowsDialog,ShareListDialog },
    data() {
        return {
            pageSelect: 1,
            salesArr: [],
            tableTabs: [],
            tryTabs: [],
            trialTags: [{ label: '推进', value: 2 },
                { label: '跟踪', value: 3 },
                { label: '预备', value: 4 },
                { label: '未分类', value: 1 },
            ],
            columns: [{
                    label: "客户名称",
                    key: 'CompanyName'
                }, {
                    label: "国家",
                    key: 'Nation'
                }, {
                    label: "销售",
                    key: 'SellerName'
                }, {
                    label: "状态",
                    key: 'OverseasStatus'
                }, {
                    label: "累计点击量",
                    key: 'ViewTotal',
                    sortable: true
                }, {
                    label: "路演数量",
                    key: 'RoadShowTotal',
                    sortable: true
                }, {
                    label: "最近阅读时间",
                    key: 'LastViewTime',
                    sortable: true
                }, {
                    label: "创建时间",
                    key: 'CreateTime',
                    sortable: true
                }],
            tableParams:{
                Keywords:'',
                SortField:'ViewTotal',//排序字段
                SortDesc:1,//排序方式
                SellerId:'',//选择的销售
                CompanyStatus:'全部',//客户状态
                tagStatusSelect:'全部',//客户的试用状态
                tryStatusSelect:0,//客户试用状态对应的OverseasLabel
            },
            tableData: [],
            currentPage: 1,
            pageSize: 10,
            total: 0,
            isSelectSaleShow: false, //选择销售弹窗
            isTotalClickShow:false, //累计点击量弹窗
            isRoadDetailShow:false, //路演详情弹窗
            customData:{},//选择的客户信息

            tableLoading:false,

        };
    },
    computed: {
        Role() {
            return localStorage.Role || '';
        },
        isDataSelectBtnShow() {
            return (this.Role === 'admin' || this.Role === 'ficc_admin');
        }
    },
    watch:{
        pageSelect(newval){
            //清空筛选项
            this.tableParams={
                Keywords:'',
                SortField:'ViewTotal',
                SortDesc:1,
                SellerId:'',
                CompanyStatus:'全部',
                tagStatusSelect:'全部',
                tryStatusSelect:0,
            }
            this.$refs.overseasTable&&this.$refs.overseasTable.clearSort()
            this.handlePageChange(1,'static')
        }
    },
    methods: {
        //获取已保存选择的销售
        getSavedSales(){
            overseasCustomInterence.getSavedSalesList().then(res=>{
                if(res.Ret!==200) return 
                this.salesArr = res.Data||[]
            })
        },
        //保存选择的销售
        saveSales({AddSellerIdArr,DelSellerIdArr,sales}){
            overseasCustomInterence.saveSelectedSales({
                AddSellerIdArr,DelSellerIdArr
            }).then(res=>{
                this.$refs.selectDialog&&(this.$refs.selectDialog.dialogLoading = false)
                if(res.Ret!==200) return
                this.$message.success("选择销售成功")
                this.tableParams = {
                    Keywords:'',
                    SortField:'ViewTotal',
                    SortDesc:1,
                    SellerId:'',
                    CompanyStatus:'全部',
                    tagStatusSelect:'全部',
                    tryStatusSelect:0,
                }
                this.salesArr = sales.map(i=>({SellerId:i.value,RealName:i.label}))
                this.handlePageChange(1)
                this.isSelectSaleShow = false
            })
        },
        //客户列表
        async getTableData(type) {
            this.tableLoading = true
            const {Keywords,SortField,SortDesc,SellerId,CompanyStatus,tryStatusSelect} = this.tableParams
            //重新请求统计数据
            if(type!=='sort'){
                await this.getStatisticData()
                if(CompanyStatus==='试用'){
                    await this.getTryStatisticData()
                }
            }
            overseasCustomInterence.getCustomList({
                PageSize: this.pageSize,
                CurrentIndex: this.currentPage,
                Keywords,CompanyStatus,
                SellerId:(Array.isArray(SellerId)?SellerId.join(','):'')+'',
                OverseasLabel:tryStatusSelect,
                CustomType:this.pageSelect,
                SortField,SortDesc,
            }).then(res=>{
                this.tableLoading = false
                if(res.Ret!==200) return 
                if(!res.Data) return 
                /* //客户状态
                this.tableTabs = res.Data.StatisticsData||[]
                //手动添加一个全部
                let total = this.tableTabs.map(i=>(i.Total)).reduce((acc,curr)=>acc+curr,0)
                this.tableTabs.unshift({CompanyStatus:'全部',Total:total})
                //客户试用状态
                this.tryTabs = res.Data.OverseasLabelData||[]
                this.tryTabs = this.tryTabs.map(tab=>({
                    TryStatus:tryArr[tab.OverseasLabel],
                    Total:tab.Total,
                    OverseasLabel:tab.OverseasLabel}))
                //手动添加一个全部
                let tryTotal = this.tryTabs.map(i=>(i.Total)).reduce((acc,curr)=>acc+curr,0)
                this.tryTabs.unshift({TryStatus:'全部',Total:tryTotal,OverseasLabel:0}) */
                //客户列表
                this.tableData = res.Data.List||[]
                this.total = res.Data.Paging.Totals||0
            })
        },
        //获取客户统计数据
        async getStatisticData(){
            const {Keywords,SellerId,CompanyStatus} = this.tableParams
            const statisticRes = await overseasCustomInterence.getStatisticData({
                CustomType:this.pageSelect,
                SellerId:(Array.isArray(SellerId)?SellerId.join(','):'')+'',
                Keywords
            })
            if(statisticRes.Ret!==200) return 
            //客户状态
            this.tableTabs = statisticRes.Data||[]
            //手动添加一个全部
            let total = this.tableTabs.map(i=>(i.Total)).reduce((acc,curr)=>acc+curr,0)
            this.tableTabs.unshift({CompanyStatus:'全部',Total:total})
        },
        //客户试用状态统计数据
        async getTryStatisticData(){
            const {Keywords,SellerId} = this.tableParams
            const statisticTryRes = await overseasCustomInterence.overseasCustomInterence({
                CustomType:this.pageSelect,
                SellerId:(Array.isArray(SellerId)?SellerId.join(','):'')+'',
                Keywords
            })
            if(statisticTryRes.Ret!==200) return 
            //客户试用状态
            this.tryTabs = statisticTryRes.Data||[]
            this.tryTabs = this.tryTabs.map(tab=>({
                TryStatus:tryArr[tab.OverseasLabel],
                Total:tab.Total,
                OverseasLabel:tab.OverseasLabel}))
            //手动添加一个全部
            let tryTotal = this.tryTabs.map(i=>(i.Total)).reduce((acc,curr)=>acc+curr,0)
            this.tryTabs.unshift({TryStatus:'全部',Total:tryTotal,OverseasLabel:0})
        },
        //切换客户状态
        changeStatus(item) {
            this.tableParams.CompanyStatus = item.CompanyStatus;
            if(item.CompanyStatus!=='试用'){
                this.tableParams.tagStatusSelect = '全部';
                this.tableParams.tryStatusSelect = 0
            }
            this.handlePageChange(1);
        },
        //切换客户试用状态
        changeTagStatus(item) {
            this.tableParams.tagStatusSelect = item.TryStatus;
            this.tableParams.tryStatusSelect = item.OverseasLabel
            this.handlePageChange(1);
        },
        //列表排序
        handleSortChange({prop,order}) {
            this.tableParams.SortDesc = order==='ascending'?2:1
            this.tableParams.SortField = order?prop:'ViewTotal'
            this.handlePageChange(1,'sort')
         },
        //切换页码
        handlePageChange(page,type) {
            this.currentPage = page;
            this.getTableData(type);
        },
        //跳转至客户详情
        toCustomDetail(data) { 
            const path = data.Source===1?'/detailCustomEn':'/customDetail'
            const query = {
                ...data.Source===1?{
                    companyId:data.CompanyId - 10000000
                }:{
                    id:data.CompanyId
                },
                from:'overseas'
            }
            const href = this.$router.resolve({path,query}).href
            window.open(href,"_blank")
        },
        //设置客户的试用状态
        handleChangeTryStatus(data) {
            const { OverseasLabel, CompanyId } = data;
            overseasCustomInterence.setCustomTryStatus({
                CompanyId,OverseasLabel
            }).then(res=>{
                if(res.Ret!==200) return 
                this.$message.success("设置成功")
                this.getTableData()
            })
        },
        //打开累计点击量/路演数量弹窗
        handleDialogShow(type,data){
            this.customData = data
            if(type==='click'){
                if(!data.ViewTotal>0) return
                this.isTotalClickShow = true
            }else{
                if(!data.RoadShowTotal>0) return
                this.isRoadDetailShow = true
            }
        },
        //设置客户隐藏/取消隐藏
        handleSetCustomHide({CompanyId}){
            overseasCustomInterence.setCustomHide({CompanyId}).then(res=>{
                if(res.Ret!==200) return 
                this.$message.success(`设置${this.pageSelect===1?'隐藏':'取消隐藏'}成功`)
                this.handlePageChange(1)
            })
        },
        handleSetCustomStatus({CompanyId},type){
            overseasCustomInterence.setCustomStatus({CompanyId}).then(res=>{
                if(res.Ret!==200) return 
                this.$message.success(`${type==='reset'?'重置':'转正式'}成功`)
                this.handlePageChange(1)
            })
        },
    },
    mounted() {
        this.getSavedSales()
        this.getTableData('static');
    },
};
</script>

<style lang="scss">
.overseas-custom-list-wrap{
    .el-input--mini {
        .el-input__inner{
            padding: 0 6px !important;
            height: 24px;
            line-height: 24px;
            color: #409EFF;
            background: #ECF5FF;
            border-color: #409EFF;
            text-align: center;
        }
        .el-input__inner {
            border-color: #E4E7ED;
        }
        .el-input__suffix {
            display: none;
        }
    }
}
</style>
<style scoped lang="scss">
.overseas-custom-list-wrap{
    box-sizing: border-box;
    .top-box,.data-box{
        box-sizing: border-box;
        padding:30px;
        background-color: #fff;
    }
    .top-box{
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
    }
    .data-box{
        .data-select-box{
            display: flex;
            justify-content: space-between;
            align-items: center;
            ul{
                display: flex;
                align-items: center;
            }
            .status-box{
                .tab {
                    width: 129px;
                    height: 22px;
                    line-height: 22px;
                    text-align: center;
                    font-size: 14px;
                    border-right:1px solid #707070;
                    cursor: pointer;
                    transition-delay: 0.05s;
                    &:hover {
                        color: #409EFF;
                    }
                    &.act {
                        // padding: 9px 24px;
                        height: 40px;
                        line-height: 40px;
                        background: #409EFF;
                        border-radius: 4px;
                        color: #fff;
                        border-color: #409EFF;
                        transform: scale(1.014);
                    }
                    &:last-child {
                        border: none;
                    }
                }
            }
            .try-status-box{
                padding: 20px 0 0 30px;
                .trial-item {
                    cursor: pointer;
                    margin-right: 30px;
                    &:hover {
                        color: #409EFF;
                    }
                    &.act {
                        color: #409EFF;
                        position: relative;
                        &::after {
                            content: "";
                            width: 100%;
                            height: 2px;
                            position: absolute;
                            bottom: -10px;
                            left: 50%;
                            transform: translateX(-50%);
                            background: #409EFF;
                        }
                    }
                }
            }
        }
        .table-box{
            margin-top:20px;
            .status-box{
                display: flex;
                justify-content: center;
                .el-select{
                    margin-left: 10px;
                }
            }
            .editor{
                color:#409EFF;
                cursor: pointer;
                &:hover{
                    text-decoration: underline;
                }
            }
        }
    }
}
</style>
