<template>
  <div class="app-container">
    <el-row class="top-sum">
      <el-col :span="8">
        <el-card shadow="never" class="card-show">
          <p class="p-title">我的待办</p>
          <p class="p-main">{{ taskNumber.noStarted }}个任务</p>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="never" class="card-show">
          <p class="p-title">本周电联主播数量</p>
          <p class="p-main">-</p>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="never" class="card-show">
          <p class="p-title">本周完成任务数</p>
          <p class="p-main">{{ taskNumber.complete }}个任务</p>
        </el-card>
      </el-col>
    </el-row>

    <el-card shadow="never" class="card-show">
      <div slot="header" class="clearfix">
        <span style="display: inline-block; line-height: 2">任务列表</span>
        <div style="float: right; padding: 3px 0; display: flex">
          <el-radio-group
            v-model="queryParams.state"
            size="mini"
            @change="getList"
          >
            <el-radio-button
              plain
              :label="item.value"
              v-for="item in queryParamsList.stateList"
              :key="item.value"
              >{{ item.label }}</el-radio-button
            >
          </el-radio-group>
          <el-input
            size="mini"
            placeholder="请输入卖家昵称"
            v-model="queryParams.sellerName"
            style="width: 300px; margin-left: 15px"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="handleQuery"
            ></el-button>
          </el-input>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="typeList"
        @selection-change="handleSelectionChange"
        ref="multipleTable"
      >
        <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="saleName">
          <template slot-scope="scope">
            {{ scope.row.saleName ? scope.row.saleName : "-" }}
          </template>
        </el-table-column>
        <el-table-column label="跟进进度" align="center" prop="continueFlag">
          <template slot-scope="scope">
            <span v-if="scope.row.recordTask">
              {{ scope.row.recordTask.continueFlag | continueFlagText }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          label="跟进详情"
          align="center"
          prop="recordInfo"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ scope.row.recordTask ? scope.row.recordTask.recordInfo : "-" }}
          </template>
        </el-table-column>
        <el-table-column
          label="跟进结果"
          align="center"
          prop="intendedCooperation"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.recordTask">
              {{
                scope.row.recordTask.intendedCooperation
                  | intendedCooperationText
              }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          show-overflow-tooltip
          align="center"
          prop="intendedCooperation"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.recordTask && scope.row.recordTask.remarks">
              {{ scope.row.recordTask.remarks }}
            </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="handleUpdate(scope.row)"
              :disabled="scope.row.state == 3"
              >编辑</el-button
            >
            <el-dropdown
              @command="handleEdit($event, scope.row)"
              :disabled="scope.row.state == 3"
            >
              <span class="el-dropdown-link">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-arrow-down el-icon--right"
                  :disabled="scope.row.state == 3"
                  >更多</el-button
                >
              </span>

              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="editSale">转销售</el-dropdown-item>
                <el-dropdown-item command="editType">转面销</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-descriptions title="" v-if="formDataShow" style="margin-bottom: 15px">
        <el-descriptions-item label="卖家昵称"
          >{{ formDataShow.saleRecordVo.sellerName }}({{
            formDataShow.saleRecordVo.sellerId
          }})</el-descriptions-item
        >
        <el-descriptions-item label="粉丝数">{{
          formDataShow.saleRecordVo.fans
        }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{
          formDataShow.saleRecordVo.telephone
        }}</el-descriptions-item>
        <el-descriptions-item label="行业">{{
          formDataShow.saleRecordVo.industryName
            ? formDataShow.saleRecordVo.industryName
            : "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="所属地区">{{
          formDataShow.saleRecordVo.cityName
        }}</el-descriptions-item>
        <el-descriptions-item label="是否绑定服务商">{{
          formDataShow.saleRecordVo.providerFlag == 0 ? "否" : "是"
        }}</el-descriptions-item>

        <el-descriptions-item label="MTD">{{
          formDataShow.saleRecordVo.mtd ? formDataShow.saleRecordVo.mtd : "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="GMV">{{
          formDataShow.saleRecordVo.gmv ? formDataShow.saleRecordVo.gmv : "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="近30天">{{
          formDataShow.saleRecordVo.nearlyThirtyDays
            ? formDataShow.saleRecordVo.nearlyThirtyDays
            : "-"
        }}</el-descriptions-item>
      </el-descriptions>
      <div v-if="formDataShow">
        <el-descriptions
          title=""
          style="margin-bottom: 15px"
          v-for="item in formDataShow.recordList"
        >
          <el-descriptions-item
            :label="`第${item.recordTimes}次跟进时间`"
            :span="1"
            >{{ item.createTime }}</el-descriptions-item
          >
          <el-descriptions-item
            :label="`第${item.recordTimes}次跟进话术`"
            :span="2"
            >{{
              item.recordScript
                ? item.recordScript == "1"
                  ? "扶持"
                  : "活动"
                : "-"
            }}</el-descriptions-item
          >
          <el-descriptions-item
            :label="`第${item.recordTimes}次跟进记录`"
            :span="3"
            >{{ item.recordInfo }}</el-descriptions-item
          >
        </el-descriptions>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="跟进次数" prop="salesLeadsType">
          第{{ formDataShow ? formDataShow.nextNum : 1 }}次跟进
        </el-form-item>
        <el-form-item label="跟进详情" prop="recordInfo">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="form.recordInfo"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="跟进话术" prop="recordScript">
          <el-select
            v-model="form.recordScript"
            placeholder="选择类别"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="item in formList.recordScriptList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="继续跟进" prop="continueFlag">
          <el-select
            v-model="form.continueFlag"
            placeholder="选择类别"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="item in formList.continueFlagList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="合作状态"
          prop="intendedCooperation"
          v-if="form.continueFlag == 2"
          class="content-one"
        >
          <el-select
            v-model="form.intendedCooperation"
            placeholder="选择类别"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="item in formList.intendedCooperationList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input placeholder="请输入内容" v-model="form.remarks"> </el-input>
        </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="500px"
      append-to-body
    >
      <el-form label-width="80px" size="mini">
        <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 {
  getSaleAllocationList,
  saleClueDistribution,
  getIndustryInfoList,
  getUserByRoleName,
  getTaskNumber,
  getSaleClueTaskList,
  getSaleTaskInfoBySellerId,
  addInsertSaleTaskRecord,
  saleClueToOffline,
} from "@/api/sales/sale";
export default {
  name: "sale-html",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      typeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 分配销售
      openAllocation: false,
      // 选择的销售id
      saleId: undefined,
      // 销售列表
      saleList: [],
      // 分配销售确定loading
      confirmLoadingSale: false,
      // 汇总数据获取
      taskNumber: {
        complete: 0,
        noStarted: 0,
      },
      userId: undefined,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sellerName: undefined,
        state: null,
      },
      //查询参数所用下拉数据
      queryParamsList: {
        stateList: [
          { value: null, label: "全部" },
          { value: 1, label: "未开始" },
          { value: 2, label: "进行中" },
          { value: 3, label: "已结束" },
        ], //粉丝量级
      },
      // 销售线索回显
      formDataShow: null,
      // 表单参数
      form: {},
      //上传报表下拉数据
      formList: {
        recordScriptList: [
          { value: 1, label: "扶持" },
          { value: 2, label: "活动" },
        ], //跟进话术
        continueFlagList: [
          { value: 1, label: "继续跟进" },
          { value: 2, label: "意向合作" },
          { value: 3, label: "跟进完成无合作" },
        ], //是否继续跟进
        intendedCooperationList: [
          { value: 1, label: "不合作可跟进" },
          { value: 2, label: "添加微信" },
          { value: 3, label: "操盘合作" },
          { value: 4, label: "服务商合作" },
          { value: 5, label: "金牛合作" },
          { value: 6, label: "无法添加微信" },
        ], // 意向合作
      },
      fileList: [],
      //获取销售线索文件流
      dateFile: null,
      //销售线索上传loading
      confirmLoading: false,
      // 表单校验
      rules: {
        recordInfo: [
          { required: true, message: "跟进详情不能为空", trigger: "blur" },
          {
            min: 2,
            max: 500,
            message: "跟进详情最多500个字，最少2个字",
            trigger: "blur",
          },
        ],
        recordScript: [
          { required: false, message: "跟进详情不能为空", trigger: "blur" },
        ],
        continueFlag: [
          { required: true, message: "是否继续跟进必选", trigger: "change" },
        ],
        remarks: [
          {
            min: 2,
            max: 500,
            message: "备注最多500个字，最少2个字",
            trigger: "change",
          },
        ],
      },
      // 分配销售展示列表
      saleAllocationList: [],
    };
  },
  filters: {
    continueFlagText(status) {
      const statusMap = {
        1: "继续跟进",
        2: "意向合作",
        3: "跟进完成无合作",
      };
      return statusMap[status];
    },
    intendedCooperationText(status) {
      const statusMap = {
        1: "不合作可跟进",
        2: "添加微信",
        3: "操盘合作",
        4: "服务商合作",
        5: "金牛合作",
        6: "无法添加微信",
      };
      return statusMap[status];
    },
  },
  created() {
    this.userId = this.$store.getters.userId;
    this.getList();
    this.getIndustryInfoList();
    this.getTaskNumber();
  },
  methods: {
    /** 更多操作 */
    handleEdit(item, id) {
      this.ids = id.sellerId;
      if (item == "editSale") {
        this.getAllocationList();
      } else {
        this.$confirm("是否确认该线索转给面销?", "提示", {
          confirmButtonText: "是",
          cancelButtonText: "否",
          type: "warning",
        })
          .then(() => {
            this.getAllocationList();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消",
            });
          });
      }
    },
    /** 获取行业列表 */
    getIndustryInfoList() {
      getIndustryInfoList()
        .then((res) => {
          this.queryParamsList.industryList = res.data.map((item) => {
            return {
              label: item.name,
              value: item.id,
            };
          });
        })
        .catch((err) => {});
    },
    /** 获取top汇总数据 */
    getTaskNumber() {
      getTaskNumber({ userId: this.userId })
        .then((res) => {
          this.taskNumber.complete = res.data.complete;
          this.taskNumber.noStarted = res.data.noStarted;
        })
        .catch((error) => {
          this.taskNumber = { complete: 0, noStarted: 0 };
        });
    },

    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;
      getSaleClueTaskList({ ...this.queryParams, userId: this.userId }).then(
        (response) => {
          console.log(response.data.rows);
          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.queryParams.uploadDate = undefined;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "上传报表";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.sellerId);
    },
    /** 单条销售线索分配列表 */
    handleAllocationOne(item) {
      this.getAllocationList(item.sellerId);
    },
    /** 多销售线索分配列表 */
    handleAllocation() {
      this.getAllocationList(null);
    },
    /** 获取分配销售列表 */
    getAllocationList(sellerIds) {
      this.openAllocation = true;
      this.title = "转销售";
      getUserByRoleName({ roleName: "electricPin,facePin" })
        .then((res) => {
          this.saleList = res.data.map((item) => {
            return {
              value: item.user_id,
              label: item.nick_name,
            };
          });
        })
        .catch((error) => {});
    },
    // 销售列表删除
    removeListOne(index) {
      this.saleAllocationList.splice(index, 1);
    },
    // 分配销售确定
    submitSale() {
      if (!this.saleId) {
        this.$message.error("请选择销售");
      } else {
        this.confirmLoadingSale = true;
        saleClueDistribution({
          sellerIds: this.ids,
          saleId: this.saleId,
          createUserId: this.userId,
        })
          .then((res) => {
            this.openAllocation = false;
            this.confirmLoadingSale = false;
            this.saleId = undefined;
            this.handleQuery();
          })
          .catch((err) => {
            this.confirmLoadingSale = false;
          });
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.open = true;
      this.title = "跟进填写";
      getSaleTaskInfoBySellerId({ sellerId: row.sellerId })
        .then((res) => {
          this.formDataShow = res.data;
        })
        .catch((error) => {});
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          let formData = {};
          formData.continueFlag = this.form.continueFlag;
          formData.createUserId = this.userId;
          formData.intendedCooperation =
            this.form.continueFlag == 2
              ? !this.form.intendedCooperation
                ? null
                : this.form.intendedCooperation
              : null;
          formData.recordInfo = this.form.recordInfo;
          formData.recordScript = !this.form.recordScript
            ? null
            : this.form.recordScript;
          formData.remarks = this.form.remarks;
          formData.sellerId = this.formDataShow.saleRecordVo.sellerId;
          formData.recordTimes = this.formDataShow.nextNum;
          addInsertSaleTaskRecord(formData)
            .then((res) => {
              this.confirmLoading = false;
              this.$message.success("添加跟进成功");
              this.cancel();
              this.handleQuery();
            })
            .catch((err) => {
              this.confirmLoading = false;
            });
        }
      });
    },
    /** 删除按钮操作 */
    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>

<style scoped lang="scss">
.top-sum {
  margin-bottom: 15px;
  ::v-deep .card-show {
    text-align: center;
    .p-title {
      width: 100%;
      font-size: 10px;
      color: darkgray;
      font-weight: bold;
    }
    .p-main {
      width: 100%;
      font-size: 20px;
      font-weight: bold;
    }
  }
}
::v-deep .el-form-item__label {
  white-space: nowrap;
}
</style>
