<template>
  <div class="app-container">
      <!--用户数据-->
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="客户编码" prop="customerCode">
          <el-input
            v-model="queryParams.customerCode"
            placeholder="请输入客户编码"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input
            v-model="queryParams.customerName"
            placeholder="请输入客户名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input
            v-model="queryParams.mobile"
            placeholder="请输入手机"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="客户状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择客户状态" clearable size="small">
            <el-option
                  v-for="item in statusOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
          </el-select>
        </el-form-item>
        <el-form-item   label="客户类型" prop="customerLevel">
          <el-select filterable v-model="queryParams.customerLevel" placeholder="请选择客户类型" clearable size="small">
            <el-option
                  v-for="item in customerLevelOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
          </el-select>
        </el-form-item>
        <el-form-item label="客户标签" prop="tags">
            <el-select multiple  filterable v-model="tagIds" placeholder="请选择客户标签" clearable size="small">
              <el-option
                    v-for="item in tagsOptions"
                    :key="item.dictLabel"
                    :label="item.dictLabel"
                    :value="item.dictLabel"
                  />
            </el-select>
          </el-form-item>

         <el-form-item label="从客户" prop="isDuplicate">
            <el-select   filterable v-model="queryParams.isDuplicate" placeholder="请选择从客户" clearable size="small">
              <el-option
                    v-for="item in isDuplicateOptions"
                    :key="item.dictLabel"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
            </el-select>
          </el-form-item>


        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
              style="width:205.4px"
              clearable size="small"
              v-model="dateRange"
              type="daterange"
              value-format="yyyy-MM-dd"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>

        </el-form-item>

      <el-form-item label="客户来源" prop="source">
            <el-select v-model="queryParams.source" placeholder="请选择客户来源" clearable size="small">
              <el-option
                    v-for="item in sourceOptions"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
            </el-select>
       </el-form-item>

        <el-form-item>
          <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-plus"
            @click="handleAdd"
            v-hasPermi="['crm:customer:add']"
          >新增客户</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            icon="el-icon-edit"
            size="mini"
            :disabled="multiple"
            @click="handleAssign"
            v-hasPermi="['crm:customer:assignToUser']"
          >客户分配</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-button
              type="success"
              size="mini"
              @click="handleAssignList"
              v-hasPermi="['crm:customerAssign:list']"
            >分配历史记录</el-button>
          </el-col>
        <el-col :span="1.5">
            <el-button
              type="success"
              size="mini"
              :disabled="multiple"
              @click="handleEditScource"
              v-hasPermi="['crm:customer:editScource']"
            >修改客户来源</el-button>
          </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            v-hasPermi="['crm:customer:importLine']"
          >导入线索客户</el-button>
        </el-col>

        <el-col :span="1.5">
          <el-button
            type="warning"
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['crm:customer:export']"
          >导出</el-button>
        </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table  height="500" border v-loading="loading" :data="customerList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="客户编码" align="center" prop="customerCode" />
        <el-table-column  label="客户名称"   align="center" prop="customerName" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-link @click="handleShow(scope.row)" :underline="false" type="primary" >{{  scope.row.isDuplicate==1?getCustomerName(scope.row.customerName)+"[从]":getCustomerName(scope.row.customerName)   }}</el-link>
          </template>
        </el-table-column>
        <el-table-column  label="手机" width="120px"  align="center" prop="mobile"   >
          <template slot-scope="scope">
            {{scope.row.mobile}}
          </template>
        </el-table-column>
        <el-table-column  label="客户来源" align="center" prop="source">
          <template slot-scope="scope">
              <el-tag prop="status" v-for="(item, index) in sourceOptions"    v-if="scope.row.source==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column  label="跟进阶段"  align="center" prop="visitStatus" >
          <template slot-scope="scope">
              <el-tag prop="visitStatus" v-for="(item, index) in visitStatusOptions"    v-if="scope.row.visitStatus==item.dictValue">{{item.dictLabel}}</el-tag>
            </template>
        </el-table-column>
        <el-table-column  label="客户类型"  align="center" prop="customerType" >
          <template slot-scope="scope">
              <el-tag v-for="item in customerLevelOptions"    v-if="scope.row.customerLevel === item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="标签" align="center" prop="tags" />
        <el-table-column label="备注" align="center" prop="remark" width="120"  />
        <el-table-column label="进线客户详情" align="center" :show-overflow-tooltip="true" prop="registerDesc" />
        <el-table-column label="领取时间" align="center" prop="startTime" />
        <el-table-column label="进线客户提交日期" align="center" prop="registerSubmitTime" width="130" />
         <el-table-column  label="认领人"  align="center" prop="companyUserNickName" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="100">
        </el-table-column>

        <el-table-column label="最后一次跟进时间" align="center" prop="receiveTime" width="100">
        </el-table-column>
        <el-table-column label="入公海时间" align="center" prop="poolTime" width="100">
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"/>


    <el-dialog :title="assign.title" :visible.sync="assign.open" width="800px" @close="closeAssignPop" append-to-body>
      <assign-user  ref="assignUser" @close="closeAssign"   />
    </el-dialog>
    <el-drawer
      size="75%"
      :title="show.title" :visible.sync="show.open">
        <customer-details  ref="customerDetails" />
    </el-drawer>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div class="el-upload__tip" slot="tip">
            <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
          </div>
          <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
    </el-dialog>

    <el-dialog :title="source.title" :visible.sync="source.open" width="1000px" append-to-body>
       <edit-source ref="editSource" @close="closeSource()"></edit-source>
    </el-dialog>
    <el-dialog :title="customer.title" :visible.sync="customer.open" width="1000px" append-to-body>
       <add-or-edit-customer ref="customer" @close="closeCustomer()"></add-or-edit-customer>
    </el-dialog>
    <el-dialog title="导入结果" :close-on-press-escape="false" :close-on-click-modal="false" :visible.sync="importMsgOpen" width="500px" append-to-body>
       <div class="import-msg" v-html="importMsg">
       </div>
    </el-dialog>
    <el-dialog :title="assignList.title" :visible.sync="assignList.open" width="1000px" append-to-body>
      <customer-assign-list  ref="assignList" @close="closeAssignList"></customer-assign-list>
    </el-dialog>

    <el-dialog :title="xy.title" :visible.sync="xy.open" width="1000px" @close="xy.open=false" append-to-body>
       <div class="xy-content">
        <div class="xy-img">
          <img src="@/assets/image/xy_01.jpg"/>
          <img src="@/assets/image/xy_02.jpg"/>
        </div>
        <div  class="footer">
              <el-button  @click="submitExport" :disabled="exportDisable">{{exportBtnText}}</el-button>
          </div>
       </div>
    </el-dialog>
  </div>
