<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="跟进状态" prop="state">
        <el-select
          filterable
          v-model="queryParams.state"
          placeholder="选择跟进状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in queryParamsList.industryList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          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-table
      v-loading="loading"
      :data="typeList"
      @selection-change="handleSelectionChange"
      ref="multipleTable"
    >
      <el-table-column label="卖家ID" align="center" prop="seller_id" />
      <el-table-column label="卖家昵称" align="center" prop="seller_name" />
      <el-table-column label="行业" align="center" prop="industryName">
        <template slot-scope="scope">
          {{ scope.row.industryName ? scope.row.industryName : "-" }}
        </template>
      </el-table-column>
      <el-table-column label="联系方式" align="center" prop="customerPhone" />
      
      <el-table-column label="跟进状态" align="center" prop="state">
        <template slot-scope="scope">
          {{ scope.row.state | stateName }}
        </template>
      </el-table-column>
      <el-table-column label="开始拨打时间" align="center" prop="startedAt">
      </el-table-column>
      <el-table-column label="通话时长" align="center" prop="duration">
      </el-table-column>
      <el-table-column
        label="话术名称"
        align="center"
        prop="surveyName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="客户关注点"
        align="center"
        :show-overflow-tooltip="true"
        prop="focus"
      >
        <template slot-scope="scope">
          <div v-if="JSON.parse(scope.row.focus).length == 0">-</div>
          <div v-else>
            <span v-for="(item, index) in JSON.parse(scope.row.focus)">
              {{ item
              }}{{ index == JSON.parse(scope.row.focus).length - 1 ? "" : "," }}
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="销售" align="center" prop="saleName">
        <template slot-scope="scope">
          {{ scope.row.saleName ? scope.row.saleName : "-" }}
        </template>
      </el-table-column>

      <el-table-column label="录音地址" align="center" prop="recordUrl">
      </el-table-column>
      <el-table-column label="对话内容" align="center" prop="content">
        <template slot-scope="scope">
          <span v-for="(item, index) in scope.row.speakerContent">
            {{ item.script == "" ? "暂无对话" : item.script
            }}{{ index == scope.row.speakerContent.length - 1 ? "" : "," }}
          </span>
        </template>
      </el-table-column>
    </el-table>

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

