<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage,ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { customInterence,reportVarietyENInterence } from '@/api/api.js'
import _ from 'lodash'
import mPage from '@/components/mPage.vue';
import clickNumberDetail from "./components/clickNumberDetailDia.vue"
import todoDialogEn from "./components/todoDialogEn.vue"
import historyToDoDiaEn from './components/historyToDoDiaEn.vue';
import country from "@/utils/countryData"
import UnDoStatistic from './components/UnDoStatistic.vue';
import ToDoTotalEdit from './components/ToDoTotalEdit.vue';
import reportVarietyEnSet from './components/reportVarietyEnSet.vue'

const router = useRouter()

const countryData=country

// 获取销售列表
const sellerList = ref([])
function getSellerList(){
  customInterence.saleslist({SellerType:1}).then(res=>{
    if(res.Ret == 200){
      sellerList.value = res.Data.List || []
    }
  })
}
getSellerList()


/* 获取销售 */
//销售筛选
const sales = ref([])
const salesArr = ref([])
function getSale() {
  customInterence.getSale({Status:0}).then(res => {
      if(res.Ret === 200) {
          salesArr.value = res.Data.List||[];
      }
  })
}
getSale()



// 获取列表
const searchParams = reactive({
  Keywords:"",
  CurrentIndex:1,
  PageSize:10,
  SortType:"",
  SortParam:""
})
const dataList = ref([])
const total = ref(0)
const varietyVal = ref([])
function getList(type=''){
  if(type=='search'){
    searchParams.CurrentIndex=1
  }
  const arr=[]
  varietyVal.value&&varietyVal.value.forEach(_e => {
    arr.push(_e[1])
  });
  customInterence.getCustomListEn({
      ...searchParams,
      EnPermissionIds:arr.join(','),
      Sellers:sales.value.join(',')
  }).then(res=>{
    // console.log(res);
    if(res.Ret == 200){
      dataList.value = res.Data.List || []
      total.value = res.Data.Paging.Totals
    }
  })
}
getList()


 //切换页码
function pageChange(page_no){
  searchParams.CurrentIndex=page_no
  getList()
}
function refreshList(){
  searchParams.Keywords="",
  searchParams.CurrentIndex=1,
  searchParams.PageSize=8,
  searchParams.SortType="",
  searchParams.SortParam=""

  varietyVal.value=[]
  getList()
}
// 累计点击量排序
function sortChange({order,prop}){
  console.log('order',order)
  const sortParamMap = {
    "todoStatus":"todoStatusStr",
    "dlDay":"deadLine"
  }
  if(sortParamMap[prop]){
    const {SortParam} = searchParams
    searchParams.SortParam = SortParam === sortParamMap[prop]?'':sortParamMap[prop]
    searchParams.SortType=''
  }else{
    searchParams.SortParam = ''
    searchParams.SortType=order=="descending"?'1':order=="ascending"?'2':'0'
  }
  getList()
}



// 获取英文品种权限数据
const varietyOpt = ref([])
function getENReportVarietyOpts(){
  reportVarietyENInterence.filterVarietyOpts({}).then(res=>{
    varietyOpt.value=res
  })
}
getENReportVarietyOpts()



 // ----------------------------------TODO
 const todoInfo = ref({}) // todo数据项
const todoDialogShow = ref(false)// 是否打开新建/编辑 TODO的弹窗
const todoOptionType = ref("")// todo操作类型 新建、编辑、完成
const todoHistoryDialogShow = ref(false)
const isToDoTotalEditShow = ref(false)
const isUnDoStatisticShow = ref(false)
const todoFormRef = ref(null)
// 打开TODO弹窗
function openTodoEditDia(row,type){
  //打开新建/编辑/审核弹窗
  // console.log(row,type);
  todoInfo.value=row
  if(['新建','编辑',"完成"].includes(type)){
    todoOptionType.value = type
    todoDialogShow.value = true
  }else{
    todoHistoryDialogShow.value=true
  }
}
// 新建/编辑/审核确认提交
function todoSubmit(todo){
  let apiName;
  let param={}
  if(todoOptionType.value=='新建'){
    apiName = "addCustomToDoEn"
    param={
      CompanyId:todo.CompanyId,
      Description:todo.Description,
      EndTime:todo.EndTime
    }
  }else if(todoOptionType.value=='编辑'){
    apiName = "editCustomToDoEn"
    param={
      Id:todo.Id,
      CompanyId:todo.CompanyId,
      Description:todo.Description,
      EndTime:todo.EndTime
    }
  }else if(todoOptionType.value=='完成'){
    apiName = "finishCustomToDoEn"
    param={
      Id:todo.Id,
      Remark:todo.Remark
    }
  }
  customInterence[apiName](param).then(res=>{
    if(res.Ret==200){
      ElMessage.success(todoOptionType.value+'任务成功')
      if(todoOptionType.value!='编辑'){
        getList()
      }
    }
  })
}
function changeEnabled(data){
  const {CompanyId,Enabled} = data
  const enabled = Enabled===1?0:1
  customInterence.editEnabledAll({
    CompanyId,Enabled:enabled
  }).then(res=>{
    if(res.Ret!==200) return 
    ElMessage.success(`${Enabled===1?'禁用':'启用'}成功`)
    getList()
  })
}
// 根据todo的状态选择颜色
function selectTodoColor(TodoButtonColor){
  return TodoButtonColor=='gray'?"#D9D9D9":TodoButtonColor=='red'?"#D1433A":"#4EC225"
}
// 根据todo的状态选择操作按钮
function selectTodoOption(TodoInfo){
  if(TodoInfo.TodoStatus){
    if(!TodoInfo.HiddenConfirm){
      return ["编辑","完成","历史"]
    }else{
      return ["编辑","历史"]
    }
  }else{
    return ["新建","历史"]
  }
}