</template>

<script>
import store from "@/store";
import { importLineTemplate,getLineCustomerList ,assignToUser,getCustomerDetails,exportCustomer } from "@/api/crm/customer";
import customerDetails from '../components/customerDetails.vue';
import { treeselect } from "@/api/company/companyDept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";
import editSource from '../components/editSource.vue';
import addOrEditCustomer from '../components/addOrEditCustomer.vue';
import customerAssignList from '../components/customerAssignList.vue';
import assignUser from '../components/assignUser.vue';
import {customerLevelOptions} from "@/api/crm/customerLevel";
export default {
  name: "Customer",
  components: { assignUser,customerAssignList,addOrEditCustomer,customerDetails,Treeselect,editSource },
  data() {
    return {
      companyUser:store.getters.user,
      exportLoading:null,
      exportInteval:null,
      exportTime:60,
      exportBtnText:"导出",
      exportDisable:true,
      xy:{
        title:"免责协议",
        open:false,
      },
      visitStatusOptions:[],
      isDuplicateOptions:[ {"dictLabel":"不限","dictValue":""},{"dictLabel":"从客户","dictValue":1},{"dictLabel":"非从客户","dictValue":2}],
      tagIds:[],
      tagsOptions:[],
      assignList:{
        title:"分配历史记录",
        open:false,
      },
      importMsgOpen:false,
      importMsg:"",
      customer:{
          open:false,
          title:"新增客户"
      },
      source:{
          open:false,
          title:"修改客户来源"
      },
      dateRange:[],
      users:[],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/crm/customer/importLineData",
      },
      assign:{
        title:"分配客户",
        open:false,
      },
      // 部门树选项
      deptOptions: undefined,
      cityIds:[],
      citys:[],
      tags:[],
      inputVisible: false,
      inputValue: '',
      statusOptions:[],
      typeOptions:[],
      sourceOptions:[],
      sexOptions:[],
      show:{
        title:"客户详情",
        open:false,
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户表格数据
      customerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerCode: null,
        customerName: null,
        mobile: null,
        sex: null,
        weixin: null,
        userId: null,
        createUserId: null,
        receiveUserId: null,
        customerUserId: null,
        address: null,
        location: null,
        detailAddress: null,
        lng: null,
        lat: null,
        status: null,
        isReceive: null,
        deptId: null,
        isDel: null,
        customerType: null,
        receiveTime: null,
        poolTime: null,
        companyId: null,
        isLine: 1,
        source: null,
        tags: null,
        isDuplicate:null,
        customerLevel: null
      },
      // 表单参数
      form: {
        province:null,
        city:null,
        district:null,
      },
      // 表单校验
      rules: {
        customerName: [
          { required: true, message: "客户名称不能为空", trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "手机号不能为空", trigger: "blur" }
        ],
        sex: [
          { required: true, message: "性别不能为空", trigger: "blur" }
        ],
        source: [
          { required: true, message: "客户来源不能为空", trigger: "blur" }
        ],
      },
      customerLevelOptions: [],
      customerLevelOpenOptions: []
    };
  },

  created() {
    this.getDicts("crm_customer_source").then((response) => {
      this.sourceOptions = response.data;
    });
    this.getDicts("common_sex").then((response) => {
      this.sexOptions = response.data;
    });

    this.getDicts("common_sex").then((response) => {
      this.sexOptions = response.data;
    });
    this.getDicts("crm_customer_status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("crm_customer_type").then((response) => {
      this.typeOptions = response.data;
    });
    this.getDicts("crm_customer_tag").then((response) => {
        this.tagsOptions = response.data;
    });
    this.getDicts("crm_customer_user_status").then((response) => {
      this.visitStatusOptions = response.data;
    });

    this.getList();
    this.getCustomerLevelOptions()
  },
  methods: {
    getCustomerLevelOptions(){
      customerLevelOptions().then((response) => {
        this.customerLevelOptions = response.data;
      });
    },
    handleShow(row){
      this.show.open=true;
      var that=this;
      setTimeout(() => {
        console.log("qxj dCustomerId ",row.dcustomerId);
        that.$refs.customerDetails.initDuplicate(row.isDuplicate,row.dcustomerId);
        that.$refs.customerDetails.getDetails(row.customerId);
      }, 200);
    },
    handleAssignList(){
      this.assignList.open=true;
      var that=this;
      setTimeout(() => {
        that.$refs.assignList.getData();
      }, 200);
    },
    closeAssignList(){
      this.assignList.open=false;
      this.getList();
    },
    handleAdd() {
      this.customer.open = true;
      var that=this;
      setTimeout(() => {
        that.$refs.customer.handleAdd(1);
      }, 200);
    },
    closeCustomer(){
        this.customer.open=false;
        this.getList();
    },
    handleEditScource(){
      this.source.open=true;
      var that=this;
      setTimeout(() => {
        that.$refs.editSource.handleEdit(that.ids);
      }, 200);

    },
    closeSource(){
        this.source.open=false;
        this.getList();
    },

    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    handleCityChange(value) {
      console.log(value);
      var nodes=this.$refs.citySelect.getCheckedNodes();
      this.form.address=nodes[0].pathLabels[0]+"-"+nodes[0].pathLabels[1]+"-"+nodes[0].pathLabels[2];
      this.form.cityIds=value.toString();
    },

    handleAssign(){
      var that=this;
      var ids=this.ids;
      that.assign.open=true;
      setTimeout(() => {
          that.$refs.assignUser.init(ids,4);
      }, 200);
    },
    closeAssign(){
      this.assign.open=false;
      this.getList();
    },
    closeAssignPop(){
         this.$refs.assignUser.closeAction();
    },
    /** 查询客户列表 */
    getList() {
      this.loading = true;
      if(this.tagIds.length>0){
        this.queryParams.tags=this.tagIds.toString();
      }
      else{
        this.queryParams.tags=null
      }
      getLineCustomerList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.customerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        customerId: null,
        customerCode: null,
        customerName: null,
        mobile: null,
        sex: null,
        weixin: null,
        remark: null,
        userId: null,
        createUserId: null,
        receiveUserId: null,
        customerUserId: null,
        address: null,
        location: null,
        detailAddress: null,
        lng: null,
        lat: null,
        createTime: null,
        updateTime: null,
        status: 0,
        isReceive: null,
        deptId: null,
        isDel: null,
        customerType: null,
        receiveTime: null,
        poolTime: null,
        companyId: null,
        isLine: null,
        source: null,
        tags: null
      };
      this.tags=[];
      this.cityIds=[];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.customerId)
      this.single = selection.length!==1
      this.multiple = !selection.length
      console.log(this.ids)
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const customerIds = row.customerId || this.ids;
      this.$confirm('是否确认删除客户编号为"' + customerIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delLineCustomer(customerIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.exportTime=10;
        this.xy.open=true;
        var that=this;
        this.exportDisable=true;
        that.exportInteval= setInterval(function(){
          that.exportBtnText="同意隐私协议("+that.exportTime+")"
          that.exportTime--;
          if(that.exportTime<1){
            that.exportBtnText="同意隐私协议"
            clearInterval(that.exportInteval)
            that.exportInteval=null;
            that.exportDisable=false;
          }
        },1000);
    },
    submitExport(){
      var that=this;
      if(this.tagIds.length>0){
        this.queryParams.tags=this.tagIds.toString();
      }
      else{
        this.queryParams.tags=null
      }
      this.$confirm('是否确认导出所有客户数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          that.exportLoading = that.$loading({
            lock: true,
            text: '处理中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          return exportCustomer(that.addDateRange(that.queryParams, that.dateRange));
        }).then(response => {
          that.exportLoading.close();
          that.download(response.msg);
        }).catch(function() {});
    },


     /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "线索客户导入";
      this.upload.open = true;

    },
    /** 下载模板操作 */
    importTemplate() {
      importLineTemplate().then((response) => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.importMsgOpen=true;
      this.importMsg=response.msg
      this.getList();
    },
     // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    getCustomerName(customerName){
       if(customerName==null || customerName==""){
         return "";
       }
       return customerName;
    }
  }
};
</script>
<style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .el-dialog__wrapper{
    z-index: 100000;
  }
  .xy-content{

  }
  .xy-img{
    border: 1px solid #dedede;
    padding: 15px;
    margin: 15px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  .footer{
      display: flex;
      align-items: center;
      justify-content: flex-end;
  }
</style>
