<template>
  <div  @click = 'handleALL'>
    <div class="miantitle">
      <span>客户管理</span>
      <span> / 客户列表</span>
    </div>
    <div class="app-container">
      <el-card class="box-card noborder">
        <div class="tables">
          <div class="empty" v-if="tableData.total==0">
            <img src="@/assets/images/project/empty.png">
            <div class="p1">抱歉，没找到相关数据</div>
            <div class="p2">建议调整关键词或筛选条件，重新搜索</div>
            <div class="btn btn_primary h36 w88" @click="opennew">添加客户</div>
            <div class="btn btn_primary btn_shallow h36 w88" @click="pldrs">批量导入</div>
          </div>
          <div class="table_search">
            <div class="searchInput">
              <el-input type="text" clearable v-model="searchParam.companyName" @change="clearname" placeholder="输入企业名称查询"></el-input>
              <div class="btn" @click="handleCurrentChange(1)">搜索</div>
            </div>
            <div class="dc">
              <div class="total">共{{tableData.total}}条</div>
              <div class="btn-export" @click="pldrs"><img src="@/assets/images/project/import.png">批量导入</div>
              <div class="btn btn_primary h32 p10" @click="opennew"><div class="img img1"></div>添加客户</div>
            </div>
          </div>
          <el-table v-if="tableData.total > 0"
            :data="tableData.rows"
            stripe border
            style="width: 100%">
            <el-table-column
              prop="index"
              label="序号"
              fixed="left"
              width="47">
              <template slot-scope='scope'>
                <span>{{ (searchParam.pageNum - 1) * searchParam.pageSize + scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="date"
              label="企业名称"
              fixed="left"
              width="441">
            <template slot-scope="scope">
              <div class="ps1">
                <div class="wordprimary ps2" @click="toDetail(scope.row,'')">{{scope.row.companyName}}</div>
                <div class="ps3">
                  <div  @click="toDetail(scope.row,'gjjl')">写跟进<img src="@/assets/images/project/edit_1.png"></div>
                  <div  @click="toDetail(scope.row,'business')">编辑信息<img src="@/assets/images/project/edit_2.png"></div>
                </div>
              </div>
            </template>

            </el-table-column>
            <el-table-column
              prop="cooperationProject"
              label="合作项目"
              width="76">
              <template slot-scope="scope">
                {{scope.row.cooperationProject || '--'}}
              </template>
            </el-table-column>
            <el-table-column
              prop="followProject"
              label="跟进项目"
              width="76">
              <template slot-scope="scope">
                {{scope.row.followProject || '--'}}
              </template>
            </el-table-column>
            <el-table-column
              prop="reserveProject"
              label="储备项目"
              width="76">
              <template slot-scope="scope">
                {{scope.row.reserveProject || '--'}}
              </template>
            </el-table-column>
            <el-table-column
              prop="legalPerson"
              label="法定代表人"
              width="110">
              <template slot-scope="scope">
                {{scope.row.legalPerson || '--'}}
              </template>
            </el-table-column>
            <el-table-column
              prop="registerAddress"
              label="注册地区"
              width="160">
              <template slot-scope="scope">
                {{scope.row.registerAddress || '--'}}
              </template>
            </el-table-column>
            <el-table-column
              prop="registerCapitalStr"
              label="注册资本金（万元）"
              width="140">
              <template slot-scope="scope">
                {{scope.row.registerCapital || '--'}}
              </template>
            </el-table-column>
            <el-table-column
              prop="creditLevel"
              label="企业主体评级" width="100">
              <template slot-scope="scope">
                {{scope.row.creditLevel || '--'}}
              </template>
            </el-table-column>
            <el-table-column
              prop="isOn"
              label="上市公司" width="76">
              <template slot-scope="scope">
                {{scope.row.isOn == 1?"是":"否"}}
              </template>
            </el-table-column>
            <el-table-column
              prop="isMajor"
              label="局级大客户" width="88">
              <template slot-scope="scope">
                <span v-if="scope.row.isMajor != null">
                {{scope.row.isMajor == 1?"是":"否"}}
                </span>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="customerLevel"
              label="客户等级" width="76">
              <template slot-scope="scope">
                {{scope.row.customerLevel || '--'}}
              </template>
            </el-table-column>
            <el-table-column
              prop="companyNature"
              label="客户性质" width="76">
              <template slot-scope="scope">
                {{scope.row.companyNature || '--'}}
              </template>
            </el-table-column>
            <el-table-column
              prop="companyLevel"
              label="客户级别" width="76">
              <template slot-scope="scope">
                {{scope.row.companyLevel || '--'}}
              </template>
            </el-table-column>
            <el-table-column
              prop="address"
              label="企业母公司" width="268">
              <template slot-scope="scope">
                <div class="">{{scope.row.superCompany || '--'}}</div>
              </template>
            </el-table-column>
            <el-table-column :key="keys"
              prop="mainBusiness"
              label="主营业务" width="400">
              <template slot-scope="scope">
                <div v-if="scope.row.mainBusiness == null || scope.row.mainBusiness == ''">--</div>
                <div class="box"  v-else-if="scope.row.sq1==true">{{scope.row.mainBusiness1}}...<span @click="sq1(scope.row,false)">更多</span></div>
                <div class="box"  v-else>{{scope.row.mainBusiness}}<span @click="sq1(scope.row,true)">收起</span></div>
              </template>
            </el-table-column>
            <el-table-column
              prop="companyAttribute" :key="keys+2"
              label="发包属性" width="400">
              <template slot-scope="scope">
                <div v-if="scope.row.companyAttribute == null || scope.row.companyAttribute == ''">--</div>
                <div class="box"  v-else-if="scope.row.sq2==true">{{scope.row.companyAttribute1}}...<span @click="sq2(scope.row,false)">更多</span></div>
                <div class="box"  v-else>{{scope.row.companyAttribute}}<span @click="sq2(scope.row,true)">收起</span></div>
              </template>
            </el-table-column>
            <el-table-column
              prop="followUser"
              label="跟进人" width="110">
              <template slot-scope="scope">
                {{scope.row.followUser || '--'}}
              </template>
            </el-table-column>
          </el-table>
          <div class="bottems" v-if="tableData.total>searchParam.pageSize">
            <el-pagination
              background
              :page-size="searchParam.pageSize"
              :current-page="searchParam.pageNum"
              @current-change="handleCurrentChange"
              layout="prev, pager, next"
              :total="tableData.total">
            </el-pagination>
          </div>
        </div>
        <el-dialog
          class="popups"
          :visible.sync="dialogVisible"
          width="534px"
          @close="resetForm('ruleForm')"
        >
          <div class="poptitle">
            <img src="@/assets/images/economies/icon.png">
            <span>添加客户</span>
          </div>
          <el-form class="popform j" :model="queryParam" :rules="rules" ref="ruleForm" label-width="130px">
            <el-form-item label="企业名称：" class="row"  prop="companyName">
              <el-input type="text" placeholder="请输入" v-model="queryParam.companyName" @input="getCompany"></el-input>
              <div class="resultlist" v-if="showlist" id="box">
                <div v-for="(item,index) in companData" @click="selCompany(item)"><span  v-html="item.name"></span></div>
              </div>
            </el-form-item>
            <el-form-item label="客户等级：" class="row">
              <el-select  placeholder="请选择" v-model="queryParam.customerLevel">
                <el-option v-for="(item,index) in customerLevel" :key="index" :label="item.dictLabel" :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="法定代表人：" class="row">
              <el-input type="text" placeholder="请输入" v-model="queryParam.legalPerson"></el-input>
            </el-form-item>
            <el-form-item label="注册资本（万）：" class="row">
              <el-input type="text" placeholder="请输入" v-model="queryParam.registerCapital" @input='number'></el-input>
            </el-form-item>
            <el-form-item label="企业注册地：" class="row">
              <el-cascader :props="props" @change="getAddr($event)" ref="address" v-model="queryParam.address" :options="addressList" clearable></el-cascader>
            </el-form-item>
            <el-form-item label="统一社会信用代码：" class="row">
              <el-input type="text" placeholder="请输入" v-model="queryParam.creditCode"></el-input>
            </el-form-item>
            <div class="popbot">
              <div class="wordprimary" @click="toct">前往城投平台寻找客户线索></div>
              <div class="btn btn_cancel h32" @click="resetForm('ruleForm')">返回</div>
              <div class="btn btn_primary h32" @click="submitForm('ruleForm')">添加</div>
            </div>
          </el-form>
        </el-dialog>
      </el-card>
    </div>
    <batchimport v-if="pldr" :importtype="types" @cancels="cancelimport" @getdatas="handleCurrentChange(1)"></batchimport>
  </div>
</template>

<script>
  import { getToken } from "@/utils/auth";
  import "@/assets/styles/project.scss"
  import {getCustomerList,importData,addCustomer} from '@/api/custom/custom'
  import {getEnterprise,getDictType,} from '@/api/main'
  import prvinceTree from '@/assets/json/provinceTree'
  import batchimport from '../../project/projectList/component/batchImport'
  import axios from 'axios'
  import {encodeStr} from "@/assets/js/common"
export default {
  name: 'CustomList',
  components:{batchimport},
  data() {
    return{
      encodeStr,
      pldr: false,
      types:'custom',
      searchParam:{
        companyName:'',
        pageNum:1,
        pageSize:20
      },
      props:{ checkStrictly: true, expandTrigger: 'hover' },
      dialogVisible:false,
      textarea:"",
      nowedit:-1,//当前正在编辑的文本
      tipslit:[],//项目标签
      tipsvalue:"",//标签填写内容
      tableData: [],//列表
      companData:[],//联想企业列表

      customerLevel:[],//客户等级
      addressList:[],//地区
      //添加客户
      queryParam:{
        companyId:'',//jsk企业id
        companyName:'',//客户名称（企业名称
        customerLevel:'',//客户等级
        legalPerson:'',//法定代表人
        registerCapital:'',//注册资本
        registerAddress:'',//企业注册地址
        creditCode:'',//社会统一信用代码
        address:'',//选择的地址
        provinceId:'',
        cityId:'',
        districtId:'',
      },
      rules:{
        companyName:[{ required: true, message: '请输入非空格字符！', trigger: 'blur' },]
      },
      //批量导入
      action: process.env.VUE_APP_BASE_API + "/customer/importData",
      fileList: [],
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // isNew:true,
      showlist:false,
      keys:1,
    }
  },
  created() {
    this.getCustomerList()
    this.getDictType()
    this.prvinceTree()
  },
  methods:{
    sq1(item,sq){
      this.$nextTick(()=>{
        item.sq1 = sq
        this.keys++ ;
      })
    },
    sq2(item,sq){
      this.$nextTick(()=>{
        item.sq2 = sq
        this.keys++ ;
      })
    },
    handleALL(event){
      var one = document.getElementById("box");
      if(one){
        if(!one.contains(event.target)){
          this.showlist = false
        }
      }
    },
    toct(){
      this.$router.push({path:'/macro/urban'})
    },
    getDictType(){
      //获取客户等级
      getDictType('customer_level_type').then(result=>{
        this.customerLevel = result.code == 200 ? result.data:[]
      })
    },
    pldrs(){
      this.pldr = true
    },
    cancelimport(){
      this.pldr = false
    },
    //获取客户列表
    getCustomerList(){
      getCustomerList(this.searchParam).then(result=>{
        this.tableData = result
        this.tableData.rows.forEach(item=>{
          item.registerCapital = item.registerCapital == null?null: item.registerCapital.replace(/^\D*(\d*(?:\.\d{0,6})?).*$/g, '$1')
          if(item.mainBusiness != "" && item.mainBusiness != null && item.mainBusiness.length>84){
            item.mainBusiness1 = item.mainBusiness.substring(0,81)
            item.sq1 = true
          }else{
            item.sq1 = false
          }
          if(item.companyAttribute != "" && item.companyAttribute != null && item.companyAttribute.length>84){
            item.companyAttribute1 = item.companyAttribute.substring(0,81)
            item.sq2 = true
          }else{
            item.sq2 = false
          }
      })
      })
    },
    //跳转到客户详情
    toDetail(row,type){
      let customerId = row.customerId
      let companyId = row.companyId
      let path = type
      if(type == "" && companyId == null){
        path = 'business'
      }
      this.$router.push({path:'/enterprise/'+encodeStr(companyId),query:{customerId:customerId,path:path}})
    },
    clearname(value){
      if(value == ""){
        this.handleCurrentChange(1)
      }
    },
    //翻页
    handleCurrentChange(val) {
      this.pldr=false
      // this.isNew = false
      this.searchParam.pageNum=val
      this.getCustomerList()
    },
    //打开新建窗口
    opennew(){
      this.dialogVisible = true
    },
    getAddr(obj){
      if(obj.length == 0){
        this.queryParam.provinceId = ''
        this.queryParam.cityId = ''
        this.queryParam.districtId = ''
        return false
      }
      let labelString = this.$refs.address.getCheckedNodes()[0].pathLabels.join("-");
      this.queryParam.registerAddress = labelString
      this.queryParam.provinceId = obj[0]
      this.queryParam.cityId = obj.length>=1 ? obj[1]:''
      this.queryParam.districtId = obj.length>=2 ? obj[2]:''
    },
    //获取建设库客户
    getCompany(value){
      this.queryParam.companyId = null
      if (value.length>=2){
        let param = {
          keyword:value,
          page:{
            limit:20,
            page:1
          }
        }
        getEnterprise(JSON.stringify(param)).then(result=>{
          if(result.code != 200)
            return
          this.showlist = true
          this.companData = result.data.list
        })
      }
    },
    selCompany(item){
      this.queryParam.companyId = item.jskEid
      this.queryParam.companyName = item.name.replace(/<[^>]+>/g, '')
      this.queryParam.legalPerson = item.legalPerson
      let registeredCapitalStr = ""
      if(item.registeredCapitalStr == "0" || item.registeredCapitalStr == 0){
        registeredCapitalStr = ''
      }else{
        registeredCapitalStr = item.registeredCapitalStr
      }
      this.queryParam.registerCapital = registeredCapitalStr
      this.queryParam.creditCode = item.creditCode
      this.queryParam.provinceId = item.provinceId
      this.queryParam.cityId = item.cityId
      this.queryParam.districtId = item.cityId

      let list = []
      if(item.provinceId != null && item.provinceId != "")
        list.push(item.provinceId)
      if(item.cityId != null && item.cityId != "")
        list.push(item.cityId)
      if(item.districtId != null && item.districtId != "")
        list.push(item.districtId)
      this.$nextTick(()=>{
        this.queryParam.address = list
        let _this = this
        setTimeout(function() {
          if(_this.$refs.address){
            _this.queryParam.registerAddress = _this.$refs.address.getCheckedNodes()[0].pathLabels.join("-")
          }
        },1000)
      })
      this.showlist = false
    },
    //添加客户
    submitForm(formName) {
      // if(this.queryParam.companyId=="" || this.queryParam.companyId == null){
      //   this.$message.error({message:'请选择企业！',showClose:true})
      //
      //   return;
      // }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          addCustomer(this.queryParam).then(result=>{
            if(result.code == 200){
              this.$message.success('添加成功！')
              this.dialogVisible = false
              this.handleCurrentChange(1)
              this.resetForm('ruleForm')
            }else{
              this.$message.error(result.msg)
            }
          })
        } else {
        }
      });
    },
    resetForm(formName) {
     this.queryParam = {
        companyId:'',//jsk企业id
        companyName:'',//客户名称（企业名称
        customerLevel:'',//客户等级
        legalPerson:'',//法定代表人
        registerCapital:'',//注册资本
        registerAddress:'',//企业注册地址
        creditCode:'',//社会统一信用代码
        address:'',//选择的地址
        provinceId:'',
        cityId:'',
        districtId:'',
      },
      this.dialogVisible = false
      this.showlist = false
    },

    //地区
    async prvinceTree() {
      // await axios.post("https://files.jiansheku.com/file/json/common/provinceTree.json", {}, {
      //   headers: {
      //     'Content-Type': 'application/json'
      //   }
      // }).then(res => {
      //   if (res.data.code == 200) {
      //     console.log(res.data.data)
      //   }
      // })
      // console.log(prvinceTree)
      this.addressList = prvinceTree;
      this.getadd(this.addressList)
    },
    //处理注册地数据
    getadd(row) {
      this.addrcallback(row,this.getadd)
    },
    addrcallback(row,callback){
      if(row){
        row.forEach(item => {
          item.value = item.id
            callback &&  callback(item.children)
        })
      }
    },
    //输入数字
    number(value){
      if(value == '')
        this.queryParam.registerCapital = value
      else
         this.queryParam.registerCapital = value.replace(/^\D*(\d*(?:\.\d{0,6})?).*$/g, '$1')//输入6位小数
    }
  }
}
</script>

