<template>
  <div>
    <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 && isNew == true">
            <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" v-model="searchParam.companyName" placeholder="输入企业名称查询"></el-input>
              <div class="btn" @click="handleCurrentChange(1)">搜索</div>
            </div>
            <div class="dc">
              <div class="total">共126条</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="isNew != true || tableData.total > 0"
            :data="tableData.rows"
            stripe border
            style="width: 100%"
            :default-sort = "{prop: 'date', order: 'descending'}"
          >
            <el-table-column
              prop="index"
              label="序号"
              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="企业名称"
              width="441">
            <template slot-scope="scope">
              <div class="ps1">
                <div class="wordprimary ps2" @click="toDetail(scope.row.companyId,'')">{{scope.row.companyName}}</div>
                <div class="ps3">
                  <div  @click="toDetail(scope.row.companyId,1)">写跟进<img src="@/assets/images/project/edit_1.png"></div>
                  <div  @click="toDetail(scope.row.companyId,2)">编辑信息<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.registerCapitalStr || '--'}}
              </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">
                {{scope.row.isMajor == 1?"是":"否"}}
              </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="wordprimary">{{scope.row.superCompany || '--'}}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="mainBusiness"
              label="主营业务" width="120">
              <template slot-scope="scope">
                {{scope.row.mainBusiness || '--'}}
              </template>
            </el-table-column>
            <el-table-column
              prop="companyAttribute"
              label="发包属性" width="120">
              <template slot-scope="scope">
                {{scope.row.companyAttribute || '--'}}
              </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>0">
            <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">
                <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">前往城投平台寻找客户线索></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>
    <div class="uploadwin" v-if="pldr">
      <div class="upload" v-if="addfile==false">
        <div class="up_title">批量导入客户</div>
        <div class="up_box">
          <el-upload :class="{'none':isUpload == true}"
                     class="upload-demo"
                     :action="action"
                     :multiple="false"
                     accept=".xls,.xlsx"
                     drag
                     ref="upload"
                     :auto-upload="false"
                     :file-list="fileList"
                     :on-change="handleFileListChange"
                     :headers="headers"
                     :on-success="onSuccess">
            <img class="up_img" src="@/assets/images/project/upload.png">
            <div class="up_text">点击选择或将文件(xls，xlsx)拖拽至此上传成员名录</div>
            <div class="up_tip">导入的文件内容必须依照下载模板的要求填写</div>
            <div class="up_tip">上传文件最大为2M，仅支持Excel表格文件（xls,xlsx)</div>
            <div class="up_tip">导入已存在的客户将自动跳过</div>
          </el-upload>
          <div class="up_success" v-if="isUpload == true">
            <img src="@/assets/images/project/success.png">上传成功
          </div>
          <div class="btn_download" v-if="isUpload == false" @click="downloadClick"><div class="img"></div>点击下载</div>
        </div>
        <div class="btns">
          <div class="btn btn_primary btn_disabled h34" v-if="isUpload==false">确定导入</div>
          <div class="btn btn_primary h34" @click="importConfirmClick" v-else>确定导入</div>
          <div class="btn btn_default h34">取消</div>
        </div>
      </div>
      <div class="success" v-if="addfile==true">
        <div v-if="addsuccess==false">
          <img class="img" src="@/assets/images/project/clock.png">
          <div class="p1">查询客户中...</div>
          <div class="p2">请耐心等待，过程大概30秒</div>
        </div>
        <div v-if="addsuccess == true">
          <div class="p3">
            <img src="@/assets/images/project/success.png">查询成功
          </div>
          <div class="p2">成功导入客户信息</div>
          <div class="btns">
            <div class="btn btn_primary h32" @click="handleCurrentChange(1)">查看</div>
          </div>
        </div>
      </div>
    </div>
  </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 axios from 'axios'
export default {
  name: 'CustomList',
  data() {
    return{
      pldr: false,
      searchParam:{
        companyName:'',
        pageNum:1,
        pageSize:20
      },
      props:{ checkStrictly: true, expandTrigger: 'hover' },
      dialogVisible:false,
      textarea:"",
      nowedit:-1,//当前正在编辑的文本
      tipslit:[],//项目标签
      tipsvalue:"",//标签填写内容
      tableData: [],//列表
      isUpload:false,//有上传的文件
      addfile:false,//已上传文件
      addsuccess:false,//已成功加入数据
      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,
    }
  },
  created() {
    this.getCustomerList()
    this.getDictType()
    this.prvinceTree()
  },
  methods:{
    getDictType(){
      //获取客户等级
      getDictType('customer_level_type').then(result=>{
        this.customerLevel = result.code == 200 ? result.data:[]
      })
    },
    pldrs(){
      this.pldr = true
      this.addfile = false
      this.isUpload = false
      this.addsuccess = false
    },
    //获取客户列表
    getCustomerList(){
      getCustomerList(this.searchParam).then(result=>{
        this.tableData = result
      })
    },
    //跳转到客户详情
    toDetail(id,type){
      if(type == 1){//跟进

      }else if(type == 2){//编辑信息

      }
    },
    //翻页
    handleCurrentChange(val) {
      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){
      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){
      console.log(item)
      this.queryParam.companyId = item.jskEid
      this.queryParam.companyName = item.name.replace(/<[^>]+>/g, '')
      this.queryParam.legalPerson = item.legalPerson
      this.queryParam.registerCapital = item.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.queryParam.address = list
      this.queryParam.registerAddress = item.registerAddress
      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
    },
    // 批量导入
    importConfirmClick() {
      if (this.fileList.length > 0) {
        this.$refs["upload"].submit();
        this.getCustomerList();
        this.addfile = true
      } else {
        this.$message("请先选择文件");
      }
    },
    downloadClick() {
      let a = document.createElement("a");
      a.setAttribute("href", "/file/Template.xlsx");
      a.setAttribute("download", "批量导入模版.xlsx");
      document.body.appendChild(a);
      a.click();
    },
    handleFileListChange(file, fileList) {
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]];
        this.isUpload = true
      }
    },
    onSuccess(res, file, fileList) {
      if(res.code == 200 )
        this.addsuccess = true
      else
        this.$message.error({message:res.msg,showClose:true})
    },

    //地区
    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){
      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%;
}

  .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;
  }
  .w88{
    width: 88px;
  }
  .tables{
    position: relative;
    height: calc(100vh - 134px);
    .empty{
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
      .btn{
        margin-right: 8px;
        margin-top: 12px;
      }
    }
  }
  .ps1{
    display: flex;
    justify-content: space-between;
    .ps2{
      width: 270px;
    }
    .ps3{
      width: 150px;
      display: flex;
      justify-content: right;
      >div{
        margin-left: 12px;
        &:hover{
          color: #0CBC6D;
          cursor: pointer;
        }
        >img{
          float: right;
          margin: 3px 0 0 4px
        }
      }
    }
  }
  .popbot{
    .wordprimary{
      display: inline;
      padding-right: 26px;
    }
  }
  .none{display: none}
</style>
