<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="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>
        <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="addNew"
          >领样申请</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="typeList"
      ref="multipleTable"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        label="商品名称"
        align="center"
        prop="itemTitle"
        width="300"
      >
        <template slot-scope="scope">
          <div style="display: flex; width: 100%">
            <div style="width: 40%">
              <img
                :src="scope.row.itemImgUrl"
                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.itemTitle"
              >
                {{ scope.row.itemTitle }}
              </a>
              <p>商品Id： {{ scope.row.itemId }}</p>
              <p>商品单价： {{ scope.row.itemPrice / 100 }}元</p>

              <p>
                佣金率：
                {{
                  scope.row.commissionRate
                    ? scope.row.commissionRate / 10 + "%"
                    : "-"
                }}
              </p>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="预估服务费"
        align="center"
        prop="regimentalPromotion"
      >
      </el-table-column>
      <el-table-column
        label="平台领样要求"
        align="center"
        prop="sampleRequirement"
      >
        <template slot-scope="scope">
          <div v-if="!!scope.row.sampleRequirement">
            {{ scope.row.sampleRequirement }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="样品数量" align="center" prop="sampleCount">
        <template slot-scope="scope">
          <div v-if="!!scope.row.sampleCount">
            {{ scope.row.sampleCount }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="领样人数" align="center" prop="remark">
        <template slot-scope="scope">
          <div v-if="!!scope.row.remark">
            {{ scope.row.remark }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="领样份数" align="center" prop="remark">
        <template slot-scope="scope">
          <div v-if="!!scope.row.remark">
            {{ scope.row.remark }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="activityItemStatus">
        <template slot-scope="scope">
          <div v-if="!!scope.row.activityItemStatus">
            {{ scope.row.activityItemStatus | activityItemStatusName }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <div v-if="!!scope.row.createTime">
            {{ scope.row.createTime.split(" ")[0] }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column
        label="手卡信息"
        align="center"
        prop="partnerRecommendText"
      >
        <template slot-scope="scope">
          <div v-if="!!scope.row.partnerRecommendText">
            {{ scope.row.partnerRecommendText }}
          </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"
        class-name="small-padding fixed-width"
        width="200px"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="okInfomation(scope.row)"
            >领样申请</el-button
          >
          <el-button size="mini" type="text" @click="copyInfomation(scope.row)"
            >商品复制</el-button
          >

          <el-button size="mini" type="text" @click="toDetail(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="!!ids ? '修改商品' : '新增商品'"
      :visible.sync="openAllocation"
      width="800px"
      append-to-body
    >
      <el-form
        ref="formBroadcast"
        :model="formBroadcast"
        :rules="rulesBroadcast"
        label-width="100px"
        :inline="true"
      >
        <el-form-item label="创建人" prop="userName" style="width: 100%">
          {{ $store.getters.name }}
        </el-form-item>
        <el-form-item label="活动ID" prop="activityId">
          <el-input
            placeholder="请输入活动ID"
            style="width: 240px"
            v-model="formBroadcast.activityId"
            :disabled="edit"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="商品ID" prop="itemId">
          <el-input
            placeholder="请输入商品ID"
            style="width: 240px"
            v-model="formBroadcast.itemId"
            :disabled="edit"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="发货地" prop="postArea">
          <selectTree
            :disabled="edit"
            style="width: 240px"
            v-model="formBroadcast.postArea"
            filterable
            :data="superiorList"
            :props="{
              value: 'id',
              label: 'name',
            }"
          />
        </el-form-item>
        <el-form-item label="不发货地区" prop="noPostArea">
          <selectTree
            style="width: 240px"
            v-model="formBroadcast.noPostArea"
            filterable
            :multiple="true"
            :data="superiorList"
            :props="{
              value: 'id',
              label: 'name',
            }"
          />
        </el-form-item>
        <el-form-item label="佣金比例" prop="commissionRate">
          <el-input
            placeholder="请输入佣金比例"
            style="width: 240px"
            v-model="formBroadcast.commissionRate"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="服务费" prop="regimentalPromotion">
          <el-input
            placeholder="请输入服务费"
            style="width: 240px"
            v-model="formBroadcast.regimentalPromotion"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="服务费率" prop="regimentalPromotionRate">
          <el-input
            placeholder="请输入服务费率"
            style="width: 240px"
            v-model="formBroadcast.regimentalPromotionRate"
          >
          </el-input>
        </el-form-item>

        <el-form-item label="领样要求" prop="sampleRequirement">
          <el-input
            placeholder="请输入领样要求"
            style="width: 240px"
            v-model="formBroadcast.sampleRequirement"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="样品数量" prop="sampleCount">
          <el-input
            placeholder="请输入样品数量"
            style="width: 240px"
            v-model="formBroadcast.sampleCount"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="商品链接" prop="detailUrl">
          <el-input
            placeholder="请输入商品链接"
            style="width: 240px"
            v-model="formBroadcast.detailUrl"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="发货率" prop="deliveryRate">
          <el-input
            placeholder="请输入发货率"
            style="width: 240px"
            v-model="formBroadcast.deliveryRate"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="手卡内容"
          prop="partnerRecommendText"
          style="width: 100%"
          class="entire-line"
        >
          <el-input
            placeholder="请输入手卡内容"
            style="width: 100%"
            type="textarea"
            :rows="2"
            v-model="formBroadcast.partnerRecommendText"
          >
          </el-input>
        </el-form-item>
      </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>

    <!-- 审核拒绝 -->
    <el-dialog
      title="拒绝原因"
      :visible.sync="refuseVisible"
      width="500px"
      append-to-body
    >
      <el-input
        placeholder="请输入拒绝原因"
        style="width: 100%"
        type="textarea"
        :rows="2"
        v-model="refuseInfo"
      >
      </el-input>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRefuse" :loading="refuseLoading"
          >确 定</el-button
        >
        <el-button
          @click="
            refuseLoading = false;
            refuseVisible = false;
            refuseInfo = null;
          "
          >取 消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { refreshCache } from "@/api/system/dict/type";
import {
  getItemList,
  getAreaList,
  getCity,
  checkItem,
  editItem,
} from "@/api/goodsManagement/goods";
import selectTree from "./selectTree.vue";
export default {
  name: "account-list",
  components: {
    selectTree,
  },
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (!!value && !this.edit) {
        checkItem({ itemId: value }).then((res) => {
          if (res.message == "true") {
            callback();
          } else {
            callback(new Error(res.message));
          }
        });
      } else {
        callback();
      }
    };
    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: [],
      superiorList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemTitle: undefined,
        itemId: undefined,
        examineStatus: "2",
      },
      //页面所有的下拉数据
      queryParamsList: {
        tagList: [
          { value: "2", label: "我的商品" },
          { value: "1", label: "待审核" },
          { value: "3", label: "审核拒绝" },
        ],
      },
      // 表单参数
      form: {},
      formBroadcast: {},
      //上传报表下拉数据
      formList: {},
      fileList: [],
      accept: "",
      //获取销售线索文件流
      dateFile: new FormData(),
      //销售线索上传loading
      confirmLoading: false,
      // 表单校验
      rules: {},
      rulesBroadcast: {
        itemId: [
          {
            required: true,
            message: "商品ID必填",
            trigger: "blur",
          },
          { required: true, validator: equalToPassword, trigger: "blur" },
        ],
        activityId: {
          required: true,
          message: "活动ID必填",
          trigger: "blur",
        },
        postArea: {
          required: true,
          message: "发货地必选",
          trigger: "change",
        },
        noPostArea: {
          required: true,
          message: "不发货地必选",
          trigger: "change",
        },
        commissionRate: {
          required: true,
          message: "佣金比例必填",
          trigger: "blur",
        },
        regimentalPromotion: {
          required: true,
          message: "服务费必填",
          trigger: "blur",
        },
        regimentalPromotionRate: {
          required: true,
          message: "服务费率必填",
          trigger: "blur",
        },
        sampleRequirement: {
          required: true,
          message: "领样要求必填",
          trigger: "blur",
        },
        sampleCount: {
          required: true,
          message: "样品数量必填",
          trigger: "blur",
        },
        partnerRecommendText: [
          {
            required: true,
            message: "手卡内容必填",
            trigger: "blur",
          },
          {
            min: 5,
            max: 200,
            message: "手卡内容最少输入5个字符",
            trigger: "change",
          },
        ],
      },
      // 分配销售展示列表
      ksInfo: null,
      userId: null,
      refuseVisible: false,
      refuseLoading: false,
      refuseInfo: null,
      itemId: null,
    };
  },
  created() {
    this.userId = this.$store.getters.userId;
    this.getList();
  },
  filters: {
    activityItemStatusName(status) {
      const statusMap = {
        1: "待审核",
        2: "审核通过",
        3: "审核失败（拒绝）",
        5: "失效",
      };
      return statusMap[status];
    },
  },
  methods: {
    handleSelectionChange(selection) {
      this.okIds = selection.map((item) => item.itemId);
    },
    okInfomation(item) {
      this.$router.replace({
        path: "/goodsManagement/promoterSelect",
        query: {
          itemIds: JSON.stringify([item.itemId]),
        },
      });
    },
    toDetail(item) {
      localStorage.setItem(
        "addItemInfo",
        JSON.stringify({ ...item, type: "look" })
      );
      this.$router.replace({
        path: "/goodsManagement/goodsPreview",
      });
    },
    copyInfomation(item) {
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard
          .writeText(
            `
店铺: ${item.shopTitle}
商品体验: ${item.shopScore}
商家服务: ${item.mallServiceScore}
产品: ${item.itemTitle}
直播价: ¥${item.zkFinalPrice / 100}
佣金比例: ${item.commissionRate}%
团长推荐: ${item.partnerRecommendText}
链接: ${item.detailUrl}`
          )
          .then(() => {
            this.$message.success("复制成功");
          })
          .catch((err) => {
            this.$message.error("复制失败");
          });
      } else {
        // 创建text area
        const textArea = document.createElement("textarea");
        textArea.value = `
店铺: ${item.shopTitle}
商品体验: ${item.shopScore}
商家服务: ${item.mallServiceScore}
产品: ${item.itemTitle}
直播价: ¥${item.zkFinalPrice / 100}
佣金比例: ${item.commissionRate}%
团长推荐: ${item.partnerRecommendText}
链接: ${item.detailUrl}`;
        // 使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("复制失败");
          }
        );
      }
    },
    submitRefuse() {
      if (!!this.refuseInfo) {
        var params = {};
        params.itemId = this.itemId;
        params.examineStatus = 3;
        params.refuseDetail = this.refuseInfo;
        params.examineId = this.$store.getters.userId;
        params.examineName = this.$store.getters.name;
        editItem(params)
          .then((res) => {
            this.refuseVisible = false;
            this.refuseLoading = false;
            this.getList();
            this.$modal.msgSuccess("已拒绝");
          })
          .catch(() => {
            this.$message.error("失败");
          });
      } else {
        this.$message.error("请输入拒绝原因");
      }
    },
    getAreaList() {
      getAreaList().then((res) => {
        this.superiorList = res.map((item) => {
          return {
            id: item,
            name: item,
            disabled: true,
          };
        });
      });
    },
    loadNode(node, resolve) {
      if (node.level === 0) {
        return resolve([{ name: "region" }]);
      }
      if (node.level > 1) return resolve([]);

      console.log(node);
      getCity({ province: node.data.id }).then((res) => {
        const data = res.map((item) => {
          return {
            id: item,
            name: item,
          };
        });
        resolve(data);
      });
      //   setTimeout(() => {
      //     const data = [
      //       {
      //         name: "leaf",
      //         leaf: true,
      //       },
      //       {
      //         name: "zone",
      //       },
      //     ];

      //     resolve(data);
      //   }, 500);
    },
    handleNodeClick(val) {
      console.log(val);
      this.$set(this.formBroadcast, "postArea", val.id);
      this.$set(this.formBroadcast, "postAreaName", val.name);
      if (!val.children || val.children.length == 0) {
        this.$refs.selectReport.blur();
      }
    },
    /** 查询字典类型列表 */
    getList() {
      this.loading = true;

      getItemList({ ...this.queryParams }).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.getAreaList();
      this.openAllocation = true;
      this.edit = false;
      this.ids = null;
      this.confirmLoading = false;
      this.formBroadcast = {};
      setTimeout(() => {
        this.$refs.formBroadcast.clearValidate();
      }, 0);
    },
    /** 编辑地址 新增达人*/
    handleAddbroadcast(item) {
      this.getAreaList();
      this.$nextTick(() => {
        this.ids = item.itemId;
        this.edit = true;
        this.openAllocation = true;
        this.$set(this.formBroadcast, "activityId", item.activityId);
        this.$set(this.formBroadcast, "itemId", item.itemId);
        this.$set(this.formBroadcast, "postArea", item.postArea);
        this.$set(this.formBroadcast, "noPostArea", item.noPostArea);
        this.$set(this.formBroadcast, "commissionRate", item.commissionRate);

        this.$set(
          this.formBroadcast,
          "regimentalPromotion",
          item.regimentalPromotion
        );
        this.$set(
          this.formBroadcast,
          "regimentalPromotionRate",
          item.regimentalPromotionRate
        );
        this.$set(
          this.formBroadcast,
          "sampleRequirement",
          item.sampleRequirement
        );
        this.$set(this.formBroadcast, "sampleCount", item.sampleCount);
        this.$set(this.formBroadcast, "detailUrl", item.detailUrl);
        this.$set(this.formBroadcast, "deliveryRate", item.deliveryRate);
        this.$set(
          this.formBroadcast,
          "partnerRecommendText",
          item.partnerRecommendText
        );
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
    },
    /** 新增直播确定按钮 */
    submitFormBroadcast: function () {
      this.$refs["formBroadcast"].validate((valid) => {
        if (valid) {
          if (!this.edit) {
            localStorage.setItem(
              "addItemInfo",
              JSON.stringify(this.formBroadcast)
            );
            this.$router.replace({
              path: "/goodsManagement/goodsPreview",
            });
          } else {
            this.confirmLoading = true;
            var params = { ...this.formBroadcast };
            params.examineStatus = 1;
            editItem(params)
              .then((res) => {
                this.confirmLoading = false;
                this.openAllocation = false;
                this.formBroadcast = {};
                this.getList();
                this.$modal.msgSuccess("修改成功");
              })
              .catch(() => {
                this.confirmLoading = false;
                this.$message.error("失败");
              });
          }
        }
      });
    },
    /** 提交按钮 */
    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%;
}
::v-deep .el-tabs__content {
  overflow: initial;
}
</style>