<style lang="scss" scoped>
  .app-container{
    height: calc(100vh - 134px)
  }
.box-card{
  padding-top: 16px;
  width: 100%;
  height: 100%;
}
.box{
  position: relative;
  >span{
    position: absolute;
    right: 10px;
    bottom: 0;
    color: #0081FF;
    cursor: pointer;
    &:hover{
      color: #006AD1;
    }
  }
}
  .dc{
    font-size: 12px;
    color: #3D3D3D;
    font-weight: 400;
    position: relative;
    &::after{
      content: ' ';
      width: 2px;
      height: 2px;
      background: rgba(35,35,35,0.4);
      border-radius: 50%;
      position: absolute;
      top: 16px;
      left: 14px;
    }
    >div{
      display: inline-block;
      margin-left: 20px;
    }
  }
  .img.img1{
    margin-right: 2px;
    background: url('../../../../src/assets/images/project/add_2.png')no-repeat center center;
    background-size: 100%;
  }
  .w88{
    width: 88px;
  }
  .tables{
    position: relative;
    height: calc(100vh - 134px);
    overflow: auto;
    .empty{
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
      .btn{
        margin-right: 8px;
        margin-top: 16px;
      }
    }
  }
  .ps1{
    display: flex;
    justify-content: space-between;
    .ps2{
      width: 270px;
    }
    .ps3{
      width: 155px;
      display: flex;
      justify-content: right;
      >div{
        margin-left: 12px;
        &:hover{
          color: #0CBC6D;
          cursor: pointer;
        }
        >img{
          float: right;
          margin: 3px 0 0 4px;
          width: 14px;
        }
      }
    }
  }
  .popbot{
    .wordprimary{
      display: inline;
      padding-right: 26px;
    }
  }
  .app-container{
    height: auto;
  }
  .searchInput{
    .el-input{
      width: 260px;
    }
  }
</style>
