<template>
  <div id="edit-custom-container">
    <!-- 编辑客户区域 -->
    <div class="edit-custom-zone">
      <el-form :model="editForm" inline size="medium" ref="editForm" 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="varietyIns" 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;" size="medium" @click="editSubmit">保存</el-button>
          <el-button  style="width:120px;" size="medium" @click="editCancel">取消</el-button>
        </template>
        <template v-else>
          <el-button type="primary" style="width:120px;margin-right: 6px;" size="medium" @click="toEdit">编辑</el-button>
          <el-button  style="width:120px;" size="medium" @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 >
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </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 slot-scope="{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 slot-scope="{row}">
                {{row.CompanyName || '-'}}
              </template>
            </el-table-column>
            <el-table-column label="手机号" align="center" prop="Mobile">
              <template slot-scope="{row}">
                {{row.CountryCode}}-{{row.Mobile}}
              </template>
            </el-table-column>
            <el-table-column label="注册时间" align="center" prop="RegisterTime">
              <template slot-scope="{row}">
                {{row.RegisterTime || '-'}}
              </template>
            </el-table-column>
            <el-table-column label="邮箱地址" align="center" prop="Email">
              <template slot-scope="{row}">
                {{row.Email}}
              </template>
            </el-table-column>
            <el-table-column label="累计点击量" align="center" sortable="custom" width="120"
            prop="ViewTotal">
              <template slot-scope="{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 slot-scope="{row}">
                {{row.CreateTime}}
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="Enabled" >
              <template slot-scope="{row}">
                <span :class="[row.Enabled===0?'hint':'']">{{row.Enabled?'启用':'禁用'}}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="120">
              <template slot-scope="{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.sync="showClickTimesDia" 
    :name="clickTimesDetailItem.contactsName" type="contacts"
    :id="clickTimesDetailItem.contactsId"></click-number-detail>
    <!-- 添加/编辑联系人 -->
    <contact-save-en-dia :contactsSubmitForm="contactsSubmitForm" :title="dialogTitle" :showAddDia.sync="showAddDia"
     :companyId="searchParams.CompanyId" @updateList="updateList"></contact-save-en-dia>

    <!-- 图片预览 -->
		<el-image-viewer 
		v-if="showViewer" 
		:on-close="closeViewer" 
		:url-list="[imgView]" />
  </div>
</template>

