<template>
  <div class="app-container customer-page">
    <div v-show="showSearch" class="filter-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="90px" class="filter-form">
      <el-form-item label="公司名称" prop="companyId">
        <el-select filterable v-model="queryParams.companyId" placeholder="请选择公司名称" clearable size="small" class="filter-control">
          <el-option
            v-for="item in companys"
            :key="'companyId'+item.companyId"
            :label="item.companyName"
            :value="item.companyId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户编码" prop="customerCode">
        <el-input
          v-model="queryParams.customerCode"
          placeholder="请输入客户编码"
          clearable
          size="small"
          class="filter-control"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          size="small"
          class="filter-control"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号码"
          clearable
          size="small"
          class="filter-control"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择客户状态" clearable size="small" class="filter-control">
          <el-option
            v-for="item in statusOptions"
            :key="'status'+item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户类型" prop="customerType">
        <el-select multiple v-model="ctsTypeArr" placeholder="请选择客户类型" clearable size="small" class="filter-control">
          <el-option
            v-for="item in typeOptions"
            :key="'type'+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"
          class="filter-control filter-date"
          v-model="dateRange"
          type="daterange"
          value-format="yyyy-MM-dd"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleScheduleTimeChange"
        />
      </el-form-item>
      <el-form-item label="客户来源" prop="source">
        <el-select multiple v-model="sourceArr" placeholder="请选择客户来源" clearable size="small" class="filter-control">
          <el-option
            v-for="item in sourceOptions"
            :key="'source'+item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户标签" prop="tags">
        <el-select multiple v-model="tagIds" placeholder="请选择客户标签" clearable size="small" class="filter-control">
          <el-option
            v-for="item in tagsOptions"
            :key="'tags'+item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否下单" prop="isBuy">
        <el-select filterable v-model="queryParams.isBuy" placeholder="请选择是否下单" clearable size="small" class="filter-control">
          <el-option key="1" label="已下单" value="1" />
          <el-option key="0" label="未下单" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item class="filter-actions">
        <el-button type="cyan" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
      </el-form>
    </div>

    <div class="toolbar-row">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handleEditSource"
          v-hasPermi="['crm:customer:editSource']"
        >修改客户来源</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:edit']"
        >修改</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:remove']"
        >删除</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>
    </div>

    <div class="table-card">
    <el-table
      border
      stripe
      v-loading="loading"
      :data="customerList"
      class="customer-table"
      :max-height="tableMaxHeight"
      :header-cell-style="tableHeaderStyle"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="48" align="center" fixed="left" />
      <el-table-column label="ID" align="center" prop="customerId" width="72" show-overflow-tooltip />
      <el-table-column label="公司名称" align="center" prop="companyName" min-width="110" show-overflow-tooltip />
      <el-table-column label="客户编码" align="center" prop="customerCode" min-width="110" show-overflow-tooltip />
      <el-table-column label="客户名称" align="center" prop="customerName" min-width="100" show-overflow-tooltip />
      <el-table-column label="手机号码" align="center" prop="mobile" min-width="130" show-overflow-tooltip />
      <el-table-column label="性别" align="center" prop="sex" width="72">
        <template slot-scope="scope">
          <el-tag size="mini" v-for="(item, index) in sexOptions" :key="'sex'+index" v-if="scope.row.sex==item.dictValue">{{item.dictLabel}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="微信号" align="center" prop="weixin" min-width="100" show-overflow-tooltip />
      <el-table-column label="所在地" align="center" prop="address" min-width="120" show-overflow-tooltip />
      <el-table-column label="标签" align="center" prop="tags" min-width="100" show-overflow-tooltip />
      <el-table-column label="客户来源" align="center" prop="source" min-width="100">
        <template slot-scope="scope">
          <el-tag size="mini" v-for="(item, index) in sourceOptions" :key="'source'+index" v-if="scope.row.source==item.dictValue">{{item.dictLabel}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="客户类型" align="center" prop="customerType" min-width="100">
        <template slot-scope="scope">
          <el-tag size="mini" v-for="(item, index) in typeOptions" :key="'customerType'+index" v-if="scope.row.customerType==item.dictValue">{{item.dictLabel}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="客户状态" align="center" prop="status" min-width="100">
        <template slot-scope="scope">
          <el-tag size="mini" v-for="(item, index) in statusOptions" :key="'status'+index" v-if="scope.row.status==item.dictValue">{{item.dictLabel}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="认领人" align="center" prop="companyUserNickName" min-width="90" show-overflow-tooltip />
      <el-table-column label="领取时间" align="center" prop="startTime" width="160" show-overflow-tooltip />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" show-overflow-tooltip />
      <el-table-column label="最后一次跟进时间" align="center" prop="receiveTime" width="160" show-overflow-tooltip />
      <el-table-column label="入公海时间" align="center" prop="poolTime" width="160" show-overflow-tooltip />

      <el-table-column label="操作" fixed="right" width="168" 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:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleShow(scope.row)"
            v-hasPermi="['crm:customer:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['crm:customer:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    </div>
    <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="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户编码" prop="customerCode">
          <el-input v-model="form.customerCode" :disabled="form.customerId!=null" placeholder="请输入客户编码" />
        </el-form-item>
        <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="customerType">
          <el-select v-model="form.customerType" placeholder="请选择客户类型" clearable size="small">
            <el-option
              v-for="item in typeOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="item.dictValue" v-for="item in statusOptions">{{item.dictLabel}}</el-radio>
          </el-radio-group>
        </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="remark">
          <el-input :rows="2" v-model="form.remark" type="textarea" 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-drawer
      size="75%"
      :title="show.title" :visible.sync="show.open">
      <customer-details  ref="customerDetails" />
    </el-drawer>

    <el-dialog :title="source.title" :visible.sync="source.open" width="600px" append-to-body>
      <edit-customer-source  ref="editSource" @close="closeSource"></edit-customer-source>
    </el-dialog>
  </div>
</template>

<script>
import { listCustomer,getCustomer,addCustomer,updateCustomer,delCustomer,exportCustomer  } from "@/api/crm/customer";
import { getCompanyList } from "@/api/company/company";
import customerDetails from '../components/customerDetails.vue';
import editCustomerSource from '../components/editCustomerSource.vue';
import {getCitys} from "@/api/his/city";
import { throwStatement } from "@babel/types";
export default {
  name: "Customer",
  components: { customerDetails,editCustomerSource },
  data() {
    return {
      tableMaxHeight: 520,
      tableHeaderStyle: { background: '#f5f7fa', color: '#606266', fontWeight: '600' },
      source:{
        title:"修改客户来源",
        open:false,
      },
      tagId:null,
      tagsOptions:[],
      ctsTypeArr:[],
      sourceArr:[],
      dateRange:[],
      cityIds:[],
      citys:[],
      tags:[],
      tagIds:[],
      inputVisible: false,
      inputValue: '',
      statusOptions:[],
      typeOptions:[],
      sourceOptions:[],
      sexOptions:[],
      pageSizes: [10, 20, 30, 50,100,500 ],
      show:{
        title:"客户详情",
        open:false,
      },
      companys:[],
      // 遮罩层
      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: null,
        source: null,
        tags: null,
        beginTime: null,
        endTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      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" }
        ],
      }
    };
  },
  created() {
    this.updateTableHeight();
    window.addEventListener('resize', this.updateTableHeight);
    this.getDicts("crm_customer_tag").then((response) => {
      this.tagsOptions = response.data;
    });
    this.getDicts("crm_customer_source").then((response) => {
      this.sourceOptions = response.data;
    });
    this.getDicts("sys_sex").then((response) => {
      this.sexOptions = response.data;
    });
    this.getDicts("sys_crm_customer_status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_crm_customer_type").then((response) => {
      this.typeOptions = response.data;
    });
    getCompanyList().then(response => {
      this.companys = response.data;
    });
    this.getCitys();
    this.getList();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.updateTableHeight);
  },
  methods: {
    updateTableHeight() {
      this.tableMaxHeight = Math.max(360, window.innerHeight - 340);
    },
    handleScheduleTimeChange(val) {
      if (val) {
        this.queryParams.beginTime = val[0];
        this.queryParams.endTime = val[1];
      } else {
        this.queryParams.beginTime = null;
        this.queryParams.endTime = null;
      }
    },
    handleEditSource(){
      this.source.open=true;
      var that=this;
      setTimeout(() => {
        that.$refs.editSource.handleEdit(that.ids);
      }, 200);

    },
    closeSource(){
      this.source.open=false;
      this.getList();
    },
    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();
    },
    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();
    },
    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();
    },
    getCitys(){
      getCitys().then(res => {
        this.loading = false;
        this.citys=res.data;
      })
    },
    handleShow(row){
      var that=this;
      that.show.open=true;
      setTimeout(() => {
        that.$refs.customerDetails.getDetails(row.customerId);
      }, 200);
    },
    /** 查询客户列表 */
    getList() {
      this.loading = true;
      if(this.ctsTypeArr.length>0){
        this.queryParams.customerType=this.ctsTypeArr.toString();
      }
      else{
        this.queryParams.customerType=null
      }

      if(this.sourceArr.length>0){
        this.queryParams.source=this.sourceArr.toString();
      }
      else{
        this.queryParams.source=null
      }
      if(this.tagIds.length>0){
        this.queryParams.tags=this.tagIds.toString();
      }
      else{
        this.queryParams.tags=null
      }

      listCustomer(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: "1",
        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.queryParams.beginTime = null;
      this.queryParams.endTime = null;
      this.dateRange = null;
      this.resetForm("queryForm");
      //this.$forceUpdate(); // 强制更新视图
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.customerId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const customerId = row.customerId || this.ids
      var that=this;
      getCustomer(customerId).then(response => {
        this.form = response.customer;
        if(this.form.status!=null){
          this.form.status = this.form.status.toString();
        }
        if(this.form.customerType!=null){
          this.form.customerType = this.form.customerType.toString();
        }
        if(this.form.sex!=null){
          this.form.sex = this.form.sex.toString();
        }
        if(this.form.source!=null){
          this.form.source = this.form.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) {
            updateCustomer(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addCustomer(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 delCustomer(customerIds);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      //const queryParams = this.queryParams;
      const queryParams=this.addDateRange(this.queryParams, this.dateRange)
      this.$confirm('是否确认导出客户数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return exportCustomer(queryParams);
      }).then(response => {
        this.download(response.msg);
      }).catch(function() {});
    }
  }
};
</script>
<style scoped lang="scss">
.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;
}
</style>
<style>
.el-dialog__wrapper{
  z-index: 100000;
}
</style>
