<template>
  <div id="custom-listEn-container">
    <!-- 顶部区域 -->
    <div class="top-zone">
      <div class="btn-box">
        <el-button type="primary" @click="openAddUserDia" style="height: 40px;width: 110px;">添加客户</el-button>
        <el-button type="primary" @click="isToDoTotalEditShow=true" style="height: 40px;width: 110px;padding:0;text-align:center;line-height:40px;">TO-DO编辑框</el-button>
        <el-button type="primary" @click="isUnDoStatisticShow=true" style="height: 40px;width: 110px;padding:0;text-align:center;line-height:40px;">未完成TO-DO</el-button>
      </div>
      <div>
        <el-cascader
            v-model="sales"
            placeholder="请选择销售"
            :options="salesArr"
            :props="{
                emitPath:false,
                multiple: true,
                label:'RealName',
                children:'ChildrenList',
                value:'AdminId'
            }"
            :show-all-levels="false"
            collapse-tags
            clearable
            filterable
            @change="getList('search')">
        </el-cascader>
        <el-cascader
          v-model="varietyVal"
          :options="varietyOpt"
          collapse-tags
          clearable
          :props="{
            multiple:true,
            value:'EnPermissionId',
            label:'EnPermissionName',
            children:'Child'
          }"
          placeholder="请选择阅读权限"
          @change="handleChangeVariety"
          style="margin-left:20px"
        />
        <el-input 
          v-model="searchParams.Keywords" 
          placeholder="请输入客户名称/邮箱/手机号" 
          @input="getList('search')"
          style="width: 520px;margin-left:20px"
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </div>
      
    </div>
    <!-- 表格区域 -->
    <div class="table-zone">
        <el-table :data="dataList" border @sort-change="sortChange">
          <el-table-column label="客户名称" align="center" prop="CompanyName">
            <template slot-scope="{row}">
              <span class="table-options" @click="customDetail(row)" >{{row.CompanyName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="To-Do" align="center" prop="todoStatus" sortable="custom">
            <template slot="header" slot-scope="{}">
							<div class="todolabel" :class="{sort:searchParams.SortParam=='todoStatusStr'}" style="display:inline-block;">
								<span>To-Do</span>
							</div>
						</template>
            <template slot-scope="{row}">
              <div class="todo-status-box">
                <div class="todo-status-flag" :style="'background-color:'+selectTodoColor(row.TodoInfo.TodoButtonColor)"></div>
                <div>
                  <div class="table-options" 
                  v-for="item in selectTodoOption(row.TodoInfo)" :key="item"
                  @click="openTodoEditDia(row,item)">
                    {{item}}
                  </div>
                </div>
              </div>
              <!-- {{row.todoStatus}} -->
            </template>
          </el-table-column>
          <el-table-column align="center" prop="dlDay" sortable="custom">
            <template slot="header" slot-scope="{}">
              <el-tooltip content="未完成To Do任务的截止日期-当前日期" placement="top-start">
                <div class="todolabel" :class="{sort:searchParams.SortParam=='deadLine'}" style="display:inline-block;">
                  <span>DL</span>
                  <i class="el-icon-warning-outline"></i>
                </div>
              </el-tooltip>
            </template>
            <template slot-scope="{row}">
              {{row.TodoInfo.Deadline || '--'}}
            </template>
          </el-table-column>
          <el-table-column label="所属国家" align="center" prop="Country">
            <template slot-scope="{row}">
              {{row.Country}}
            </template>
          </el-table-column>
          <el-table-column label="所属销售" align="center" prop="SellerName">
            <template slot-scope="{row}">
              {{row.SellerName}}
            </template>
          </el-table-column>
          <el-table-column label="累计点击量" align="center" 
          width="140" prop="ViewTotal" sortable="custom">
            <template slot-scope="{row}">
              <span class="table-options" @click="clickNumberDetail(row)" v-if="row.ViewTotal!=0">{{row.ViewTotal}}</span>
              <span v-else>{{row.ViewTotal}}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" show-overflow-tooltip prop="CreateTime">
            <template slot-scope="{row}">
              {{row.CreateTime}}
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" show-overflow-tooltip prop="CreateTime">
            <template slot-scope="{row}">
              <span :style="`color:${row.Enabled!==1?'red':''}`">{{row.Enabled===0?'禁用':row.Enabled===1?'启用':'部分禁用'}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="{row}">
              <span class="table-options option-button" @click="handleShowSetVariety(row)">权限配置</span>
              <span class="table-options option-button" @click="editCustom(row)">编辑</span>
              <span class="table-options option-button" @click="changeEnabled(row)">{{row.Enabled===1?'禁用':'启用'}}</span>
              <span class="table-options option-button" @click="delCustom(row)" style="color:#D1433A;">删除</span>
            </template>
          </el-table-column>
          <div slot="empty" class="table-noData">
            <img src="~@/assets/img/cus_m/nodata.png">
            <span>暂无数据</span>
          </div>
      </el-table>
    </div>
    <!-- 页数选择器 -->
    <m-page
      :page_no="searchParams.CurrentIndex"
      :pageSize="searchParams.PageSize"
      :total="total"
      style="position: absolute;right: 50px;bottom: 50px;"
      @handleCurrentChange="pageChange"
    />
    <!-- 添加客户弹窗 -->
    <el-dialog title="添加客户" :visible.sync="showAddUserDia" width="625px"
    append-to-body :close-on-click-modal="false">
      <div style="display: flex;flex-direction: column; align-items: center;margin-bottom: 35px;">
        <el-form :model="addUserForm" ref="addUserForm" label-width="80px">
          <el-form-item label="客户名称" prop="companyName" :rules="{required:true,message:'客户名称不能为空',trigger:'blur'}">
            <el-input v-model="addUserForm.companyName" placeholder="请输入客户名称" style="width: 337px;"></el-input>
          </el-form-item>
          <el-form-item label="所属国家" prop="countryCode" :rules="{required:true,message:'所属国家不能为空',trigger:'change'}">
            <el-select v-model="addUserForm.countryCode" placeholder="请选择" filterable style="width: 337px;">
              <el-option :label="item.cnName" :value="item.code" 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-form-item>
          <el-form-item label="所属销售" prop="seller" :rules="{required:true,message:'所属销售不能为空',trigger:'change'}">
            <el-select v-model="addUserForm.seller" placeholder="请选择" style="width: 337px;" filterable>
              <el-option :label="item.RealName" :value="item.AdminId" v-for="item in sellerList" :key="item.AdminId"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div style="margin-top: 40px;">
          <el-button type="primary" style="width:120px;margin-right:10px" @click="addUser" size="medium">确定</el-button>
          <el-button  style="width:120px;" @click="showAddUserDia=false" size="medium">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 详情弹窗 -->
    <click-number-detail :visible.sync="showClickNumberDia" 
    :name="clickNumberDetailItem.customerName" 
    :id="clickNumberDetailItem.customerId"></click-number-detail>
    <!-- to do新建/编辑/完成弹窗 -->
    <todo-dialog-en :visible.sync="todoDialogShow" :todoInfo="todoInfo" 
     @todoConfirm="todoSubmit" ref="todoForm" :option-type="todoOptionType"></todo-dialog-en>
     <!-- to do历史弹窗 -->
     <history-to-do-dia-en :visible.sync="todoHistoryDialogShow" :todoInfo="todoInfo"></history-to-do-dia-en>
     <!-- 未完成to-do统计弹窗 -->
     <un-do-statistic :visible.sync="isUnDoStatisticShow"></un-do-statistic>
     <!-- To-Do编辑框弹窗 -->
     <to-do-total-edit :visible.sync="isToDoTotalEditShow"></to-do-total-edit>
    <!-- 配置权限 -->
    <el-dialog 
      title="权限配置" 
      :visible.sync="showSetVariety" 
      width="705px"
      append-to-body 
      :close-on-click-modal="false"
    >
      <div style="padding:10px 40px">
        <reportVarietyEnSet ref="varietyIns" :checked="checkedVariety" v-if="showSetVariety" />
      </div>
      <div style="text-align:center;padding:10px 0 30px 0">
        <el-button type="primary" plain @click="showSetVariety=false">取消</el-button>
        <el-button type="primary" style="margin-left:20px" @click="handleSaveVariety">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import mPage from '@/components/mPage.vue';
import clickNumberDetail from "../compontents/clickNumberDetailDia.vue"
import todoDialogEn from "../compontents/todoDialogEn.vue"
import historyToDoDiaEn from '../compontents/historyToDoDiaEn.vue';
import country from "@/utils/countryData"
import { customInterence,reportVarietyENInterence } from '@/api/api.js'
import UnDoStatistic from '../compontents/UnDoStatistic.vue';
import ToDoTotalEdit from '../compontents/ToDoTotalEdit.vue';
import reportVarietyEnSet from '@/components/reportVarietyEnSet.vue'

  export default {
    name:"customListEn",
    components:{mPage,clickNumberDetail,todoDialogEn,historyToDoDiaEn, UnDoStatistic, ToDoTotalEdit,reportVarietyEnSet},
    watch:{
      'addUserForm.countryCode':{
        handler(newVal){
          this.addUserForm.countryName = newVal?this.countryData.find(item => item.code == newVal).cnName:''
        }
      }
    },
    data() {
      // 不监听 countryData 数组里面的数据 - 即国家数据
      this.countryData=country

      return {
        searchParams:{
          Keywords:"",
          CurrentIndex:1,
          PageSize:10,
          SortType:"",
          SortParam:""
        }, 
        dataList:[],
        // 销售列表
        sellerList:[],
        total:0,
        //  -----------------------添加客户
        showAddUserDia:false, // 显示添加客户弹窗
        addUserForm:{
          companyName:"",
          countryCode:"",
          countryName:"",
          seller:""
        },
        // ------------------------点击量详情
        showClickNumberDia:false,
        clickNumberDetailItem:{
          customerName:"",
          customerId:""
        },
        // ----------------------------TODO弹窗
        todoInfo:{}, // todo数据项
        todoDialogShow:false,// 是否打开新建/编辑 TODO的弹窗
        todoOptionType:"",// todo操作类型 新建、编辑、完成
        todoHistoryDialogShow:false,
        isToDoTotalEditShow:false,
        isUnDoStatisticShow:false,

        //品种筛选
        varietyVal:[],
        varietyOpt:[],
        showSetVariety:false,
        checkedVariety:[],
        activeItem:{},//当前编辑权限的客户信息

        //销售筛选
        sales:[],
        salesArr:[]
      }
    },
    created(){
      this.getList()
      this.getSellerList()
      this.getENReportVarietyOpts()
      this.getSale()
    },  
    methods: {
      handleSaveVariety(){

        let params={
          CompanyId:this.activeItem.CompanyId,
          EnPermissions:this.$refs.varietyIns.checkedItems||[]
        }
        // console.log(params);
        customInterence.setENCustomReportVariety(params).then(res=>{
          if(res.Ret===200){
            this.$message.success('设置成功')
            this.refreshList()
            this.showSetVariety=false
          }
        })
      },
      // 获取英文品种权限数据
      getENReportVarietyOpts(){
        reportVarietyENInterence.filterVarietyOpts({}).then(res=>{
          this.varietyOpt=res
        })
      },
      handleShowSetVariety(item){
        this.activeItem=item
        this.checkedVariety=_.cloneDeep(item.EnPermissions||[]) 
        this.showSetVariety=true
      },
      handleChangeVariety(){
        this.searchParams={
          Keywords:"",
          CurrentIndex:1,
          PageSize:8,
          SortType:"",
          SortParam:""
        }
        this.getList()
      },
      // 根据todo的状态选择颜色
      selectTodoColor(TodoButtonColor){
        return TodoButtonColor=='gray'?"#D9D9D9":TodoButtonColor=='red'?"#D1433A":"#4EC225"
      },
      // 根据todo的状态选择操作按钮
      selectTodoOption(TodoInfo){
        if(TodoInfo.TodoStatus){
          if(!TodoInfo.HiddenConfirm){
            return ["编辑","完成","历史"]
          }else{
            return ["编辑","历史"]
          }
        }else{
          return ["新建","历史"]
        }
      },
      // 获取销售列表
      getSellerList(){
        customInterence.saleslist({SellerType:1}).then(res=>{
          if(res.Ret == 200){
            this.sellerList = res.Data.List || []
          }
        })
      },
      // 获取列表
      getList(type=''){
        if(type=='search'){
          this.searchParams.CurrentIndex=1
        }
        const arr=[]
        this.varietyVal&&this.varietyVal.forEach(_e => {
          arr.push(_e[1])
        });
        customInterence.getCustomListEn({
            ...this.searchParams,
            EnPermissionIds:arr.join(','),
            Sellers:this.sales.join(',')
        }).then(res=>{
          // console.log(res);
          if(res.Ret == 200){
            this.dataList = res.Data.List || []
            this.total = res.Data.Paging.Totals
          }
        })
      },
      refreshList(){
        this.searchParams={
          Keywords:"",
          CurrentIndex:1,
          PageSize:8,
          SortType:"",
          SortParam:""
        }
        this.varietyVal=[]
        this.getList()
      },
      //切换页码
      pageChange(page_no){
        this.searchParams.CurrentIndex=page_no
        this.getList()
      },
      // 累计点击量排序
      sortChange({order,prop}){
        console.log('order',order)
        const sortParamMap = {
          "todoStatus":"todoStatusStr",
          "dlDay":"deadLine"
        }
        if(sortParamMap[prop]){
          const {SortParam} = this.searchParams
          this.searchParams.SortParam = SortParam === sortParamMap[prop]?'':sortParamMap[prop]
          this.searchParams.SortType=''
        }else{
          this.searchParams.SortParam = ''
          this.searchParams.SortType=order=="descending"?'1':order=="ascending"?'2':'0'
        }
        this.getList()
      },
      // -------------------------------------------打开添加客户弹窗
      openAddUserDia(){
        const { href } = this.$router.resolve({
				  path:'/addCustomEn',
        });
      	window.open(href, '_blank');
        // this.addUserForm={
        //   companyName:"",
        //   countryCode:"",
        //   countryName:"",
        //   seller:""
        // }
        // this.$nextTick(()=>{
        //   this.$refs.addUserForm && this.$refs.addUserForm.clearValidate()
        // })
        // this.showAddUserDia=true
      },
      // 添加客户
      addUser(){
        this.$refs.addUserForm.validate(valid=>{
          if(valid){
            let param={
              CompanyName:this.addUserForm.companyName,
              CountryCode:this.addUserForm.countryCode,
              Country:this.addUserForm.countryName,
              SellerId:this.addUserForm.seller
            }
            // console.log(param);
            customInterence.addCustomEn(param).then(res=>{
              if(res.Ret == 200){
                this.showAddUserDia=false
                this.$message.success('添加客户成功')
                this.refreshList()
              }
            })
          }
        })
      },
      //查看客户看详情
      customDetail(row){
        const { href } = this.$router.resolve({
				path:'/detailCustomEn',
				query:{
					companyId:row.CompanyId,
				}});
      	window.open(href, '_blank');
        //this.$router.push({path:"/detailCustomEn",query:{companyId:row.CompanyId}})
      },
      // 编辑客户
      editCustom(row){
        const { href } = this.$router.resolve({
				path:'/editCustomEn',
				query:{
					companyId:row.CompanyId,
				}});
      	window.open(href, '_blank');
        //this.$router.push({path:"/editCustomEn",query:{companyId:row.CompanyId}})
      },
      // -----------------------------点击量详情
      clickNumberDetail(row){
        this.clickNumberDetailItem.customerName = row.CompanyName
        this.clickNumberDetailItem.customerId = row.CompanyId
        this.showClickNumberDia=true
      },
      // 删除客户
      delCustom(row){
        this.$confirm(`是否确认删除客户<span style="color:#409EFF">${row.CompanyName}</span>，并删除该客户下所有的联系人？`,"操作提示",
        {
          type:"warning",
          dangerouslyUseHTMLString:true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        }).then(res=>{
          customInterence.delCustomEn({CompanyId:row.CompanyId}).then(res=>{
            if(res.Ret == 200){
              this.$message.success("删除客户成功")
              this.getList()
            }
          })
        }).catch(() => {});
      },
      // ----------------------------------TODO
      // 打开TODO弹窗
      openTodoEditDia(row,type){
        //打开新建/编辑/审核弹窗
        // console.log(row,type);
        this.todoInfo=row
        if(['新建','编辑',"完成"].includes(type)){
          this.todoOptionType = type
          this.todoDialogShow = true
        }else{
          this.todoHistoryDialogShow=true
        }
      },
      // 新建/编辑/审核确认提交
      todoSubmit(todo){
        let apiName;
        let param={}
        if(this.todoOptionType=='新建'){
          apiName = "addCustomToDoEn"
          param={
            CompanyId:todo.CompanyId,
            Description:todo.Description,
            EndTime:todo.EndTime
          }
        }else if(this.todoOptionType=='编辑'){
          apiName = "editCustomToDoEn"
          param={
            Id:todo.Id,
            CompanyId:todo.CompanyId,
            Description:todo.Description,
            EndTime:todo.EndTime
          }
        }else if(this.todoOptionType=='完成'){
          apiName = "finishCustomToDoEn"
          param={
            Id:todo.Id,
            Remark:todo.Remark
          }
        }
        customInterence[apiName](param).then(res=>{
          if(res.Ret==200){
            this.$refs.todoForm.closeDia()
            this.$message.success(this.todoOptionType+'任务成功')
            if(this.todoOptionType!='编辑'){
              this.getList()
            }
          }
        })
      },
      changeEnabled(data){
        const {CompanyId,Enabled} = data
        const enabled = Enabled===1?0:1
        customInterence.editEnabledAll({
          CompanyId,Enabled:enabled
        }).then(res=>{
          if(res.Ret!==200) return 
          this.$message.success(`${Enabled===1?'禁用':'启用'}成功`)
          this.getList()
        })
      },
      /* 获取销售 */
      getSale() {
        customInterence.getSale({Status:0}).then(res => {
            if(res.Ret === 200) {
                this.salesArr = res.Data.List||[];
            }
        })
      },
    },
  }
</script>

<style lang="scss">
  #custom-listEn-container{
    .todolabel{
			&+span.caret-wrapper{
				.sort-caret.ascending{
					border-bottom-color: #C0C4CC;
				}
				.sort-caret.descending{
					border-top-color: #C0C4CC
				}
			}
		}
		.todolabel.sort{
			&+span.caret-wrapper{
				.sort-caret.ascending{
					border-bottom-color: #409EFF;
				}
			}
		}
  }
</style>
<style lang="scss" scoped>
  #custom-listEn-container{
    display: flex;
    flex-direction: column;
    height:calc(100vh - 110px);
    background-color: white;
    border: 1px solid #ECECEC;
    border-radius: 2px;
    box-sizing: border-box;
    padding: 20px 30px 30px 30px;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
    .top-zone{
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;
    }
    .table-zone{
      overflow: auto;
      flex-grow: 1;
      margin-top: 10px;
      margin-bottom: 50px;
      .todo-status-box{
        display: flex;
        justify-content: center;
        align-items: center;
        .todo-status-flag{
          width: 10px;
          height: 10px;
          border-radius: 50%;
          margin-right: 20px;
        }
      }
      .table-options{
        cursor: pointer;
        font-size: 14px;
        color: #409EFF;
      }
      .option-button{
        white-space:nowrap;
        margin: 0 6px;
      }
      .table-noData{
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        margin: 18vh 0;
        img{
          height: 110px;
          width: 136px;
        }
        span{
          font-weight: 400;
          font-size: 16px;
          color: #999999;
        }
      }
    }
  }
</style>