<script>
import {
  listType,
  getType,
  delType,
  addType,
  updateType,
  refreshCache,
} from "@/api/system/dict/type";
import {
  getSaleList,
  importSaleExcelOrCsv,
  getSaleAllocationList,
  saleClueDistribution,
  getUserByRoleName,
  importRobotTelephone,
  getRobotTelephoneRecordList,
  getRobotTelephoneResultList,
} from "@/api/sales/sale";
export default {
  name: "sale",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      dialogTableVisible: false,
      logPage: {
        pageNum: 1,
        pageSize: 10,
      },
      logData: [],
      logTotal: 0,
      logLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      typeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 分配销售
      openAllocation: false,
      // 选择的销售id
      saleId: undefined,
      // 获取用户id
      userId: undefined,
      // 销售列表
      saleList: [],
      // 分配销售确定loading
      confirmLoadingSale: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        createTime: undefined,
        state: undefined,
      },
      //查询参数所用下拉数据
      queryParamsList: {
        industryList: [
          { value: 1, label: "未开始" },
          { value: 2, label: "进行中" },
          { value: 3, label: "已结束" },
        ], //行业下拉
        fansList: [
          { value: 1, label: "0~50W" },
          { value: 2, label: "50W~200W" },
          { value: 3, label: "200W~500W" },
          { value: 4, label: "500W以上" },
        ], //粉丝量级
        distributionSaleFlagList: [
          { value: 0, label: "否" },
          { value: 1, label: "是" },
        ], //是否分配销售
        salesLeadsTypeList: [
          { value: 1, label: "50W低潜" },
          { value: 2, label: "50W中高潜" },
          { value: 3, label: "200W高潜" },
          { value: 4, label: "200W~500W" },
          { value: 5, label: "500W以上" },
        ], //销售线索类型
      },
      // 表单参数
      form: {},
      //上传报表下拉数据
      formList: {
        salesLeadsTypeList: [
          { value: 1, label: "50W低潜" },
          { value: 2, label: "50W中高潜" },
          { value: 3, label: "200W高潜" },
          { value: 4, label: "200W~500W" },
          { value: 5, label: "500W以上" },
        ], //销售线索类型
      },
      fileList: [],
      //获取销售线索文件流
      dateFile: null,
      //销售线索上传loading
      confirmLoading: false,
      // 表单校验
      rules: {
        salesLeadsType: [
          { required: true, message: "选择类别不能为空", trigger: "blur" },
        ],
        uploadDate: [
          { required: true, message: "月份不能为空", trigger: "blur" },
        ],
      },
      // 分配销售展示列表
      saleAllocationList: [],
    };
  },
  created() {
    this.userId = this.$store.getters.userId;

    this.getList();
  },
  mounted() {},
  filters: {
    stateName(status) {
      const statusMap = {
        1: "未开始",
        2: "进行中",
        3: "已结束",
        null: "-",
      };
      return statusMap[status];
    },
  },
  methods: {
    /** 复选框禁用 */
    selectable(row, index) {
      return true;
      // if (!!row.saleName) {
      //   return false;
      // } else {
      //   return true;
      // }
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return false;
    },
    /** 删除文件 */
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    /** 上传文件 */
    handlePreview(file) {
      console.log(file);
    },
    /** 上传文件前验证 */
    handleBeforeUpload(file) {
      console.log(file);
      const fileSuffix = ["xlsx", "xls", "csv"];
      const fileName = file.name;
      const fileStrArr = fileName.split(".");
      const suffix = fileStrArr[fileStrArr.length - 1];

      let result = fileSuffix.some((item) => {
        return item === suffix;
      });

      if (!result) {
        this.$message.error("不支持该文件类型");
        this.loadDisabled = false;
        return false;
      }
      this.dateFile = file;
      return false;
    },
    /** 查询字典类型列表 */
    getList() {
      this.loading = true;
      getRobotTelephoneResultList(this.queryParams).then((response) => {
        this.typeList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.confirmLoading = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.dateFile = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.pageNum = 1;
      // this.handleQuery();
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "上传报表";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.sellerId);
    },
    /** 导入外呼 */
    handleUpload(item) {
      this.$confirm("本次导入数据100条，是否确认导入！")
        .then((_) => {
          var params = {};
          params.ids = item.id;
          params.userId = this.userId;
          importRobotTelephone(params)
            .then((res) => {
              this.$message.success("导入成功");
            })
            .catch(() => {});
        })
        .catch((_) => {});
    },
    handleUploadAll(item) {
      if (item.errorList.length > 0) {
        var params = {};
        params.ids = item.errorList
          .map((c) => {
            return c.id;
          })
          .join();
        params.userId = this.userId;
        importRobotTelephone(params)
          .then((res) => {
            this.$message.success("导入成功");
          })
          .catch(() => {});
      }
    },
    getLogList() {
      var params = {};
      params.pageNum = this.logPage.pageNum;
      params.pageSize = this.logPage.pageSize;
      this.logLoading = true;
      getRobotTelephoneRecordList(params)
        .then((res) => {
          this.logData = res.data.rows;
          this.logTotal = res.data.total;
          this.logLoading = false;
        })
        .catch(() => {
          this.logLoading = false;
        });
    },
    /** 外呼导入记录 */
    handleLog() {
      this.dialogTableVisible = true;
      this.getLogList();
    },
    /** 批量导入外呼 */
    handleAllRobotTelephone() {
      this.$confirm("是否确认导入！")
        .then((_) => {
          var params = {};
          params.ids = this.ids.join();
          params.userId = this.userId;
          importRobotTelephone(params)
            .then((res) => {
              this.$message.success("导入成功");
            })
            .catch(() => {});
        })
        .catch((_) => {
          this.ids = [];
          this.handleQuery();
        });
    },
    /** 单条销售线索分配列表 */
    handleAllocationOne(item) {
      console.log(item);
      this.getAllocationList(item.sellerId);
    },
    /** 多销售线索分配列表 */
    handleAllocation() {
      this.getAllocationList(null);
    },
    /** 获取分配销售列表 */
    getAllocationList(sellerIds) {
      var params = {};
      if (sellerIds) {
        params.sellerIds = sellerIds;
        this.ids = [sellerIds];
      } else {
        params.sellerIds = this.ids.join();
      }
      getSaleAllocationList(params)
        .then((res) => {
          if (res.code === 200) {
            this.openAllocation = true;
            this.title = "分配销售";
            this.saleAllocationList = res.data;
            getUserByRoleName({ roleName: "electricPin,facePin" })
              .then((res) => {
                this.saleList = res.data.map((item) => {
                  return {
                    value: item.user_id,
                    label: item.nick_name,
                  };
                });
              })
              .catch((error) => {});
          }
        })
        .catch((err) => {
          this.$message.error("分配销售列表数据请求出错");
        });
    },
    // 销售列表删除
    removeListOne(index) {
      this.saleAllocationList.splice(index, 1);
    },
    // 分配销售确定
    submitSale() {
      if (!this.saleId) {
        this.$message.error("请选择销售");
      } else {
        this.confirmLoadingSale = true;
        saleClueDistribution({
          sellerIds: this.saleAllocationList
            .map((item) => {
              return item.sellerId;
            })
            .join(),
          saleId: this.saleId,
          createUserId: this.userId,
        })
          .then((res) => {
            this.openAllocation = false;
            this.confirmLoadingSale = false;
            this.saleId = undefined;
            this.$refs.multipleTable.clearSelection();
            this.handleQuery();
          })
          .catch((err) => {
            this.confirmLoadingSale = false;
          });
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const dictId = row.dictId || this.ids;
      getType(dictId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改字典类型";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.dateFile) {
            this.confirmLoading = true;
            let formData = new FormData();
            formData.append("file", this.dateFile);
            formData.append("salesLeadsType", this.form.salesLeadsType);
            formData.append("uploadDate", this.form.uploadDate);
            formData.append("createUserId", this.userId);
            importSaleExcelOrCsv(formData)
              .then((res) => {
                this.confirmLoading = false;
                this.$message.success("上传成功");
                this.cancel();
                this.handleQuery();
              })
              .catch((err) => {
                this.confirmLoading = false;
              });
          } else {
            this.$message.error("请上传文件");
          }

          // if (this.form.dictId != undefined) {
          //   updateType(this.form).then((response) => {
          //     this.$modal.msgSuccess("修改成功");
          //     this.open = false;
          //     this.getList();
          //   });
          // } else {
          //   addType(this.form).then((response) => {
          //     this.$modal.msgSuccess("新增成功");
          //     this.open = false;
          //     this.getList();
          //   });
          // }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dictIds = row.dictId || this.ids;
      this.$modal
        .confirm('是否确认删除字典编号为"' + dictIds + '"的数据项？')
        .then(function () {
          return delType(dictIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/dict/type/export",
        {
          ...this.queryParams,
        },
        `type_${new Date().getTime()}.xlsx`
      );
    },
    /** 刷新缓存按钮操作 */
    handleRefreshCache() {
      refreshCache().then(() => {
        this.$modal.msgSuccess("刷新成功");
      });
    },
  },
};
</script>
