<script setup>
import { reactive, ref,onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router';
import { customInterence } from '@/api/api.js'
import { ElImageViewer,ElMessage,ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { useClickNumDia } from "../custom/hooks/customlistHook";
import mPage from '@/components/mPage.vue';
import clickNumberDetail from "./components/clickNumberDetailDia.vue"
import country from "@/utils/countryData"
import ContactSaveEnDia from './components/ContactSaveEnDia.vue';
import reportVarietyEnSet from './components/reportVarietyEnSet.vue'

const $router = useRouter()
const $route = useRoute()

const countryData=country

const {showClickTimesDia,clickTimesDetailItem,clickTimesDetail,closeNumDia,} = useClickNumDia(); //点击量详情弹窗

onMounted(()=> {
  if($route.path == '/addCustomEn'){
    getSellerList()
    return
  } 
  if(!$route.query.companyId){
    // 无客户信息
    $router.replace('/customListEn')
    return 
  }

  getSellerList()
  customDetail()
  getList()
})

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


// edit 编辑英文客户 英文客户详情
const viewType = ref($route.path == '/detailCustomEn'?'detail':'edit')
const editForm = reactive({
  CompanyId:Number($route.query.companyId)||0,
  CompanyName:"",
  CountryCode:"",
  Country:"",
  SellerId:""
})

const varietyOpts = ref([])
// 客户详情
function customDetail(){
  customInterence.customDetailEn({CompanyId:editForm.CompanyId}).then(res=>{
    if(res.Ret == 200){
      editForm.CompanyName=res.Data.CompanyName
      editForm.Country=res.Data.Country
      editForm.CountryCode=res.Data.CountryCode
      editForm.SellerId=res.Data.SellerId
      varietyOpts.value=res.Data.EnPermissions
    }else{
      $router.replace('/customListEn')
    }
  })
}


// 联系人列表搜索参数
const searchParams = reactive({
  CompanyId:$route.query.companyId||0,
  CurrentIndex:1,
  PageSize:8,
  SortType:"",
  Keywords:""
})
const total = ref(0)
  // 联系人列表
const contactsList = ref([])
function getList(type=''){
  if(type=="search"){
    searchParams.CurrentIndex=1
  }
  customInterence.getContactsListEn(searchParams).then(res=>{
    if(res.Ret == 200){
      contactsList.value = res.Data.List || []
      total.value = res.Data.Paging.Totals
    }
  })
}
// 累计点击量排序
function clickTimesSortChange({order}){
  searchParams.SortType=order=="ascending"?'2':order=="descending"?'1':''
  getList()
}
// 重置列表和搜索项
function refreshList(){
  searchParams.SortType=""
  searchParams.Keywords=""
  searchParams.CurrentIndex=1
  getList()
}
function pageChange(page_no){
  searchParams.CurrentIndex=page_no
  getList()
}
function updateList(type){
  type=='refresh'?getList():refreshList()
}



 // 修改提交
const editFormRef = ref(null)
const varietyInsRef = ref(null)
function editSubmit(){
  editFormRef.value.validate(valid=>{
    if(valid){
      customInterence.addCustomEn({
          ...editForm,
          EnPermissions:varietyInsRef.value.checkedItems||[],
          Nation:editForm.Country
      }).then(res=>{
        if(res.Ret == 200){
          let messageEle=ElMessage.success($route.path == '/addCustomEn'?'添加客户成功':'编辑客户成功')
          setTimeout(()=>{
            messageEle.close()
            editCancel()
          },1000)
        }
      })
    }
  })
}
// 取消修改
function editCancel(){
  //this.$router.back()
  $router.push({path:'/customListEn'})
}



// -----------------------英文客户详情独有方法
// 去编辑用户
function toEdit(){
  $router.replace({path:'/editCustomEn',query:{companyId:editForm.CompanyId}})
  viewType.value="edit"
}
// 删除客户
function customDelete(){
  ElMessageBox.confirm(`是否确认删除客户<span style="color:#409EFF">${editForm.CompanyName}</span>，并删除该客户下所有的联系人？`,"操作提示",
  {
    type:"warning",
    dangerouslyUseHTMLString:true,
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  }).then(res=>{
    customInterence.delCustomEn({CompanyId:editForm.CompanyId}).then(res=>{
      if(res.Ret == 200){
        ElMessage.success("删除客户成功")

        setTimeout(()=>{

          $router.push({path:'/customListEn'})
        },1000)
      }
    })
  }).catch(() => {});
}


// -------------------------------------添加/编辑联系人
const dialogTitle = ref("添加联系人")
const showAddDia = ref(false)
const contactsSubmitForm = ref({})
//添加联系人
function addContacts(){
  contactsSubmitForm.value={}
  dialogTitle.value="添加联系人"
  showAddDia.value=true
}
// 编辑联系人
function editContacts(row){
  contactsSubmitForm.value=row
  dialogTitle.value="编辑联系人"
  showAddDia.value=true
}
// -----------------------------上传批量导入模板
function templateUpload(file){
  let formData = new FormData()
  formData.append('File',file.file)
  formData.append('CompanyId',editForm.CompanyId)
  customInterence.importContactsEn(formData).then(res=>{
    if(res.Ret == 200){
      ElMessage.success('批量导入成功')
      refreshList()
    }
  })
}
// 删除联系人
function delContacts(row){
  ElMessageBox.confirm(`是否确认删除联系人<span style="color:#409EFF">${row.Name}</span>？`,"操作提示",
  {
    type:"warning",
    dangerouslyUseHTMLString:true,
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(res=>{
    customInterence.delContactsEn({EmailId:row.Id}).then(res=>{
      if(res.Ret == 200){
        ElMessage.success("删除联系人成功")
        getList()
      }
    })

  }).catch(() => {});
} 
//启用禁用联系人
function changeStatus(row){
  customInterence.editEnabledEn({
    EmailId:row.Id,
    Enabled:row.Enabled===1?0:1
  }).then(res=>{
    if(res.Ret!==200) return 
    ElMessage.success('操作成功')
    getList()
  })
}


/* 预览名片 */
const imgView = ref('')
const showViewer = ref(false)
function reviewCard(card) {

  showViewer.value = true;
  imgView.value = card;
}
/* 关闭预览 */
function closeViewer() {
  imgView.value = '';
  showViewer.value = false;
}



</script>
<template>
  <div id="edit-custom-container">
    <!-- 编辑客户区域 -->
    <div class="edit-custom-zone">
      <el-form :model="editForm" inline ref="editFormRef" style="flex:1">
        <el-form-item label="客户名称" prop="CompanyName" :rules="{required:true,message:'客户名称不能为空',trigger:'blur'}">
          <el-input v-model="editForm.CompanyName" placeholder="请输入客户名称" style="width: 337px;" :disabled="viewType=='detail'"></el-input>
        </el-form-item>
        <el-form-item label="所属国家" prop="CountryCode" :rules="{required:true,message:'所属国家不能为空',trigger:'change'}">
          <el-select v-model="editForm.CountryCode" placeholder="请选择" filterable style="width: 337px;" :disabled="viewType=='detail'">
            <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>
        <br/>
        <el-form-item label="所属销售" prop="SellerId" :rules="{required:true,message:'所属销售不能为空',trigger:'change'}">
          <el-select v-model="editForm.SellerId" placeholder="请选择" style="width: 337px;" filterable :disabled="viewType=='detail'">
            <el-option :label="item.RealName" :value="item.AdminId" v-for="item in sellerList" :key="item.AdminId"></el-option>
          </el-select>
        </el-form-item>
        <div class="variety-set-wrap">
          <el-form-item label="权限配置" :rules="{required:true,message:'请选择权限',trigger:'change'}">
            <div class="con">
              <reportVarietyEnSet ref="varietyInsRef" v-if="editForm.CompanyName||$route.path == '/addCustomEn'" :checked="varietyOpts" :disabled="viewType=='edit'?false:true"/>
            </div>
          </el-form-item>
        </div>
      </el-form>
      <div class="edit-zone-options">
        <template v-if="viewType=='edit'">
          <el-button type="primary" style="width:120px;margin-right: 6px;"  @click="editSubmit">保存</el-button>
          <el-button  style="width:120px;"  @click="editCancel">取消</el-button>
        </template>
        <template v-else>
          <el-button type="primary" style="width:120px;margin-right: 6px;"  @click="toEdit">编辑</el-button>
          <el-button  style="width:120px;" @click="customDelete">删除</el-button>
        </template>
      </div>
    </div>
    <!-- 联系人区域 -->
    <div class="contacts-zone" v-if="$route.path != '/addCustomEn'">
      <div class="contacts-options-zone">
        <!-- 联系人操作区域 -->
        <div class="options-zone-buttons">
          <el-button type="primary" style="margin-right: 16px;" @click="addContacts">添加联系人</el-button>
          <el-upload action="#" :show-file-list="false" style="display: inline;" :http-request="templateUpload"
          accept=".xls,.xlsx">
            <el-button type="primary" style="width: 112px;margin-right: 26px;">批量导入</el-button>
          </el-upload>
          <a href="https://hzstatic.hzinsights.com/static/admin/excel/英文联系人批量导入模板.xlsx" download>批量导入模板</a>
        </div>
        <div>
          <el-input v-model="searchParams.Keywords" placeholder="请输入联系人姓名/邮箱" @input="getList('search')"
          style="width: 520px;" clearable >
            <template #prefix>
              <el-icon><Search/></el-icon>
            </template>
          </el-input>
        </div>
      </div>
      <!-- 联系人列表区域 -->
      <div class="contacts-table-zone">
        <div style="overflow: auto;flex-grow: 1;">
          <el-table :data="contactsList" border @sort-change="clickTimesSortChange">
            <el-table-column label="联系人姓名" align="center" prop="Name">
              <template #default="{row}">
                <img 
                  :src="$icons.card"
                  alt="" 
                  style="width:17px;cursor:pointer;marginRight:5px;"
                  v-if="row.BusinessCardUrl"
                  @click="reviewCard(row.BusinessCardUrl)"
                />
                <span>{{row.Name}}</span>
              </template>
            </el-table-column>
            <el-table-column label="注册公司" align="center" prop="CompanyName">
              <template #default="{row}">
                {{row.CompanyName || '-'}}
              </template>
            </el-table-column>
            <el-table-column label="手机号" align="center" prop="Mobile">
              <template #default="{row}">
                {{row.CountryCode}}-{{row.Mobile}}
              </template>
            </el-table-column>
            <el-table-column label="注册时间" align="center" prop="RegisterTime">
              <template #default="{row}">
                {{row.RegisterTime || '-'}}
              </template>
            </el-table-column>
            <el-table-column label="邮箱地址" align="center" prop="Email">
              <template #default="{row}">
                {{row.Email}}
              </template>
            </el-table-column>
            <el-table-column label="累计点击量" align="center" sortable="custom" width="120"
            prop="ViewTotal">
              <template #default="{row}">
                <span class="table-options" @click="clickTimesDetail(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" prop="CreateTime" >
              <template #default="{row}">
                {{row.CreateTime}}
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="Enabled" >
              <template #default="{row}">
                <span :class="[row.Enabled===0?'hint':'']">{{row.Enabled?'启用':'禁用'}}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="120">
              <template #default="{row}">
                <span class="table-options" style="margin-right: 12px;" @click="editContacts(row)">编辑</span>
                <span class="table-options" style="margin-right: 12px;" @click="changeStatus(row)">{{row.Enabled?'禁用':'启用'}}</span>
                <span class="table-options" @click="delContacts(row)" style="color:#D1433A;">删除</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 页数选择器 -->
        <m-page
          v-show="total!=0"
          style="float: none;text-align: right;margin-top: 20px;"
          :page_no="searchParams.CurrentIndex"
          :pageSize="searchParams.PageSize"
          :total="total"
          @handleCurrentChange="pageChange"
        />
      </div>
    </div>
    <!-- 累计点击量详情弹窗 -->
    <click-number-detail :visible="showClickTimesDia" 
    :name="clickTimesDetailItem.contactsName" type="contacts"
    :id="clickTimesDetailItem.contactsId" @close="closeNumDia"></click-number-detail>
    <!-- 添加/编辑联系人 -->
    <contact-save-en-dia :contactsSubmitForm="contactsSubmitForm" :title="dialogTitle" :showAddDia="showAddDia"
     :companyId="searchParams.CompanyId" @updateList="updateList" @close="showAddDia=false"></contact-save-en-dia>

    <!-- 图片预览 -->
		<el-image-viewer 
		v-if="showViewer" 
		@close="closeViewer" 
		:urlList="[imgView]" />
  </div>
</template>
<style scoped lang="scss">
#edit-custom-container{
  .edit-custom-zone{
    padding: 30px 30px 10px 30px;
    display: flex;
    justify-content: space-between;
    border: 1px solid #ECECEC;
    background-color: white;
    border-radius: 2px;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
    margin-bottom: 20px;
    .edit-zone-options{
      min-width: 260px;
    }
  }
  .contacts-zone{
    border: 1px solid #ECECEC;
    background-color: white;
    border-radius: 2px;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
    padding: 30px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    .contacts-options-zone{
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      margin-bottom: 20px;
      .options-zone-buttons{
        margin-bottom: 10px;
        a{
          cursor: pointer;
          font-size: 16px;
          color: #409EFF;
          line-height: 40px;
        }
      }
    }
    .contacts-table-zone{
      .table-options{
        cursor: pointer;
        font-size: 14px;
        color: #409EFF;
      }
    }

  }
  .hint{
    color: red;
  }

  :deep(.el-form-item){
    margin-right: 100px;
  }
  :deep(.el-form-item:nth-child(2)){
    margin-right: 50px;
  }
  :deep(.el-form-item__label){
    color: black;
  }
  .img_item {
    position: relative;
    width: 280px;
    height: 180px;
    border-radius: 4px;
  }
  :deep(.variety-set-wrap){
      .el-form-item{
        width: 100%;
        .el-form-item__content{
          display: block;
          .con{
            border: 1px dashed #DCDFE6;
            border-radius: 4px;
            padding: 20px;
          }
        }
      }
    }
}
</style>