<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="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 label="创建时间" prop="createTime">
        <el-date-picker clearable size="small" style="width: 205.4px"
          v-model="dateRange"
          type="daterange"
          value-format="yyyy-MM-dd"
          start-placeholder="开始日期" end-placeholder="结束日期"
           >
        </el-date-picker>
      </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"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['crm:customer:addLine']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['crm:customer:editLine']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['crm:customer:removeLine']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-if="queryParams.status=='0'"
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handleAssign"
          v-hasPermi="['crm:customer:assign']"
        >分配线索客户</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="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:exportLine']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-tabs type="card" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="待分配" name="0"></el-tab-pane>
      <el-tab-pane label="已分配" name="1"></el-tab-pane>
    </el-tabs>
    <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="ID" align="center" prop="customerId" />
      <el-table-column label="所属公司" align="center" prop="companyName" />
      <el-table-column label="客户编号" width="120"  align="center" prop="customerCode" />
      <el-table-column label="客户名称" align="center" prop="customerName" />
      <el-table-column label="手机" align="center" prop="mobile" />
      <el-table-column  label="性别" align="center" prop="sex">
        <template slot-scope="scope">
            <el-tag prop="status" v-for="(item, index) in sexOptions"    v-if="scope.row.sex==item.dictValue">{{item.dictLabel}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="微信号" align="center" prop="weixin" />
      <el-table-column label="所在地" align="center" prop="address" />
      <el-table-column width="105" label="创建时间" align="center" prop="createTime" />
      <el-table-column  label="客户来源" align="center" prop="source">
        <template slot-scope="scope">
            <el-tag prop="source" 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="trafficSource" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作"   align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['crm:customer:editLine']"
          >修改</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAssign(scope.row)"
            v-hasPermi="['crm:customer:assign']"
          >分配</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['crm:customer:removeLine']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page-sizes="pageSizes"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="form.customerName" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input maxlength="11"  v-model="form.mobile" placeholder="请输入手机" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio :label="item.dictValue" v-for="item in sexOptions" >{{item.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="微信号" prop="weixin">
          <el-input v-model="form.weixin" placeholder="请输入微信号" />
        </el-form-item>
        <el-form-item label="所在地区" prop="address">
          <el-cascader
          ref="citySelect"
          v-model="cityIds"
          :options="citys"
          @change="handleCityChange"></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="detailAddress">
          <el-input v-model="form.detailAddress" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="客户来源" prop="source">
          <el-select v-model="form.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 label="标签" prop="tags">
          <el-tag
            :key="tag"
            v-for="tag in tags"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)">
            {{tag}}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">添加标签+</el-button>
          <el-select @change="tagsChange"  v-model="tagId" placeholder="选择客户来源" style="width:140px;margin-left: 5px;" clearable size="small">
            <el-option
                  v-for="item in tagsOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
          </el-select>
        </el-form-item>
        <el-form-item label="进线日期" prop="registerDate">
          <el-date-picker
          value-format="yyyy-MM-dd"
            v-model="form.registerDate"
            type="date"
            placeholder="请选择进线日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="进线链接" prop="registerLinkUrl">
          <el-input v-model="form.registerLinkUrl" placeholder="请输入进线链接" />
        </el-form-item>
        <el-form-item label="进线客户详情" prop="registerDesc">
          <el-input v-model="form.registerDesc" placeholder="请输入进线客户详情" />
        </el-form-item>
        <el-form-item label="进线填写时间" prop="registerSubmitTime">
          <el-date-picker
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="form.registerSubmitTime"
            type="datetime"
            placeholder="请选择进线填写时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" :rows="2" v-model="form.remark"   placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <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="导入结果" :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="assign.title" :visible.sync="assign.open" @close="closeAssignPop" width="900px" append-to-body>
       <assign-company  ref="assignCompany" @close="closeAssign"   />
    </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>

  </div>
</template>

<script>
import { assignCustomer,importLineTemplate,listLineCustomer, getLineCustomer, delLineCustomer, addLineCustomer, updateLineCustomer, exportLineCustomer } from "@/api/crm/customer";
import {getCitys} from "@/api/store/city";
import { getToken } from "@/utils/auth";
import { isAdmin } from "@/api/system/user";

import customerAssignList from '../components/customerAssignList.vue';
import assignCompany from '../components/assignCompany.vue';

export default {
  name: "Customer",
  components: { customerAssignList,assignCompany },
  
  data() {
    return {
      assignList:{
        title:"分配历史记录",
        open:false,
      },
      importMsgOpen:false,
      importMsg:"",
      tagId:null,
      activeName:"0",
      tagsOptions:[],
      companys:[],
      noAssignCount:0,
      assignCount:0,
      assign:{
        title:"分配客户",
        open:false,
      },
      companySelect:{
        title:"选择公司",
        open:false,
      },
      assignForm: {
        companyId:null,
      },
      // 表单校验
      assignRules: {
        companyId: [
          { required: true, message: "公司不能为空", trigger: "blur" }
        ],
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/crm/customer/importLineData",
      },
      pageSizes: [10, 20, 30, 50,100,500 ],
      cityIds:[],
      citys:[],
      tags:[],
      inputVisible: false,
      inputValue: '',
      sourceOptions:[],
      sexOptions:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户表格数据
      customerList: [],
      dateRange:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      isAdmin: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: "0",
        isReceive: null,
        deptId: null,
        isDel: null,
        customerType: null,
        receiveTime: null,
        poolTime: null,
        companyId: null,
        isLine: null,
        source: null,
        tags: null
      },
      // 表单参数
      form: {
        province:null,
        city:null,
        district:null,
      },
      // 表单校验
      rules: {
        mobile: [
          { required: true, message: "手机号不能为空", trigger: "blur" }
        ],
        source: [
          { required: true, message: "客户来源不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getDicts("crm_customer_source").then((response) => {
      this.sourceOptions = response.data;
    });
    this.getDicts("common_sex").then((response) => {
      this.sexOptions = response.data;
    });
    this.getDicts("crm_customer_tag").then((response) => {
      this.tagsOptions = response.data;
    });

    isAdmin().then(res => {
         this.isAdmin=res.data;
         this.isAdmin=false;
     });

    this.getCitys();
    this.getList();
  },
  methods: {
    handleAssignList(){
      this.assignList.open=true;
      var that=this;
      setTimeout(() => {
            that.$refs.assignList.getData();
      }, 200);
    },
    closeAssign(){
      this.assign.open=false;
      this.getList();
    },
    closeAssignPop(){
       this.$refs.assignCompany.closeAction();
    },
    closeAssignList(){
      this.assignList.open=false;
      this.getList();
    },
    tagsChange(e){
      var item=this.tagsOptions.find(val => val.dictValue === e);
      console.log(item);
      this.tags.push(item.dictLabel);
      this.form.tags=this.tags.toString();
    },
    handleClick(tab, event) {
      this.activeName=tab.name;
      this.queryParams.status=tab.name
      this.getList();
    },
    handleCityChange(value) {
      var nodes=this.$refs.citySelect.getCheckedNodes();
      console.log(value);
      this.form.address=nodes[0].pathLabels[0]+"-"+nodes[0].pathLabels[1]+"-"+nodes[0].pathLabels[2];
      this.form.cityIds=value.toString();
    },
    getCitys(){
        getCitys().then(res => {
          this.loading = false;
          this.citys=res.data;
        })
    },
    handleClose(tag) {
        this.tags.splice(this.tags.indexOf(tag), 1);
        this.form.tags=this.tags.toString();
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.tags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
      this.form.tags=this.tags.toString();
    },
    /** 查询客户列表 */
    getList() {
      this.loading = true;
      listLineCustomer(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
    },
    handleAssign(){
    //if(this.isAdmin){
           var that=this
           this.assign.open = true;
           this.assign.title = "分配线索客户";
           setTimeout(() => {
              that.$refs.assignCompany.init(this.ids);
           }, 200);
      // }else{
      //      this.msgError("无权限操作!");
      // }
      
      // //获取所有CUSTOMER列表
      // var cutsomers=[];
      // this.customerList.forEach(function(value,index,array){
      //   that.ids.forEach(function(id,index,array){
      //     if(id==value.customerId){
      //       var data={customerId:value.customerId,customerName:value.customerName}
      //       cutsomers.push(data)
      //     }
      //   })
      // });
      // this.assignForm.customers=cutsomers;
      // this.assignCount=this.assignForm.customers.length;
    },
    submitAssignForm() {
      if(this.assignForm.customers.length==0){
        this.msgError("请选择客户");
        return;
      }
      this.$refs["assignForm"].validate(valid => {
        if (valid) {
          var ids=[];
          this.assignForm.customers.forEach(function(value,index,array){
             ids.push(value.customerId)
          });
          this.assignForm.customerIds=ids;
          assignCustomer(this.assignForm).then(response => {
              if (response.code === 200) {
                this.msgSuccess("分配成功");
                this.assign.open = false;
                this.getList();
              }
            });
        }
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加线索客户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      var that=this;
      const customerId = row.customerId || this.ids
      getLineCustomer(customerId).then(response => {
        this.form = response.data;
        this.form.sex = response.data.sex.toString();
        this.form.source = response.data.source.toString();
        if(this.form.tags!=null){
          this.tags = this.form.tags.split(",")
        }
        if(this.form.cityIds!=null){
          var ids=this.form.cityIds.split(",");
          this.cityIds=[];
          ids.forEach(element => {
              var id=parseInt(element);
              that.cityIds.push(id)
          });
        }
        this.open = true;
        this.title = "修改线索客户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.customerId != null) {
            updateLineCustomer(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addLineCustomer(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    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() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有客户数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportLineCustomer(queryParams);
        }).then(response => {
          this.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();
    }
  }
};
</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;
  }
</style>
