<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="categoryId">
        <el-select
          filterable
          v-model="queryParams.mediaId"
          placeholder="选择媒体"
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="item in queryParamsList.mediaList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </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="promoterNickName">
        <el-input
          placeholder="请输入达人名称"
          style="width: 240px"
          v-model="queryParams.promoterNickName"
        >
        </el-input>
      </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="toIndexDetail"
          >设置领样数量
        </el-button>
      </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="typeList"
      ref="multipleTable"
      @selection-change="handleSelectionChange"
      :row-key="getRowKeys"
    >
      <el-table-column
        type="selection"
        width="50"
        :reserve-selection="true"
        align="center"
      />
      <el-table-column
        label="达人名称"
        align="center"
        prop="promoterNickName"
        width="300"
      >
        <template slot-scope="scope">
          <div style="display: flex; width: 100%">
            <div style="width: 40%">
              <img
                :src="scope.row.promoterUrl"
                alt=""
                style="width: 70px; height: auto"
              />
            </div>
            <div style="width: 60%" class="item-name-calss">
              <a
                style="
                  text-overflow: ellipsis;
                  white-space: nowrap;
                  overflow: hidden;
                  width: 100%;
                "
                :title="scope.row.promoterNickName"
              >
                {{ scope.row.promoterNickName }}
              </a>
              <p>达人Id： {{ scope.row.promoterId }}</p>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="媒体" align="center" prop="mediaId" width="100px">
        <template slot-scope="scope">
          <div v-if="!!scope.row.mediaId">
            {{ scope.row.mediaId | mediaStatusName }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="粉丝数" align="center" prop="fansNumber"> </el-table-column>
      <el-table-column label="总销售额" align="center" prop="totalSale">
        <template slot-scope="scope">
          <div v-if="!!scope.row.totalSale">
            {{ scope.row.totalSale }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="所属渠道" align="center" prop="userName">
        <template slot-scope="scope">
          <div v-if="!!scope.row.userName">
            {{ scope.row.userName }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="佣金要求" align="center" prop="commissionRequirement">
        <template slot-scope="scope">
          <div v-if="!!scope.row.commissionRequirement">
            {{ scope.row.commissionRequirement }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200px"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAddbroadcast(scope.row)"
            >修改地址</el-button
          >
          <el-button size="mini" type="text" @click="copyInfomation(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"
      :pageSizes="[10, 20, 30, 50]"
    />

    <!-- 添加直播 -->
    <el-dialog
      :title="!!ids ? '修改地址' : '新增达人'"
      :visible.sync="openAllocation"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="formBroadcast"
        :model="formBroadcast"
        :rules="rulesBroadcast"
        label-width="100px"
        :inline="true"
      >
        <div v-if="!ids">
          <el-form-item label="创建人" prop="userName" style="width: 100%">
            {{ $store.getters.name }}
          </el-form-item>
          <el-form-item
            label="快手ID"
            prop="promoterId"
            style="width: 100%"
            class="entire-line"
          >
            <el-input
              placeholder="请输入快手ID"
              style="width: 240px"
              v-model="formBroadcast.promoterId"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="佣金要求"
            prop="commissionRequirement"
            style="width: 100%"
            class="entire-line"
          >
            <el-input
              placeholder="请输入佣金要求"
              style="width: 240px"
              v-model="formBroadcast.commissionRequirement"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="品类要求"
            prop="categoryRequirement"
            style="width: 100%"
            class="entire-line"
          >
            <el-input
              placeholder="请输入品类要求"
              style="width: 240px"
              v-model="formBroadcast.categoryRequirement"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="收货人"
            prop="consignee"
            style="width: 100%"
            class="entire-line"
          >
            <el-input
              placeholder="请输入收货人"
              style="width: 240px"
              v-model="formBroadcast.consignee"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="联系方式"
            prop="phone"
            style="width: 100%"
            class="entire-line"
          >
            <el-input
              placeholder="请输入联系方式"
              style="width: 240px"
              v-model="formBroadcast.phone"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="发货地址"
            prop="promoterAddress"
            style="width: 100%"
            class="entire-line"
          >
            <el-input
              placeholder="请输入发货地址"
              style="width: 100%"
              type="textarea"
              :rows="2"
              v-model="formBroadcast.promoterAddress"
            >
            </el-input>
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item label="达人名称" prop="promoterNickName" style="width: 100%">
            {{ formBroadcast.promoterNickName }}({{ formBroadcast.promoterId }})
          </el-form-item>
          <el-form-item
            label="收货人"
            prop="consignee"
            style="width: 100%"
            class="entire-line"
          >
            <el-input
              placeholder="请输入收货人"
              style="width: 240px"
              v-model="formBroadcast.consignee"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="联系方式"
            prop="phone"
            style="width: 100%"
            class="entire-line"
          >
            <el-input
              placeholder="请输入联系方式"
              style="width: 240px"
              v-model="formBroadcast.phone"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="发货地址"
            prop="promoterAddress"
            style="width: 100%"
            class="entire-line"
          >
            <el-input
              placeholder="请输入发货地址"
              style="width: 100%"
              type="textarea"
              :rows="2"
              v-model="formBroadcast.promoterAddress"
            >
            </el-input>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormBroadcast" :loading="confirmLoading"
          >确 定</el-button
        >
        <el-button
          @click="
            confirmLoading = false;
            openAllocation = false;
            formBroadcast = {};
          "
          >取 消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { refreshCache } from "@/api/system/dict/type";
import { getPromoterList, addPromoter, editPromoter } from "@/api/promoter/promoter";
export default {
  name: "account-list",
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: null,
      okIds: 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: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        promoterNickName: undefined,
        promoterId: undefined,
      },
      //页面所有的下拉数据
      queryParamsList: {
        mediaList: [
          {value: 2, label: "快手"},
          {value: 1, label: "抖音"},
        ],
      },
      // 表单参数
      form: {},
      formBroadcast: {},
      //上传报表下拉数据
      formList: {},
      fileList: [],
      accept: "",
      //获取销售线索文件流
      dateFile: new FormData(),
      //销售线索上传loading
      confirmLoading: false,
      // 表单校验
      rules: {},
      rulesBroadcast: {
        promoterId: {
          required: true,
          message: "快手ID必填",
          trigger: "blur",
        },
        consignee: {
          required: true,
          message: "收货人必填",
          trigger: "blur",
        },
        phone: {
          required: true,
          message: "联系方式必填",
          trigger: "blur",
        },
        promoterAddress: [
          {
            required: true,
            message: "发货地址必填",
            trigger: "blur",
          },
          {
            min: 5,
            max: 200,
            message: "发货地址最少输入5个字符",
            trigger: "change",
          },
        ],
      },
      // 分配销售展示列表
      ksInfo: null,
      userId: null,
    };
  },
  created() {
    this.userId = this.$store.getters.userId;
    this.getList();
  },
  filters: {
    mediaStatusName(status) {
      const statusMap = {
        1: "抖音",
        2: "快手",
      };
      return statusMap[status];
    },
  },
  methods: {
    getRowKeys(row) {
      return row.id;
    },
    handleSelectionChange(selection) {
      this.okIds = selection.map((item) => item.id);
    },
    toIndexDetail(item) {
      var that = this;
      if (!!this.okIds && this.okIds.length > 0) {
        this.$router.replace({
          path: "/goodsManagement/set",
          query: {
            promoterIds: JSON.stringify(this.okIds),
            itemIds: that.$route.query.itemIds,
          },
        });
      } else {
        this.$message.error("请选择达人");
      }
    },
    /** 查询字典类型列表 */
    getList() {
      this.loading = true;
      this.typeList = [];
      getPromoterList({ userId: this.userId, ...this.queryParams })
        .then((response) => {
          this.loading = false;
          this.typeList = response.rows;
          this.total = response.total;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 取消按钮
    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.queryParams.mediaId = undefined;
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    addNew() {
      this.openAllocation = true;
      this.edit = false;
      this.ids = null;
      this.confirmLoading = false;
      this.formBroadcast = {};
      setTimeout(() => {
        this.$refs.formBroadcast.clearValidate();
      }, 0);
    },
    /** 编辑地址 新增达人*/
    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();
            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 .entire-line .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;
  text-align: left;
}

.item-name-calss p {
  margin: 0;
  text-align: left;
}

.tableBox {
  width: 100%;
}
</style>