<script>
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import mPage from '@/components/mPage.vue';
import clickNumberDetail from "../compontents/clickNumberDetailDia.vue"
import ContactSaveEnDia from './components/ContactSaveEnDia.vue';
import country from "@/utils/countryData"
import { customInterence } from '@/api/api.js'
import reportVarietyEnSet from '@/components/reportVarietyEnSet.vue'

  export default {
    name:"editCustomEn",
    components:{mPage,clickNumberDetail,ElImageViewer,ContactSaveEnDia,reportVarietyEnSet},
    watch:{
      'editForm.CountryCode':{
        handler(newVal){
          this.editForm.Country = newVal?this.countryData.find(item => item.code == newVal).cnName:''
        }
      }
    },
    data() {
      // 不监听 countryData 数组里面的数据 - 即国家数据
      this.countryData=country
      return {
        // edit 编辑英文客户 英文客户详情
        viewType:"edit",
        editForm:{
          CompanyId:0,
          CompanyName:"",
          CountryCode:"",
          Country:"",
          SellerId:""
        },
        // 联系人列表搜索参数
        searchParams:{
          CompanyId:0,
          CurrentIndex:1,
          PageSize:8,
          SortType:"",
          Keywords:""
        },
        total:0,
        // 联系人列表
        contactsList:[],
        // 销售列表
        sellerList:[],
        // ------------------累计点击量弹窗
        showClickTimesDia:false,
        clickTimesDetailItem:{
          contactsName:"",
          contactsId:""
        },
        // --------------------添加/编辑弹窗
        dialogTitle:"添加联系人",
        showAddDia:false,
        contactsSubmitForm:{},
        imgView:'',
        showViewer:false,

        varietyOpts:[],
      }
    },
    created() {
      if(this.$route.path == '/addCustomEn'){
        this.getSellerList()
        return
      } 
      if(!this.$route.query.companyId){
        // 无客户信息
        this.$router.replace('/customListEn')
        return 
      }
      // 判断页面的类型
      this.viewType=this.$route.path == '/detailCustomEn'?'detail':'edit'
      this.editForm.CompanyId=this.searchParams.CompanyId=parseInt(this.$route.query.companyId)
      this.getSellerList()
      this.customDetail()
      this.getList()
    },
    methods: {
      // 获取销售列表
      getSellerList(){
        customInterence.saleslist({SellerType:0}).then(res=>{
          if(res.Ret == 200){
            this.sellerList = res.Data.List || []
          }
        })
      },
      // 客户详情
      customDetail(){
        customInterence.customDetailEn({CompanyId:this.editForm.CompanyId}).then(res=>{
          if(res.Ret == 200){
            this.editForm.CompanyName=res.Data.CompanyName
            this.editForm.Country=res.Data.Country
            this.editForm.CountryCode=res.Data.CountryCode
            this.editForm.SellerId=res.Data.SellerId
            this.varietyOpts=res.Data.EnPermissions
          }else{
            this.$router.replace('/customListEn')
          }
        })
      },
      getList(type=''){
        if(type=="search"){
          this.searchParams.CurrentIndex=1
        }
        customInterence.getContactsListEn(this.searchParams).then(res=>{
          if(res.Ret == 200){
            this.contactsList = res.Data.List || []
            this.total = res.Data.Paging.Totals
          }
        })
      },
      // 重置列表和搜索项
      refreshList(){
        this.searchParams.SortType=""
        this.searchParams.Keywords=""
        this.searchParams.CurrentIndex=1
        this.getList()
      },
      pageChange(page_no){
        this.searchParams.CurrentIndex=page_no
        this.getList()
      },
      updateList(type){
        type=='refresh'?this.getList():this.refreshList()
      },
      // 修改提交
      editSubmit(){
        this.$refs.editForm.validate(valid=>{
          if(valid){
            customInterence.addCustomEn({
                ...this.editForm,
                EnPermissions:this.$refs.varietyIns.checkedItems||[],
                Nation:this.editForm.Country
            }).then(res=>{
              if(res.Ret == 200){
                let messageEle=this.$message.success(this.$route.path == '/addCustomEn'?'添加客户成功':'编辑客户成功')
                setTimeout(()=>{
                  messageEle.close()
                  this.editCancel()
                },1000)
              }
            })
          }
        })
      },
      // 取消修改
      editCancel(){
        //this.$router.back()
        this.$router.push({path:'/customListEn'})
      },
      
      // -----------------------英文客户详情独有方法
      // 去编辑用户
      toEdit(){
        this.$router.replace({path:'/editCustomEn',query:{companyId:this.editForm.CompanyId}})
        this.viewType="edit"
      },
      // 删除客户
      customDelete(){
        this.$confirm(`是否确认删除客户<span style="color:#409EFF">${this.editForm.CompanyName}</span>，并删除该客户下所有的联系人？`,"操作提示",
        {
          type:"warning",
          dangerouslyUseHTMLString:true,
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }).then(res=>{
          customInterence.delCustomEn({CompanyId:this.editForm.CompanyId}).then(res=>{
            if(res.Ret == 200){
              let hint=this.$message.success("删除客户成功")
              setTimeout(()=>{
                hint.close()
                //this.$router.back()
                this.$router.push({path:'/customListEn'})
              },1000)
            }
          })
        }).catch(() => {});
      },
      // 累计点击量排序
      clickTimesSortChange({order}){
        this.searchParams.SortType=order=="ascending"?'2':order=="descending"?'1':''
        this.getList()
      },
      //累计点击量详情
      clickTimesDetail(row){
        this.clickTimesDetailItem.contactsName = row.Name
        this.clickTimesDetailItem.contactsId = row.Id
        this.showClickTimesDia=true
      },
      // -------------------------------------添加/编辑联系人
      //添加联系人
      addContacts(){
        this.contactsSubmitForm={}
        this.dialogTitle="添加联系人"
        this.showAddDia=true
      },
      // 编辑联系人
      editContacts(row){
        this.contactsSubmitForm=row
        this.dialogTitle="编辑联系人"
        this.showAddDia=true
      },
      // -----------------------------上传批量导入模板
      templateUpload(file){
        let formData = new FormData()
        formData.append('File',file.file)
        formData.append('CompanyId',this.editForm.CompanyId)
        customInterence.importContactsEn(formData).then(res=>{
          if(res.Ret == 200){
            this.$message.success('批量导入成功')
            this.refreshList()
          }
        })
      },

      // 删除客户
      delContacts(row){
        this.$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){
              this.$message.success("删除联系人成功")
              this.getList()
            }
          })

        }).catch(() => {});
      },
      //启用禁用联系人
      changeStatus(row){
        customInterence.editEnabledEn({
          EmailId:row.Id,
          Enabled:row.Enabled===1?0:1
        }).then(res=>{
          if(res.Ret!==200) return 
          this.$message.success('操作成功')
          this.getList()
        })
      },
      /* 预览名片 */
      reviewCard(card) {
        console.log('aaa');
        this.showViewer = true;
        this.imgView = card;
      },
      /* 关闭预览 */
      closeViewer() {
        this.imgView = '';
        this.showViewer = false;
      },
    },
  }
</script>

<style lang="scss" scoped>
#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;
  }
}
</style>
<style lang="scss">
#edit-custom-container{
  .el-form-item{
    margin-right: 100px;
  }
  .el-form-item:nth-child(2){
    margin-right: 50px;
  }
  .el-form-item__label{
    color: black;
  }
  .img_item {
    position: relative;
    width: 280px;
    height: 180px;
    border-radius: 4px;
  }
  .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>