<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="bdUserId">
        <el-select
          filterable
          v-model="queryParams.bdUserId"
          placeholder="人员名称"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in queryParamsList.personList"
            :key="item.userId"
            :label="item.nickMame"
            :value="item.userId"
          >
            <div style="display: flex">
              <span
                style="
                  width: 10px;
                  height: 10px;
                  border-radius: 50%;
                  background-color: green;
                  position: relative;
                  top: 12px;
                  margin-right: 5px;
                "
                :style="
                  item.status == '0' ? 'backgroundColor:green' : 'backgroundColor:red'
                "
              >{{ item.value }}</span
              ><span>{{ item.nickMame }}</span>
            </div>
          </el-option>
        </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 label="认领状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="选择认领状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in queryParamsList.statusList"
            :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"
      ref="multipleTable"
      @sort-change="sortChange"
    >
      <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="fansNumber"></el-table-column>

      <el-table-column
        label="单视频销售额"
        align="center"
        prop="avgVideoSales"
        sortable="custom"
      >
        <template slot-scope="scope">
          <div v-if="!!scope.row.avgVideoSales">
            {{ scope.row.avgVideoSales }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column
        label="短视频销售额"
        align="center"
        prop="videoSales"
        sortable="custom"
      >
        <template slot-scope="scope">
          <div v-if="!!scope.row.videoSales">
            {{ scope.row.videoSales }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column
        label="睿选近30天GMV"
        align="center"
        prop="monthDayGmv"
        sortable="custom"
      >
        <template slot-scope="scope">
          <div v-if="!!scope.row.monthDayGmv">
            {{ allMoney(scope.row.monthDayGmv / 100) }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column
        label="睿选近30天出单量"
        align="center"
        prop="monthDayOrderNum"
        sortable="custom"
      >
        <template slot-scope="scope">
          <div v-if="!!scope.row.monthDayOrderNum">
            {{ scope.row.monthDayOrderNum }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>

      <el-table-column
        label="睿选总销售额"
        align="center"
        prop="validAmount"
        sortable="custom"
      >
        <template slot-scope="scope">
          <div v-if="!!scope.row.validAmount">
            {{ allMoney(scope.row.validAmount / 100) }}
          </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" prop="userName"></el-table-column>
      <el-table-column label="操作" align="center" prop="action">
        <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="updateOneData(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=" 认领"
      :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="达人昵称"
            prop="promoterId"
            style="width: 100%"
            class="entire-line"
          >
            {{ formBroadcast.promoterNickName }}
          </el-form-item>
          <el-form-item
            label="快手ID"
            prop="promoterId"
            style="width: 100%"
            class="entire-line"
          >
            {{ formBroadcast.promoterId }}
          </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 {getSupplyChainUserList} from "@/api/supplyChain/supplyChain";
  import {
    getPromoterList2,
    addPromoter,
    editPromoter,
    deleteById,
    getGongHaiVideoSales,
  } from "@/api/promoter/promoter";

  export default {
    name: "account-list",
    components: {},

    data() {
      let validatePhone = (rule, value, callback) => {
        /*console.log(rule);
          console.log(value);
          console.log(callback);*/
        if (!value) {
          callback(new Error("联系方式不能为空！"));
        }
        //使用正则表达式进行验证手机号码
        if (!/^1[3456789]\d{9}$/.test(value)) {
          callback(new Error("手机号不正确！"));
        }
        callback();
      };
      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: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          promoterNickName: undefined,
          promoterId: undefined,
          status: undefined,
        },
        //页面所有的下拉数据
        queryParamsList: {
          statusList: [
            {value: 1, label: "已认领"},
            {value: 2, label: "未认领"},
          ],
        },
        // 表单参数
        form: {},
        formBroadcast: {},
        //上传报表下拉数据
        formList: {},
        fileList: [],
        accept: "",
        //获取销售线索文件流
        dateFile: new FormData(),
        //销售线索上传loading
        confirmLoading: false,
        // 表单校验
        rules: {},
        rulesBroadcast: {
          consignee: {
            required: true,
            message: "收货人必填",
            trigger: "blur",
          },
          phone: {
            required: true,
            // message: "联系方式必填",
            validator: validatePhone,
            trigger: "blur",
          },
          promoterAddress: [
            {
              required: true,
              message: "发货地址必填",
              trigger: "blur",
            },
            {
              min: 5,
              max: 200,
              message: "发货地址最少输入5个字符",
              trigger: "change",
            },
          ],
        },
        // 分配销售展示列表
        ksInfo: null,
        userId: null,
        prop: "",
        sort: "DESC",
        personList: [],
      };
    },
    created() {
      this.userId = this.$store.getters.userId;
      this.getList();
      this.getPersonList();
    },
    filters: {},
    methods: {
      getPersonList() {
        getSupplyChainUserList().then((response) => {
          this.queryParamsList.personList = response.rows;
        });
      },
      toIndexDetail(item) {
        this.$router.replace({
          path: "/promoter/detail",
          query: {
            id: item.id,
          },
        });
      },
      sortChange(col, prop, order) {
        this.prop = col.prop;

        this.sort = !!col.order ? (col.order == "descending" ? "DESC" : "ASC") : "DESC";
        this.handleQuery();
      },
      /** 查询字典类型列表 */
      getList() {
        this.loading = true;

        getPromoterList2({
          userId: this.userId,
          ...this.queryParams,
          parameter: this.prop,
          orderBy: this.sort,
        }).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");
        this.handleQuery();
      },
      addNew() {
        this.openAllocation = true;
        this.edit = false;
        this.ids = null;
        this.confirmLoading = false;
        this.formBroadcast = {};
        setTimeout(() => {
          this.$refs.formBroadcast.clearValidate();
        }, 0);
      },
      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.loading = false;
              });
          })
          .catch(() => {
          });
      },
      updateOneData(item) {
        getGongHaiVideoSales({promoterId: item.promoterId}).then((res) => {
          this.$modal.msgSuccess("更新成功");
          this.getList();
        });
      },
      /** 编辑地址 新增达人*/
      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 = {
              mediaId: 2,
              userId: this.userId,
              userName: this.$store.getters.name,
              ...this.formBroadcast,
            };

            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;
              });
          }
        });
      },
      /** 提交按钮 */
      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;
    text-align: left;
  }

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

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