<template>
  <div class="app-container">
    <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"
          :loading="loadingAdd"
          >提交领样</el-button
        >
      </el-col>
    </el-row>
    <p>领样已提交数量：{{ sampleReceivedCount }}</p>
    <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="itemId" 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="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="consignee" width="350px">
        <template slot-scope="scope">
          <div style="width: 100%" class="item-name-calss">
            <p style="margin-bottom: 5px">
              收货人：

              <span v-if="!scope.row.consigneeEdit">{{ scope.row.consignee }}</span>
              <el-input
                v-else
                v-model="scope.row.consignee"
                placeholder="请输入内容"
                style="width: 200px"
              ></el-input>
              <a
                :class="!scope.row.consigneeEdit ? 'el-icon-edit' : 'el-icon-check'"
                @click="scope.row.consigneeEdit = !scope.row.consigneeEdit"
                style="color: deepskyblue; margin-left: 10px; display: inline"
              ></a>
            </p>

            <p style="margin-bottom: 5px">
              手机号：

              <span v-if="!scope.row.promoterPhoneEdit">{{
                scope.row.promoterPhone
              }}</span>
              <el-input
                v-else
                v-model.number="scope.row.promoterPhone"
                placeholder="请输入内容"
                style="width: 200px"
              ></el-input>
              <a
                :class="!scope.row.promoterPhoneEdit ? 'el-icon-edit' : 'el-icon-check'"
                @click="scope.row.promoterPhoneEdit = !scope.row.promoterPhoneEdit"
                style="color: deepskyblue; margin-left: 10px; display: inline"
              ></a>
            </p>
            <p style="margin-bottom: 5px">
              地址：

              <span v-if="!scope.row.promoterAddressEdit">{{
                scope.row.promoterAddress
              }}</span>
              <el-input
                v-else
                v-model="scope.row.promoterAddress"
                placeholder="请输入内容"
                style="width: 200px"
              ></el-input>
              <a
                :class="!scope.row.promoterAddressEdit ? 'el-icon-edit' : 'el-icon-check'"
                @click="scope.row.promoterAddressEdit = !scope.row.promoterAddressEdit"
                style="color: deepskyblue; margin-left: 10px; display: inline"
              ></a>
            </p>
          </div>
        </template>
      </el-table-column>

      <!-- <el-table-column label="收货人" align="center" prop="consignee" width="150px">
        <template slot-scope="scope">
          <div>
            <el-input v-model="scope.row.consignee" placeholder="请输入收货人"></el-input>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        label="达人手机号"
        align="center"
        prop="promoterPhone"
        width="150px"
      >
        <template slot-scope="scope">
          <div>
            <el-input
              v-model="scope.row.promoterPhone"
              placeholder="请输入达人手机号"
            ></el-input>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="达人地址"
        align="center"
        prop="promoterAddress"
        width="200px"
      >
        <template slot-scope="scope">
          <div>
            <el-input
              v-model="scope.row.promoterAddress"
              placeholder="请输入达人地址"
            ></el-input>
          </div>
        </template>
      </el-table-column> -->
      <el-table-column label="领样数量" align="center" prop="sampleCount" width="250px">
        <template slot-scope="scope">
          <div>
            <el-input v-model.number="scope.row.sampleCount"></el-input>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="领样备注"
        align="center"
        prop="sampleRequirement"
        width="250px"
      >
        <template slot-scope="scope">
          <div>
            <el-input
              v-model="scope.row.sampleRequirement"
              placeholder="请输入领样备注"
            ></el-input>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="150px"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="copyInfomation(scope.row)"
            >一键同步</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="
              workVisible = true;
              noticeContent = '';
              ids = `${scope.row.itemId + '-' + scope.row.promoterId}`;
            "
            >上传凭证</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
      :close-on-click-modal="false"
    >
      <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"
      :close-on-click-modal="false"
      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>

    <!-- 上传作业 -->
    <el-dialog
      title="上传"
      :visible.sync="workVisible"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
    >
      <!-- <uploadEditor
        v-model="noticeContent"
        style="min-height: 100px"
        v-if="workVisible"
      /> -->

      <uploadCvImageVue ref="fileUpload" :multiple="true" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="workUpload" :loading="workLoading"
          >确 定</el-button
        >
        <el-button
          @click="
            workLoading = false;
            workVisible = false;
            noticeContent = '';
            $refs.fileUpload.fileList = []
          "
          >取 消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { refreshCache } from "@/api/system/dict/type";
