<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
      :rules="rules"
    >
      <el-form-item label="商品名称" prop="itemTitle">
        <el-input
          placeholder="请输入商品名称"
          style="width: 240px"
          v-model="queryParams.itemTitle"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="商品ID" prop="itemId">
        <el-input
          placeholder="请输入商品ID"
          style="width: 240px"
          v-model="queryParams.itemId"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="达人名称" prop="promoterNickName">
        <el-input
          placeholder="请输入达人名称"
          style="width: 240px"
          v-model="queryParams.promoterNickName"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="达人ID" prop="promoterId">
        <el-input
          placeholder="请输入达人ID"
          style="width: 240px"
          v-model="queryParams.promoterId"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="单价起始价" prop="reservePriceStart">
        <el-input
          placeholder="请输入单价起始价"
          style="width: 240px"
          v-model="queryParams.reservePriceStart"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="单价结束价" prop="reservePriceEnd">
        <el-input
          placeholder="请输入单价结束价"
          style="width: 240px"
          v-model="queryParams.reservePriceEnd"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="有效订单起始数" prop="validorderStart">
        <el-input
          placeholder="请输入有效订单起始数"
          style="width: 240px"
          v-model.number="queryParams.validorderStart"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="有效订单结束数" prop="validorderEnd">
        <el-input
          placeholder="请输入有效订单结束数"
          style="width: 240px"
          v-model.number="queryParams.validorderEnd"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="时间筛选" prop="uploadDate">
        <el-date-picker
          v-model="uploadDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        ></el-date-picker>
      </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-button
          type="primary"
          plain
          size="mini"
          @click="addNew"
          style="margin-bottom: 15px"
          :loading="downLoading"
          >导出</el-button
        >
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="typeList" ref="multipleTable">
      <el-table-column
        label="达人名称"
        align="center"
        prop="promoterNickName"
        width="300"
      >
        <template slot-scope="scope">
          <div
            class="item-name-calss"
            style="display: flex; width: 100%; justify-content: center"
          >
            <a :title="scope.row.promoterNickName">
              {{ scope.row.promoterNickName }}
            </a>
            <p>({{ scope.row.promoterId }})</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="fansNumber" width="300">
        <template slot-scope="scope">
          <div class="item-name-calss">
            <a
              :title="scope.row.itemTitle"
              style="
                text-overflow: ellipsis;
                white-space: nowrap;
                overflow: hidden;
                width: 100%;
              "
            >
              {{ scope.row.itemTitle }}
            </a>
            <p>({{ scope.row.itemId }})</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品单价" align="center" prop="reservePrice">
        <template slot-scope="scope">
          <div v-if="!!scope.row.reservePrice">
            {{ allMoney(scope.row.reservePrice / 100) }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="销售额" align="center" prop="orderAmount">
        <template slot-scope="scope">
          <div v-if="!!scope.row.orderAmount">
            {{ allMoney(scope.row.orderAmount / 100) }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="有效订单" align="center" prop="validorder">
        <template slot-scope="scope">
          <div v-if="!!scope.row.validorder">
            {{ scope.row.validorder }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="预估服务费" align="center" prop="regimentalPromotionAmount">
        <template slot-scope="scope">
          <div v-if="!!scope.row.regimentalPromotionAmount">
            {{ allMoney(scope.row.regimentalPromotionAmount / 100) }}
          </div>
          <div v-else>-</div>
        </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 { refreshCache } from "@/api/system/dict/type";
import {
  getPromoterList,
  addPromoter,
  editPromoter,
  deleteById,
} from "@/api/promoter/promoter";
import { getQueryProductListl, downFilePost } from "@/api/supplyChain/supplyChain";
export default {
  name: "account-list",
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: null,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      typeList: [],
      //上传文件类型
      fileType: [".doc", ".xls", ".xlsx", ".ppt", ".pdf", ".csv"],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openFp: false,
      formFp: {},
      // 是否可编辑
      edit: false,
      // 分配销售
      openAllocation: false,
      // 选择的销售id
      saleId: undefined,
      // 销售列表
      saleList: [],
      // 分配销售确定loading
      confirmLoadingSale: false,
      // 日期范围
      dateRange: [],
      downLoading: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        promoterNickName: undefined,
        promoterId: undefined,
        itemTitle: undefined,
        itemId: undefined,
        reservePriceEnd: undefined,
        reservePriceStart: undefined,
        validorderStart: undefined,
        validorderEnd: undefined,
      },
      uploadDate: [new Date(), new Date()],
      //页面所有的下拉数据
      queryParamsList: {},
      // 表单参数
      form: {},
      formBroadcast: {},
      //上传报表下拉数据
      formList: {},
      fileList: [],
      accept: "",
      //获取销售线索文件流
      dateFile: new FormData(),
      //销售线索上传loading
      confirmLoading: false,
      // 表单校验
      rules: {
        reservePriceEnd: {
          type: "number",
          message: "商品单价结束价只能输入数字",
          trigger: "change",
          transform(value) {
            return +value;
          },
        },
        reservePriceStart: {
          type: "number",
          message: "商品单价起始价只能输入数字",
          trigger: "change",
          transform(value) {
            return +value;
          },
        },
      },
      rulesBroadcast: {},
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              end.setTime(end.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              end.setTime(end.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              end.setTime(end.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              end.setTime(end.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      // 分配销售展示列表
      ksInfo: null,
      userId: null,
    };
  },
  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;
    let dd = date.getDate();
    dd = dd < 10 ? "0" + dd : dd;
    this.uploadDate = [`${y}-${MM}-${dd}`, `${y}-${MM}-${dd}`];
    this.getList();
  },
  filters: {},
  methods: {
    toIndexDetail(item) {
      this.$router.replace({
        path: "/promoter/detail",
        query: {
          id: item.id,
        },
      });
    },
    /** 查询字典类型列表 */
    getList() {
      this.loading = true;

      getQueryProductListl(
        this.addDateRange(
          {
            userId: this.userId,
            ...this.queryParams,
            reservePriceStart: this.queryParams.reservePriceStart
              ? this.queryParams.reservePriceStart * 100
              : null,
            reservePriceEnd: this.queryParams.reservePriceEnd
              ? this.queryParams.reservePriceEnd * 100
              : null,
          },
          this.uploadDate,
          "startDate",
          "endDate"
        )
      ).then((response) => {
        this.typeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.confirmLoading = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.dateFile = null;
      this.resetForm("formBroadcast");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      let date = new Date();
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let dd = date.getDate();
      dd = dd < 10 ? "0" + dd : dd;
      this.uploadDate = [`${y}-${MM}-${dd}`, `${y}-${MM}-${dd}`];
      this.handleQuery();
    },
    addNew() {
      this.downLoading = true;
      downFilePost(
        "/itemCollectSamples/exportProductList",
        this.addDateRange(
          {
            userId: this.userId,
            reservePriceStart: this.queryParams.reservePriceStart
              ? this.queryParams.reservePriceStart * 100
              : null,
            reservePriceEnd: this.queryParams.reservePriceEnd
              ? this.queryParams.reservePriceEnd * 100
              : null,
            promoterNickName: this.queryParams.promoterNickName,
            promoterId: this.queryParams.promoterId,
            itemTitle: this.queryParams.itemTitle,
            itemId: this.queryParams.itemId,
            validorderStart: this.queryParams.validorderStart,
            validorderEnd: this.queryParams.validorderEnd,
          },
          this.uploadDate,
          "startDate",
          "endDate"
        )
      ).then((res) => {
        let blob = new Blob([res], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        let downloadElement = document.createElement("a");
        let href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.href = href;
        downloadElement.download = "激励列表.xlsx"; //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放掉blob对象
        this.downLoading = false;
      });
    },
    handleDelete(item) {
      this.$modal
        .confirm(`请确认是否解绑此达人？`)
        .then(() => {
          var params = {};
          params.id = item.id;
          params.userId = this.$store.getters.userId;
          deleteById(params)
            .then((res) => {
              this.$modal.msgSuccess("解绑成功");
              this.handleQuery();
            })
            .catch(() => {
              this.$message.error("失败");
              this.loading = false;
            });
        })
        .catch(() => {});
    },
    /** 编辑地址 新增达人*/
    handleAddbroadcast(item) {
      this.ids = item.id;
      this.edit = true;
      this.openAllocation = true;
      this.$set(this.formBroadcast, "consignee", item.consignee);
      this.$set(this.formBroadcast, "phone", item.phone);
      this.$set(this.formBroadcast, "promoterAddress", item.promoterAddress);
      this.$set(this.formBroadcast, "promoterNickName", item.promoterNickName);
      this.$set(this.formBroadcast, "promoterId", item.promoterId);
    },
    copyInfomation(item) {
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard
          .writeText(
            `
  收货人: ${item.consignee}
  手机号: ${item.phone}
  收货地址: ${item.promoterAddress}`
          )
          .then(() => {
            this.$message.success("复制成功");
          })
          .catch((err) => {
            this.$message.error("复制失败");
          });
      } else {
        // 创建text area
        const textArea = document.createElement("textarea");
        textArea.value = `
  收货人: ${item.consignee}
  手机号: ${item.phone}
  收货地址: ${item.promoterAddress}`;
        // 使text area不在viewport，同时设置不可见
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        return new Promise((resolve, reject) => {
          // 执行复制命令并移除文本框
          document.execCommand("copy") ? resolve() : reject(new Error("出错了"));
          textArea.remove();
        }).then(
          () => {
            this.$message.success("复制成功");
          },
          () => {
            this.$message.error("复制失败");
          }
        );
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
    },
    /** 新增直播确定按钮 */
    submitFormBroadcast: function () {
      this.$refs["formBroadcast"].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          let formData = {
            userId: this.userId,
            userName: this.$store.getters.name,
            ...this.formBroadcast,
          };

          if (!this.ids) {
            addPromoter(formData)
              .then((res) => {
                this.confirmLoading = false;
                this.$message.success("新增成功");
                this.openAllocation = false;
                this.ids = null;
                this.cancel();
                this.handleQuery();
              })
              .catch((err) => {
                this.confirmLoading = false;
              });
          } else {
            formData.id = this.ids;
            editPromoter(formData)
              .then((res) => {
                this.confirmLoading = false;
                this.$message.success("修改成功");
                this.openAllocation = false;
                this.ids = null;
                this.cancel();
                this.handleQuery();
              })
              .catch((err) => {
                this.confirmLoading = false;
              });
          }
        }
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          var fileList = this.$refs.fileUploadDialog.fileList;
          var dapanUrls = this.$refs.fileUpload.fileList;
          var portraitUrls = this.$refs.fileUploadFx.fileList;
          if (fileList.length == 0 && dapanUrls.length == 0 && portraitUrls.length == 0) {
            this.$message.error("直播数据,数据大盘,画像分析必须最少上传一项");
            return;
          } else {
            this.confirmLoading = true;
            let formData = new FormData();
            this.ids;
            formData.append("id", this.ids);
            formData.append("actualGmv", this.delcommafy(this.form.actualGmv));
            formData.append(
              "dapanUrls",
              JSON.stringify(
                dapanUrls.map((item) => {
                  return item.url;
                })
              )
            );
            formData.append(
              "portraitUrls",
              JSON.stringify(
                portraitUrls.map((item) => {
                  return item.url;
                })
              )
            );
            fileList.forEach((file) => formData.append("files", file.raw));
            dataUpload(formData)
              .then((res) => {
                this.confirmLoading = false;
                this.$message.success("上传成功");
                this.open = false;
                this.ids = null;
                this.cancel();
                this.handleQuery();
              })
              .catch((err) => {
                this.confirmLoading = false;
              });
          }
          console.log(fileList, dapanUrls, portraitUrls);
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.entire-line {
  width: 100%;
  ::v-deep .el-form-item__content {
    width: 60%;
  }
}
::v-deep .el-form-item__label {
  white-space: nowrap;
}
</style>
<style scoped lang="scss">
::v-deep a {
  color: #409eff;
  display: block;
}
.item-name-calss p {
  margin: 0;
  text-align: center;
}
.tableBox {
  width: 100%;
}
</style>
