<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="sellerName">
        <el-input
          v-model="queryParams.sellerName"
          placeholder="请输入卖家昵称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="选择日期">
        <el-date-picker
          v-model="queryParams.uploadDate"
          type="month"
          placeholder="选择月"
          style="width: 240px"
          value-format="yyyy-MM"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="行业" prop="industryId">
        <el-select
          filterable
          v-model="queryParams.industryId"
          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 label="是否分配销售" prop="distributionSaleFlag">
        <el-select
          v-model="queryParams.distributionSaleFlag"
          placeholder="是否分配销售"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in queryParamsList.distributionSaleFlagList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="粉丝量级" prop="fansType">
        <el-select
          v-model="queryParams.fansType"
          placeholder="粉丝量级"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in queryParamsList.fansList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="类别" prop="salesLeadsType">
        <el-select
          v-model="queryParams.salesLeadsType"
          placeholder="请选择类别"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in queryParamsList.salesLeadsTypeList"
            :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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-document-add"
          size="mini"
          @click="handleAdd"
          >上传报表</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-s-custom"
          size="mini"
          @click="handleAllocation"
          :disabled="ids.length == 0"
          >分配人员</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-printer"
          size="mini"
          @click="handleAllRobotTelephone"
          :disabled="ids.length == 0"
          >批量导入外呼</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-printer"
          size="mini"
          @click="handleLog"
          >导入外呼记录</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleRefreshCache"
          >刷新缓存</el-button
        >
      </el-col>
      <!-- <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar> -->
    </el-row>
    <el-dialog title="查看外呼导入记录" :visible.sync="dialogTableVisible">
      <el-table :data="logData" :loading="logLoading">
        <el-table-column
          property="createTime"
          label="日期"
          width="150"
          align="center"
        ></el-table-column>
        <el-table-column
          property="name"
          label="导入线索数量"
          width="200"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.successList.length + scope.row.errorList.length }}条
          </template>
        </el-table-column>
        <el-table-column property="success" label="导入成功" align="center">
          <template slot-scope="scope">
            {{ scope.row.successList.length }}条
          </template>
        </el-table-column>
        <el-table-column property="error" label="导入失败" align="center">
          <template slot-scope="scope">
            {{ scope.row.errorList.length }}条(<el-button
              size="mini"
              type="text"
              :disabled="scope.row.errorList.length == 0"
              @click="handleUploadAll(scope.row)"
              >重新导入</el-button
            >)
          </template>
        </el-table-column>
        <el-table-column
          property="createUserName"
          label="操作人"
          align="center"
        ></el-table-column>
      </el-table>
      <pagination
        v-show="logTotal > 0"
        :total="logTotal"
        :page.sync="logPage.pageNum"
        :limit.sync="logPage.pageSize"
        @pagination="getLogList"
      />
    </el-dialog>

    <el-table
      v-loading="loading"
      :data="typeList"
      @selection-change="handleSelectionChange"
      ref="multipleTable"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        :selectable="selectable"
      />
      <el-table-column label="卖家ID" align="center" prop="sellerId" />
      <el-table-column label="卖家昵称" align="center" prop="sellerName" />
      <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="cityName" />
      <el-table-column label="卖家粉丝数" align="center" prop="fans">
        <template slot-scope="scope">
          {{ scope.row.fans ? scope.row.fans : "-" }}
        </template>
      </el-table-column>
      <el-table-column label="是否跃迁" align="center" prop="transitionFlag">
        <template slot-scope="scope">
          {{ scope.row.transitionFlag ? scope.row.transitionFlag : "-" }}
        </template>
      </el-table-column>
      <el-table-column
        label="是否导入外呼"
        align="center"
        prop="importPhoneFlag"
      >
        <template slot-scope="scope">
          {{ scope.row.importPhoneFlag == 0 ? "否" : "是" }}
        </template>
      </el-table-column>

      <el-table-column
        label="联系方式"
        align="center"
        prop="telephone"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="是否绑定服务商"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          {{ scope.row.providerFlag ? scope.row.providerFlag : "-" }}
        </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="GMV" align="center" prop="gmv">
        <template slot-scope="scope">
          <span v-if="scope.row.gmv">{{ scope.row.gmv }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="MTD" align="center" prop="mtd">
        <template slot-scope="scope">
          <span v-if="scope.row.mtd">{{ scope.row.mtd }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="近30天" align="center" prop="nearlyThirtyDays">
        <template slot-scope="scope">
          <span v-if="scope.row.nearlyThirtyDays">{{
            scope.row.nearlyThirtyDays
          }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <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="handleAllocationOne(scope.row)"
            :disabled="!!scope.row.saleName"
            >分配</el-button
          >
          <el-button size="mini" type="text" @click="handleUpload(scope.row)"
            >导入外呼</el-button
          >
        </template>
      </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="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="选择类别" prop="salesLeadsType">
          <el-select
            v-model="form.salesLeadsType"
            placeholder="选择类别"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="item in formList.salesLeadsTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择月份" prop="uploadDate">
          <el-date-picker
            v-model="form.uploadDate"
            type="month"
            placeholder="选择月"
            style="width: 240px"
            value-format="yyyy-MM"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="销售线索">
          <el-upload
            class="upload-demo"
            action="http://192.168.0.195:9003/sale/saleClueInfoController/importSaleExcelOrCsv"
            :before-upload="handleBeforeUpload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            accept=""
            :on-exceed="handleExceed"
            :file-list="fileList"
            :show-file-list="false"
          >
            <el-button size="small" icon="el-icon-upload">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传.csv .xlsx .xls文件
              <br />
              <span v-if="!!dateFile">{{ dateFile.name }}</span>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="confirmLoading"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 分配销售-->
    <el-dialog
      :title="title"
      :visible.sync="openAllocation"
      width="1000px"
      append-to-body
    >
      <div
        v-for="(item, index) in saleAllocationList"
        :key="item.id"
        style="margin-bottom: 10px; display: flex"
      >
        <el-descriptions title="">
          <el-descriptions-item label="卖家昵称"
            >{{ item.sellerName }}({{ item.sellerId }})</el-descriptions-item
          >
          <el-descriptions-item label="粉丝数">{{
            item.fans
          }}</el-descriptions-item>
          <el-descriptions-item label="联系方式">{{
            item.telephone
          }}</el-descriptions-item>
        </el-descriptions>
        <i
          class="el-icon-delete"
          style="cursor: pointer"
          v-if="saleAllocationList.length > 1"
          @click="removeListOne(index)"
        ></i>
      </div>
      <el-form label-width="80px">
        <el-form-item label="选择销售" prop="sale">
          <el-select
            filterable
            v-model="saleId"
            placeholder="选择销售"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="item in saleList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitSale"
          :loading="confirmLoadingSale"
          >确 定</el-button
        >
        <el-button
          @click="
            openAllocation = false;
            confirmLoadingSale = false;
            saleId = undefined;
            saleAllocationList = [];
          "
          >取 消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listType,
  getType,
  delType,
  addType,
  updateType,
  refreshCache,
} from "@/api/system/dict/type";
import {
  getSaleList,
  importSaleExcelOrCsv,
  getSaleAllocationList,
  saleClueDistribution,
  getIndustryInfoList,
  getUserByRoleName,
  getUserRoleByUserId,
  importRobotTelephone,
  getRobotTelephoneRecordList,
} 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,
        sellerName: undefined,
        uploadDate: new Date(),
        distributionSaleFlag: undefined,
        industryId: undefined,
        fansType: undefined,
        salesLeadsType: undefined,
        userId: undefined,
      },
      //查询参数所用下拉数据
      queryParamsList: {
        industryList: [], //行业下拉
        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;
    let date = new Date();
    let y = date.getFullYear();
    let MM = date.getMonth() + 1;
    MM = MM < 10 ? "0" + MM : MM;
    this.queryParams.uploadDate = `${y}-${MM}`;
    this.getUserRoleByUserId();
  },
  mounted() {
    this.$nextTick(() => {
      // this.getList();
      this.getIndustryInfoList();
    });
  },
  methods: {
    /** 获取用户信息 */
    getUserRoleByUserId() {
      getUserRoleByUserId({ userId: this.userId })
        .then((res) => {
          if (res.data[0].role_key == "electricPin") {
            this.queryParams.salesLeadsType = 2;
          } else if (res.data[0].role_key == "facePin") {
            this.queryParams.salesLeadsType = 3;
          } else {
            this.queryParams.salesLeadsType = 2;
          }
          this.getList();
        })
        .catch((error) => {});
    },
    /** 复选框禁用 */
    selectable(row, index) {
      return true;
      // if (!!row.saleName) {
      //   return false;
      // } else {
      //   return true;
      // }
    },
    /** 获取行业列表 */
    getIndustryInfoList() {
      getIndustryInfoList()
        .then((res) => {
          this.queryParamsList.industryList = res.data.map((item) => {
            return {
              label: item.name,
              value: item.id,
            };
          });
        })
        .catch((err) => {});
    },
    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;
      getSaleList(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 = [];
      let date = new Date();
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      this.queryParams.uploadDate = `${y}-${MM}`;
      this.resetForm("queryForm");
      this.queryParams.pageNum = 1;
      // this.handleQuery();
      this.getUserRoleByUserId();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "上传报表";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
    },
    /** 导入外呼 */
    handleUpload(item) {
      this.$confirm("是否确认导入？")
        .then((_) => {
          var params = {};
          params.ids = item.id;
          params.userId = this.userId;
          importRobotTelephone(params)
            .then((res) => {
              this.$message.success(res.msg);
            })
            .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(res.msg);
            this.getLogList()
          })
          .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(`本次导入${this.ids.length}条,是否确认导入？`)
        .then((_) => {
          var params = {};
          params.ids = this.ids.join();
          params.userId = this.userId;
          importRobotTelephone(params)
            .then((res) => {
              this.$message.success(res.msg);
            })
            .catch(() => {});
        })
        .catch((_) => {
          this.ids = [];
          this.handleQuery();
        });
    },
    /** 单条销售线索分配列表 */
    handleAllocationOne(item) {
      console.log(item);
      this.getAllocationList(item.id);
    },
    /** 多销售线索分配列表 */
    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>