// -------------------------------------------添加客户
function openAddUserDia(){
  const { href } = router.resolve({
    path:'/addCustomEn',
  });
  window.open(href, '_blank');
}

 //查看客户看详情
function customDetail(row){
  const { href } = router.resolve({
  path:'/detailCustomEn',
  query:{
    companyId:row.CompanyId,
  }});
  window.open(href, '_blank');
}

 // 编辑客户
function editCustom(row){
  const { href } = router.resolve({
  path:'/editCustomEn',
  query:{
    companyId:row.CompanyId,
  }});
  window.open(href, '_blank');
}


 // 删除客户
function delCustom(row){
  ElMessageBox.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){
        ElMessage.success("删除客户成功")
        getList()
      }
    })
  }).catch(() => {});
}


  // -----------------------------点击量详情
const showClickNumberDia = ref(false)
const clickNumberDetailItem = reactive({
  customerName:"",
  customerId:0
})
function clickNumberDetailHandle(row){
  clickNumberDetailItem.customerName = row.CompanyName
  clickNumberDetailItem.customerId = row.CompanyId
  showClickNumberDia.value=true
}



const showSetVariety = ref(false)
const checkedVariety = ref([])
const activeItem = ref({})//当前编辑权限的客户信息
const varietyInsRef = ref(null)
function handleSaveVariety(){
  let params={
    CompanyId:activeItem.value.CompanyId,
    EnPermissions:varietyInsRef.value.checkedItems||[]
  }
  // console.log(params);
  customInterence.setENCustomReportVariety(params).then(res=>{
    if(res.Ret===200){
      ElMessage.success('设置成功')
      refreshList()
      showSetVariety=false
    }
  })
}
function handleShowSetVariety(item){
  activeItem.value=item
  checkedVariety.value=_.cloneDeep(item.EnPermissions||[]) 
  showSetVariety.value=true
}

function handleChangeVariety(){

  searchParams.Keywords="",
  searchParams.CurrentIndex=1,
  searchParams.PageSize=8,
  searchParams.SortType="",
  searchParams.SortParam=""

  getList()
}



</script>
<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"
        >
          <template #prefix>
						<el-icon><Search /></el-icon>
					</template>
        </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 #default="{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 #header>
							<div class="todolabel" :class="{sort:searchParams.SortParam=='todoStatusStr'}" style="display:inline-block;">
								<span>To-Do</span>
							</div>
						</template>
            <template #default="{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 #header>
              <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 #default="{row}">
              {{row.TodoInfo.Deadline || '--'}}
            </template>
          </el-table-column>
          <el-table-column label="所属国家" align="center" prop="Country">
            <template #default="{row}">
              {{row.Country}}
            </template>
          </el-table-column>
          <el-table-column label="所属销售" align="center" prop="SellerName">
            <template #default="{row}">
              {{row.SellerName}}
            </template>
          </el-table-column>
          <el-table-column label="累计点击量" align="center" 
          width="140" prop="ViewTotal" sortable="custom">
            <template #default="{row}">
              <span class="table-options" @click="clickNumberDetailHandle(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 #default="{row}">
              {{row.CreateTime}}
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" show-overflow-tooltip prop="CreateTime">
            <template #default="{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 #default="{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>
          <template #empty>
            <div class="table-noData">
              <img src="~@/assets/img/cus_m/nodata.png">
              <span>暂无数据</span>
            </div>
          </template>
      </el-table>
    </div>
    <!-- 页数选择器 -->
    <m-page
      :page_no="searchParams.CurrentIndex"
      :pageSize="searchParams.PageSize"
      :total="total"
      style="position: absolute;right: 50px;bottom: 50px;"
      @handleCurrentChange="pageChange"
    />

    <!-- 详情弹窗 -->
    <click-number-detail :visible="showClickNumberDia" 
    :name="clickNumberDetailItem.customerName" 
    :id="clickNumberDetailItem.customerId"></click-number-detail>
    <!-- to do新建/编辑/完成弹窗 -->
    <todo-dialog-en :visible="todoDialogShow" :todoInfo="todoInfo" 
     @todoConfirm="todoSubmit" :option-type="todoOptionType" @close="todoDialogShow=false"></todo-dialog-en>
     <!-- to do历史弹窗 -->
     <history-to-do-dia-en :visible="todoHistoryDialogShow" :todoInfo="todoInfo" @close="todoHistoryDialogShow=false"></history-to-do-dia-en>
     <!-- 未完成to-do统计弹窗 -->
     <un-do-statistic :visible="isUnDoStatisticShow" @close="isUnDoStatisticShow=false"></un-do-statistic>
     <!-- To-Do编辑框弹窗 -->
     <to-do-total-edit :visible="isToDoTotalEditShow" @close="isToDoTotalEditShow=false"></to-do-total-edit>
    <!-- 配置权限 -->
    <el-dialog 
      title="权限配置" 
      v-model="showSetVariety" 
      width="705px"
      append-to-body 
      :close-on-click-modal="false"
    >
      <div style="padding:10px 40px">
        <reportVarietyEnSet ref="varietyInsRef" :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>
<style scoped lang="scss">
#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;
        }
      }
    }

    :deep(.todolabel){
			&+span.caret-wrapper{
				.sort-caret.ascending{
					border-bottom-color: #C0C4CC;
				}
				.sort-caret.descending{
					border-top-color: #C0C4CC
				}
			}
		}
		:deep(.todolabel.sort){
			&+span.caret-wrapper{
				.sort-caret.ascending{
					border-bottom-color: #409EFF;
				}
			}
		}
  }
</style>