import {
  getItemList,
  getAreaList,
  getCity,
  checkItem,
  editItem,
  preview,
  addPreview,
} from "@/api/goodsManagement/goods";
import selectTree from "./selectTree.vue";
import uploadEditor from "./uploadEditor.vue";
import uploadCvImageVue from "./uploadCvImage.vue";
export default {
  name: "account-list",
  components: {
    uploadEditor,
    selectTree,
    uploadCvImageVue,
  },
  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 {
      api: "",
      limit: 2,
      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,

      workVisible: false,
      workLoading: false,
      noticeContent: undefined,
      // 遮罩层
      loading: true,
      loadingAdd: false,
      // 选中数组
      ids: null,
      okIds: null,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      typeList: [],
      sampleReceivedCount: 0,
      //上传文件类型
      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",
        },
        regId: {
          required: true,
          message: "团长信息必填",
          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,
            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: "审核失败（拒绝）",
        4: "活动结束",
        5: "失效",
      };
      return statusMap[status];
    },
  },
  methods: {
    workUpload() {
      var index = this.typeList.findIndex((item) => {
        return this.ids == item.itemId + "-" + item.promoterId;
      });
      this.typeList[index].sampleVoucher = this.$refs.fileUpload.fileList.map(item=>{
        return item.url
      }).join()
      // console.log(index);
      // console.log(this.$refs.fileUpload.fileList)
      // console.log(this.typeList)
      this.workVisible = false
      this.$refs.fileUpload.fileList = []
    },
    handleSelectionChange(selection) {
      this.okIds = selection.map((item) => item.itemId + "-" + item.promoterId);
    },
    okInfomation(item) {
      this.$router.replace({
        path: "/goodsManagement/promoterSelect",
        query: {
          itemIds: item.itemId,
        },
      });
    },
    toDetail(item) {
      localStorage.setItem("addItemInfo", JSON.stringify({ ...item, type: "look" }));
      this.$router.replace({
        path: "/goodsManagement/goodsPreview",
      });
    },
    copyInfomation(item) {
      if (!!item.sampleRequirement && !!item.sampleCount) {
        this.typeList = [
          ...this.typeList.map((items) => {
            return {
              ...items,
              sampleRequirement: item.sampleRequirement,
              sampleCount: item.sampleCount,
            };
          }),
        ];
      } else {
        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;

      preview({
        itemIds: this.$route.query.itemIds,
        ids: this.$route.query.promoterIds,
        userId: this.$store.getters.userId,
      }).then((response) => {
        this.$nextTick(() => {
          this.okIds = response.preview.samples.map((item) => {
            return item.itemId + "-" + item.promoterId;
          });

          this.typeList = response.preview.samples.map((item) => {
            return {
              ...item,
              sampleCount: null,
              sampleRequirement: null,
              consigneeEdit: false,
              promoterPhoneEdit: false,
              promoterAddressEdit: false,
              sampleVoucher:undefined,
            };
          });
          this.sampleReceivedCount = response.preview.sampleReceivedCount;

          this.$refs.multipleTable.toggleAllSelection();
        });

        // 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() {
      console.log(this.okIds);
      if (this.okIds.length > 0) {
        var dataArr = [];
        for (let i = 0; i < this.okIds.length; i++) {
          for (let c = 0; c < this.typeList.length; c++) {
            if (
              this.okIds[i] ==
              this.typeList[c].itemId + "-" + this.typeList[c].promoterId
            ) {
              dataArr.push(this.typeList[c]);
            }
          }
        }

        var dataFind = dataArr.findIndex((v) => {
          return !v.sampleRequirement || !v.sampleCount;
        });
        if (dataFind > -1) {
          this.$message.error("请填写提交的领样");
        } else {
          this.loadingAdd = true;
          // console.log(dataArr);
          addPreview({ temCollectSamples: JSON.stringify(dataArr) }).then((res) => {
            this.loadingAdd = false;
            const obj = {
              path: "/goodsManagement/samplingList",
            };
            this.$tab.closeOpenPage(obj);
            this.$message.success("提交成功");
            localStorage.setItem("clearData", 1);
          });
        }
      } else {
        this.$message.error("请选择提交的领样");
      }
      //   this.getAreaList();
      //   this.openAllocation = true;
      //   this.edit = false;
      //   this.ids = null;
      //   this.confirmLoading = false;
      //   this.formBroadcast = {};
      //   setTimeout(() => {
      //     this.$refs.formBroadcast.clearValidate();
      //   }, 0);
    },
    /** 修改按钮操作 */
    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>
