<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: 240px"
        >
          <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="商品名称" prop="itemTitle">
        <el-input
          placeholder="请输入商品名称"
          style="width: 240px"
          v-model="queryParams.itemTitle"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="商品ID" prop="itemId">
        <el-input
          placeholder="请输入商品ID"
          style="width: 240px"
          v-model="queryParams.itemId"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="类目" prop="categoryId">
        <el-select
          filterable
          v-model="queryParams.categoryId"
          placeholder="选择行业"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in queryParamsList.categoryIdList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="选择日期">
        <el-date-picker
          v-model="uploadDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
        >搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-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-tabs v-model="queryParams.examineStatus" @tab-click="handleClick">
      <el-tab-pane
        :label="item.label"
        :name="item.value"
        v-for="(item, index) in queryParamsList.tagList"
        :key="index"
      >
        <el-button
          type="primary"
          plain
          size="mini"
          @click="batchProcess"
          v-if="queryParams.examineStatus == 1"
          style="margin-bottom: 15px"
        >批量审核
        </el-button>
        <el-table
          v-loading="loading"
          :data="typeList"
          ref="multipleTable"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          :row-key="getRowKeys"
        >
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column
            label="商品名称"
            align="center"
            prop="itemTitle"
            width="350"
            fixed="left"
          >
            <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="mediaName" width="50">
            <template slot-scope="scope">
              {{ scope.row.mediaName }}
            </template>
          </el-table-column>

          <el-table-column label="预售" align="center" prop="isPresale" width="80">


            <template slot-scope="scope">
              <font v-if="scope.row.isPresale == 2">
                是
              </font>

              <font v-if="scope.row.isPresale == 1">
                否
              </font>

              <el-button v-if="scope.row.isPresale != 1 && scope.row.isPresale != 2" size="mini" type="text"
                         @click="updateIsPresale(scope.row)"
              >设置
              </el-button>

            </template>


          </el-table-column>


          <el-table-column
            label="关联商品"
            align="center"
            prop="actionAssociation"
            width="150"
            v-if="queryParams.examineStatus == '2'"
          >
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="addItemId(scope.row)"
              >添加
              </el-button>
              <el-button size="mini" type="text" @click="showItemList(scope.row)"
              >列表
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            label="结算规则名称"
            align="center"
            prop="ruleName"
            width="150"
          >
            <template slot-scope="scope">
              <div v-if="!!scope.row.ruleName">
                <el-button size="mini" type="text" @click="lookDetail(scope.row)"
                >{{ scope.row.ruleName }}
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  @click="
                    ruleEditVisible = true;
                    formRuleEdit = { ruleId: scope.row.ruleId };
                    ids = scope.row.itemId;
                  "
                >编辑
                </el-button>
              </div>
              <div v-else>
                <el-button
                  size="mini"
                  type="text"
                  @click="
                    ruleEditVisible = true;
                    formRuleEdit = { ruleId: undefined };
                    ids = scope.row.itemId;
                  "
                >绑定规则
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="服务费率"
            align="center"
            prop="regimentalPromotionRate"
            width="150"
          >
            <template slot-scope="scope">
              {{ (scope.row.regimentalPromotionRate / 10).toFixed(2) + "%" }}
            </template>
          </el-table-column>
          <el-table-column label="创建人" align="center" prop="userName" width="150">
            <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="sampleRequirement"
            width="150"
          >
            <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" width="150">
            <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="samplesReceived"
            width="150"
          >
            <template slot-scope="scope">
              <div v-if="!!scope.row.samplesReceived">
                {{ scope.row.samplesReceived }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column
            label="领样人数"
            align="center"
            prop="samplesPeoples"
            width="150"
          >
            <template slot-scope="scope">
              <div v-if="!!scope.row.samplesPeoples">
                {{ scope.row.samplesPeoples }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>

          <el-table-column
            label="有效订单数"
            align="center"
            prop="validOrderNum"
            width="150"
          >
            <template slot-scope="scope">
              <div v-if="!!scope.row.validOrderNum">
                {{ scope.row.validOrderNum }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column label="有效金额" align="center" prop="validAmount" width="150">
            <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="activityItemStatus"
            width="150"
          >
            <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="categoryName" width="150">
            <template slot-scope="scope">
              <div v-if="!!scope.row.categoryName">
                {{ scope.row.categoryName.split(">")[0] }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>

          <el-table-column label="创建时间" align="center" prop="createTime" width="150">
            <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"
            width="250"
          >
            <template slot-scope="scope">
              <div
                v-if="!!scope.row.partnerRecommendText"
                style="
                  text-overflow: ellipsis;
                  white-space: nowrap;
                  overflow: hidden;
                  width: 100%;
                "
                :title="scope.row.partnerRecommendText"
              >
                {{ scope.row.partnerRecommendText }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>

          <el-table-column
            label="拒绝原因"
            align="center"
            prop="refuseDetail"
            v-if="queryParams.examineStatus == 3"
          >
            <template slot-scope="scope">
              <div v-if="!!scope.row.refuseDetail">
                {{ scope.row.refuseDetail }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            width="200px"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="okInfomation(scope.row)"
                v-show="queryParams.examineStatus == '1'"
                :disabled="
                  $store.getters.roles[0] != 'admin' &&
                  $store.getters.roles[0] != 'supplyChainAdmin' &&
                  $store.getters.roles[0] != 'associationManager'
                "
              >通过
              </el-button>
              <el-button
                size="mini"
                type="text"
                @click="
                  itemId = scope.row.itemId;
                  refuseVisible = true;
                "
                v-show="queryParams.examineStatus == '1'"
                :disabled="
                  $store.getters.roles[0] != 'admin' &&
                  $store.getters.roles[0] != 'supplyChainAdmin' &&
                  $store.getters.roles[0] != 'associationManager'
                "
              >拒绝
              </el-button>

              <el-button
                size="mini"
                type="text"
                @click="handleAddbroadcast(scope.row)"
                v-if="queryParams.examineStatus == '3'"
              >编辑
              </el-button>
              <el-button
                size="mini"
                type="text"
                @click="copyInfomation(scope.row)"
                v-if="queryParams.examineStatus == '2'"
              >商品复制
              </el-button>
              <el-button
                size="mini"
                type="text"
                @click="unbindingItem(scope.row)"
                v-if="queryParams.examineStatus == '2'"
              >解绑
              </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-tab-pane>
    </el-tabs>

    <!-- 添加直播 -->
    <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="选择媒体" prop="mediaId" class="entire-line" style="width: 100%">
          <el-radio-group v-model="mediaId">
            <el-radio-button label="2">快手</el-radio-button>
            <el-radio-button label="1">抖音</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否预售" prop="isPresale" v-if="this.mediaId == '2'" class="entire-line"
                      style="width: 100%">
          <el-radio-group v-model="isPresale">
            <el-radio-button label=1>否</el-radio-button>
            <el-radio-button label=2>是</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="商品类型" prop="byteDanceItemType" v-if="this.mediaId == '1'" class="entire-line"
                      style="width: 100%">
          <el-radio-group v-model="byteDanceItemType">
            <el-radio-button label="2">托管</el-radio-button>
            <el-radio-button label="1">常规</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="商品归属" prop="regId" v-if="this.mediaId == '2'">
          <el-select
            filterable
            v-model="formBroadcast.regId"
            placeholder="请选择商品所属团"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="item in regInfo"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="活动ID" v-if="this.mediaId == 2 || (this.mediaId == 1 && this.byteDanceItemType == 1)"
                      prop="activityId">
          <el-select
            style="width: 240px"
            v-model="formBroadcast.activityId"
            filterable
            allow-create
            default-first-option
            placeholder="请选择或填写活动ID"
            :disabled="edit"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品ID" prop="itemId">
          <el-input
            placeholder="请输入商品ID"
            style="width: 240px"
            v-model.trim="formBroadcast.itemId"
            :disabled="edit"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="发货地" prop="postArea" v-if="edit">
          <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="dataOwnership" v-if="this.mediaId == '2'">
          <el-select
            filterable
            v-model="formBroadcast.dataOwnership"
            placeholder="请选择销售团队归属"
            clearable
            style="width: 240px">
            <el-option
              v-for="item in dataOwnerships"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </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="sampleRequirement">
          <el-input
            placeholder="请输入领样要求"
            style="width: 240px"
            v-model="formBroadcast.sampleRequirement"
          >
          </el-input>
        </el-form-item>


        <el-form-item label="不发货地区" prop="noPostArea">
          <el-input
            placeholder="请输入不发货地区"
            style="width: 240px"
            v-model="formBroadcast.noPostArea"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="佣金比例" prop="commissionRate" v-if="edit">
          <el-input-number
            style="width: 240px"
            v-model="formBroadcast.commissionRate"
            :precision="2"
            :step="0.1"
            :max="100"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="服务费" prop="regimentalPromotion" v-if="edit">
          <el-input
            placeholder="请输入服务费"
            style="width: 240px"
            v-model="formBroadcast.regimentalPromotion"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="服务费率" prop="regimentalPromotionRate" v-if="edit">
          <el-input-number
            style="width: 240px"
            v-model="formBroadcast.regimentalPromotionRate"
            :precision="2"
            :step="0.1"
            :max="100"
            :min="0"
          ></el-input-number>
        </el-form-item>


        <el-form-item label="结算规则" prop="ruleId">
          <el-select
            filterable
            v-model="formBroadcast.ruleId"
            placeholder="请选择规则"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="item in ruleInfo"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发货时效" prop="deliveryRate" v-if="edit">
          <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
            type="textarea"
            :rows="2"
            placeholder="粘贴图片转换文字"
            v-model="formBroadcast.partnerRecommendText"
            @paste.native="handlePaste"
          >
          </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
      :close-on-click-modal="false"
    >
      <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="associationVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-input placeholder="请输入关联商品Id" style="width: 100%" v-model="refuseInfo">
      </el-input>

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


    <el-dialog
      title="是否预售"
      :visible.sync="updateIsPresaleVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-radio-group v-model="updateIsPresaleValue">
        <el-radio-button label=1>否</el-radio-button>
        <el-radio-button label=2>是</el-radio-button>
      </el-radio-group>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpdateIsPresale" :loading="refuseLoading"
        >确 定
        </el-button>
        <el-button
          @click="
            refuseLoading = false;
            updateIsPresaleVisible = false;
            updateIsPresaleValue = null;
          "
        >取 消
        </el-button>
      </div>
    </el-dialog>


    <!-- 关联商品列表 -->
    <el-dialog title="关联商品列表" :visible.sync="associationListVisible" width="800px">
      <el-table :data="associationList" style="width: 100%">
        <el-table-column label="商品名称" align="center" prop="itemTitle">
          <template slot-scope="scope">
            <span :style="associationItemId == scope.row.itemId ? 'color:red' : ''">{{
                scope.row.itemTitle
              }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品ID" align="center" prop="itemId">
          <template slot-scope="scope">
            <span :style="associationItemId == scope.row.itemId ? 'color:red' : ''">{{
                scope.row.itemId
              }}</span>
          </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"
              @click="removeItem(scope.row)"
              :disabled="associationItemId == scope.row.itemId"
            >撤销
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 结算规则列表 -->
    <el-dialog title="结算规则" :visible.sync="ruleVisible" width="800px">
      <el-table :data="ruleList" style="width: 100%">
        <el-table-column label="序号" align="center" prop="sortCount"></el-table-column>
        <el-table-column
          label="起始单数"
          align="center"
          prop="startItemCount"
        ></el-table-column>
        <el-table-column
          label="结束单数"
          align="center"
          prop="endItemCount"
        ></el-table-column>
        <el-table-column
          label="主播奖励金额"
          align="center"
          prop="anchorAmount"
        ></el-table-column>
        <el-table-column
          label="推荐人奖励金额"
          align="center"
          prop="referenceAmount"
        ></el-table-column>
      </el-table>
    </el-dialog>

    <!-- 编辑/绑定结算规则 -->
    <el-dialog title="编辑/绑定结算规则" :visible.sync="ruleEditVisible" width="500px">
      <el-form
        ref="formRuleEdit"
        :model="formRuleEdit"
        :rules="ruleEdit"
        label-width="100px"
        :inline="true"
      >
        <el-form-item label="结算规则" prop="ruleId">
          <el-select
            filterable
            v-model="formRuleEdit.ruleId"
            placeholder="请选择规则"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="item in ruleInfo"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormRuleEdit" :loading="confirmLoading"
        >确 定
        </el-button>
        <el-button
          @click="
            confirmLoading = false;
            ruleEditVisible = false;
            formRuleEdit = {};
          "
        >取 消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {refreshCache} from "@/api/system/dict/type";
import {
  getItemList,
  getAreaList,
  getCity,
  checkItem,
  editItem,
  getCategoryIds,
  getActivityIds,
  readImage,
  unbindingItem,
  batchItemProcess,
  getRegimental,
  editRelateByItemId,
  getListByRelateId,
  getRuleListNoPage,
  getRuleDetailByRuleId,
  editRuleIdByItemId,
  removeRelateByItemId,
  getDataOwnership, checkUser, updateIsPresaleByItemId,
} from "@/api/goodsManagement/goods";
import selectTree from "./selectTree.vue";
import textEditor from "./textEditor.vue";

export default {
  name: "List",
  components: {
    selectTree,
    textEditor,
  },
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (!!value && !this.edit) {

        checkItem({itemId: value, targetOwnershipId: this.formBroadcast.dataOwnership, mediaId: this.mediaId})
          .then((res) => {
            if (res.success) {
              callback();
            } else {
              callback(
                new Error(res.message)
              );
            }
          }).catch((e) => {
          console.log(e)
        });
      } else {
        callback();
      }
    };


    const checkDataOwnership = (rule, value, callback) => {
      if (!!value) {
        checkUser({ownershipId: value, userName: this.$store.getters.name})
          .then((res) => {
            if (res.success) {
              callback();
            } else {
              callback(
                new Error(res.message)
              );
            }
          }).catch((e) => {
          console.log(e)
        });
      } else {
        callback();
      }
    };
    return {
      uploadDate: [],
      updateIsPresaleValue: 1,
      isPresale: 0,
      mediaId: "2",
      byteDanceItemType: "2",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: null,
      idElse: 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,
        categoryId: undefined,
        examineStatus: "2",
      },
      //页面所有的下拉数据
      queryParamsList: {
        tagList: [
          {value: "2", label: "我的商品"},
          {value: "1", label: "待审核"},
          {value: "3", label: "审核拒绝"},
        ],
        categoryIdList: [],
        mediaList: [
          {value: 2, label: "快手"},
          {value: 1, label: "抖音"},
        ],
      },
      // 表单参数
      form: {},
      formBroadcast: {},

      formRuleEdit: {},
      options: [],
      regInfo: [],
      dataOwnerships: [],
      ruleInfo: [],
      //上传报表下拉数据
      formList: {},
      fileList: [],
      accept: "",
      //获取销售线索文件流
      dateFile: new FormData(),
      //销售线索上传loading
      confirmLoading: false,
      // 表单校验
      rules: {},
      ruleEdit: {
        ruleId: {
          required: true,
          message: "结算规则必选",
          trigger: "change",
        },
      },
      rulesBroadcast: {
        dataOwnership: [
          {
            required: true,
            message: "数据归属必填",
            trigger: "blur",
          },
          {required: true, validator: checkDataOwnership, trigger: "blur"},
        ],


        itemId: [
          {
            required: true,
            message: "商品ID必填",
            trigger: "blur",
          },
          {required: true, validator: equalToPassword, trigger: "blur"},
          {
            type: "number",
            message: "商品ID只能输入数字",
            trigger: "blur",
            transform(value) {
              return +value;
            },
          },
        ],
        activityId: [
          {
            required: true,
            message: "活动ID必填",
            trigger: "blur",
          },
          {
            type: "number",
            message: "活动ID只能输入数字",
            trigger: "blur",
            transform(value) {
              if (!!value) {
                return +value;
              }
            },
          },
        ],

        isPresale: {
          required: false,
          message: "是否预售必选",
          trigger: "blur",
        },

        postArea: {
          required: true,
          message: "发货地必选",
          trigger: "change",
        },
        noPostArea: {
          required: false,
          message: "不发货地必选",
          trigger: "blur",
        },
        regId: {
          required: true,
          message: "团长信息必填",
          trigger: "change",
        },
        commissionRate: [
          {
            required: true,
            message: "佣金比例必填",
            trigger: "blur",
          },
          {
            type: "number",
            message: "佣金比例只能输入数字",
            trigger: "blur",
            transform(value) {
              return +value;
            },
          },
        ],
        regimentalPromotion: [
          {
            required: false,
            message: "服务费必填",
            trigger: "blur",
          },
        ],
        regimentalPromotionRate: [
          {
            required: true,
            message: "服务费率必填",
            trigger: "blur",
          },
          {
            type: "number",
            message: "服务费率只能输入数字",
            trigger: "change",
            transform(value) {
              return +value;
            },
          },
        ],
        sampleRequirement: {
          required: true,
          message: "领样要求必填",
          trigger: "blur",
        },
        sampleCount: [
          {
            required: true,
            message: "样品数量必填",
            trigger: "blur",
          },
          {
            type: "number",
            message: "佣金比例只能输入数字",
            trigger: "blur",
            transform(value) {
              return +value;
            },
          },
        ],
        partnerRecommendText: [
          {
            required: true,
            message: "手卡内容必填",
            trigger: "blur",
          },
          {
            min: 5,
            message: "手卡内容最少输入5个字符",
            trigger: "change",
          },
        ],
        ruleId: {
          required: false,
          message: "",
          trigger: "change",
        },
      },
      // 分配销售展示列表
      ksInfo: null,
      userId: null,
      userName: null,
      refuseVisible: false,
      refuseLoading: false,
      refuseInfo: null,
      itemId: null,
      updateIsPresaleItemId: null,
      associationVisible: false,
      updateIsPresaleVisible: false,
      relateId: null,
      associationListVisible: false,
      associationList: null,
      associationItemId: null,
      ruleVisible: false,
      ruleList: [],
      ruleEditVisible: false,
    };
  },
  created() {
    this.userId = this.$store.getters.userId;
    this.username = this.$store.getters.name;
    this.getList();
    this.getCategoryIds();
    // this.getActivityIds();
    this.getRegimental();
    this.getDataOwnership();
    this.getRuleListNoPage();
  },
  filters: {
    activityItemStatusName(status) {
      const statusMap = {
        1: "待审核",
        2: "已上架",
        3: "审核失败（拒绝）",
        4: "活动结束",
        5: "失效",
      };
      return statusMap[status];
    },
  },
  watch: {
    "formBroadcast.partnerRecommendText": function (n, o) {
      // console.log(n.replace(/<p>|<\/?p>|&nbsp;/gim, ""));
    },
  },
  methods: {
    removeItem(item) {
      removeRelateByItemId({itemId: item.itemId})
        .then((res) => {
          this.$message.success("撤销成功");
          this.showItemList(this.idElse);
        })
        .catch(() => {
          this.$message.error("出错了，请联系管理员");
        });
    },
    lookDetail(item) {
      getRuleDetailByRuleId({ruleId: item.ruleId}).then((res) => {
        this.ruleVisible = true;
        this.ruleList = res.data;
      });
    },

    showItemList(item) {
      getListByRelateId({relateId: item.relateId})
        .then((res) => {
          this.idElse = item;
          this.associationListVisible = true;
          this.associationList = res.data;
          this.associationItemId = item.itemId;
        })
        .catch(() => {
          this.$message.error("出错了，请联系管理员");
        });
    },
    addItemId(item) {
      this.associationVisible = true;
      this.relateId = item.relateId;
    },


    updateIsPresale(item) {
      this.updateIsPresaleVisible = true;
      this.updateIsPresaleItemId = item.itemId;
    },
    submitAssociation() {
      if (!!this.refuseInfo) {
        this.refuseLoading = true;
        editRelateByItemId({
          itemId: this.refuseInfo,
          relateId: this.relateId,
        })
          .then((res) => {
            this.refuseLoading = false;
            this.associationVisible = false;
            this.relateId = null;
            this.$message.success("添加成功");
          })
          .catch(() => {
            this.refuseLoading = false;
          });
      } else {
        this.$message.error("请填写商品ID");
      }
    },

    submitUpdateIsPresale() {
      this.refuseLoading = true;
      updateIsPresaleByItemId({
        itemId: this.updateIsPresaleItemId,
        isPresale: this.updateIsPresaleValue,
      })
        .then((res) => {
          this.refuseLoading = false;
          this.updateIsPresaleItemId = null;
          this.updateIsPresaleVisible = false;
          this.updateIsPresaleValue = null;
          this.$message.success("修改成功");
          this.updateIsPresaleValue = 1;
          this.getList();
        })
        .catch(() => {
          this.refuseLoading = false;
        });

    },
    getRowKeys(row) {
      return row.itemId;
    },
    batchProcess() {
      if (this.okIds.length > 0) {
        batchItemProcess({
          itemIds: this.okIds,
          status: 2,
          examineId: this.$store.getters.userId,
          examineName: this.$store.getters.name,
        }).then((res) => {
          this.okIds = [];
          this.handleQuery();
          this.$message.success(res.message);
        });
      } else {
        this.$message.error("请选择商品");
      }
    },
    handleSelectionChange(selection) {
      this.okIds = selection.map((item) => item.itemId);
    },
    handlePaste(value) {
      let items = value.clipboardData.items[0];
      let file;
      console.log(value);
      if (items.type.includes("image")) {
        file = items.getAsFile();
        let formData = new FormData();
        formData.append("file", file);
        readImage(formData).then((res) => {
          if (res.code == 0) {
            // this.formBroadcast.partnerRecommendText = res.data;
            this.$set(this.formBroadcast, "partnerRecommendText", res.data);
          }
        });
      }
    },
    toDetail(item) {
      localStorage.setItem("addItemInfo", JSON.stringify({...item, type: "look"}));
      this.$router.replace({
        path: "/goodsManagement/goodsPreview",
      });
    },
    getActivityIds() {
      getActivityIds({userId: this.userId}).then((res) => {
        this.options = res.data.map((item) => {
          return {
            label: item,
            value: item,
          };
        });
      });
    },
    getRegimental() {
      getRegimental().then((res) => {
        this.regInfo = res.data.map((item) => {
          return {
            label: item.regName,
            value: item.id,
          };
        });
      });
    },


    getDataOwnership() {
      getDataOwnership().then((res) => {
        this.dataOwnerships = res.data.map((item) => {
          return {
            label: item.ownershipName,
            value: item.ownershipId,
          };
        });
      });
    },


    getRuleListNoPage() {
      getRuleListNoPage({userId: this.userId}).then((res) => {
        this.ruleInfo = res.data.map((item) => {
          return {
            label: item.ruleName,
            value: item.id,
          };
        });
      });
    },
    getCategoryIds() {
      getCategoryIds().then((res) => {
        this.queryParamsList.categoryIdList = res.map((item) => {
          return {
            label: item.categoryName,
            value: item.categoryId,
          };
        });
      });
    },
    copyInfomation(item) {
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard
          .writeText(
            `
店铺: ${item.shopTitle ? item.shopTitle : "-"}
商品体验: ${item.shopScore ? item.shopScore : "-"}
商家服务: ${item.mallServiceScore ? item.mallServiceScore : "-"}
产品: ${item.itemTitle}
直播价: ¥${item.zkFinalPrice / 100}
佣金比例: ${item.commissionRate / 10}%
团长推荐: ${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.shopTitle : "-"}
商品体验: ${item.shopScore ? item.shopScore : "-"}
商家服务: ${item.mallServiceScore ? item.mallServiceScore : "-"}
产品: ${item.itemTitle}
直播价: ¥${item.zkFinalPrice / 100}
佣金比例: ${item.commissionRate / 10}%
团长推荐: ${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("请输入拒绝原因");
      }
    },
    unbindingItem(item) {
      this.$modal
        .confirm(`请确认是否解绑该商品信息？`)
        .then(() => {
          var params = {};
          params.itemId = item.itemId;
          unbindingItem(params)
            .then((res) => {
              this.getList();
              this.$modal.msgSuccess(res.message);
            })
            .catch((err) => {
            });
        })
        .catch(() => {
        });
    },
    okInfomation(item) {
      this.$modal
        .confirm(`请确认是否审核通过该商品信息？`)
        .then(() => {
          var params = {};
          params.itemId = item.itemId;
          params.examineStatus = 2;
          params.examineId = this.$store.getters.userId;
          params.examineName = this.$store.getters.name;
          editItem(params)
            .then((res) => {
              this.getList();
              this.$modal.msgSuccess("审核通过");
            })
            .catch(() => {
              this.$message.error("失败");
            });
        })
        .catch(() => {
        });
    },
    getAreaList() {
      getAreaList().then((res) => {
        this.superiorList = res.map((item) => {
          return {
            id: item,
            name: item,
          };
        });
      });
    },
    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();
      }
    },
    handleClick() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 查询字典类型列表 */
    getList() {
      this.loading = true;
      getItemList(this.addDateRange({userId: this.userId, ...this.queryParams}, this.uploadDate, "startDate", "endDate")).then((response) => {
        this.typeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.confirmLoading = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.uploadDate = [];
      this.dateFile = null;
      this.resetForm("formBroadcast");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.mediaId = undefined;
      this.dateRange = [];
      this.uploadDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    addNew() {
      this.getAreaList();
      this.openAllocation = true;
      this.edit = false;
      this.ids = null;
      this.confirmLoading = false;
      this.formBroadcast = {};
      this.getActivityIds();
      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, "regId", item.regId);
        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 / 10);

        this.$set(
          this.formBroadcast,
          "regimentalPromotion",
          item.regimentalPromotion / 100
        );
        this.$set(
          this.formBroadcast,
          "regimentalPromotionRate",
          item.regimentalPromotionRate / 10
        );
        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);
        this.$set(this.formBroadcast, "ruleId", item.ruleId);
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
    },
    /** 修改/绑定结算规则 */
    submitFormRuleEdit() {
      this.$refs["formRuleEdit"].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          let params = {};
          params.ruleId = this.formRuleEdit.ruleId;
          params.itemId = this.ids;
          editRuleIdByItemId(params).then((res) => {
            this.confirmLoading = false;
            this.ruleEditVisible = false;
            this.formRuleEdit = {};
            this.getList();
            this.$modal.msgSuccess("修改成功");
          });
        }
      });
    },
    /** 新增直播确定按钮 */
    submitFormBroadcast: function () {
      this.$refs["formBroadcast"].validate((valid) => {
        if (valid) {
          if (!this.edit) {
            if (this.formBroadcast.partnerRecommendText.indexOf("img") == -1) {
              var params = {...this.formBroadcast};
              params.partnerRecommendText = params.partnerRecommendText.replace(
                /<p>|<\/?p>|&nbsp;|<pre>|<\/?pre>/gim,
                ""
              );
              params.mediaId = this.mediaId;
              params.byteDanceItemType = this.byteDanceItemType;
              params.examineStatus = 1;
              params.isPresale = this.isPresale;
              this.confirmLoading = false;
              this.openAllocation = false;
              console.log("是否预售")
              console.log(this.isPresale)
              console.log(params)
              localStorage.setItem("addItemInfo", JSON.stringify(params));
              this.$router.replace({
                path: "/goodsManagement/goodsPreview",
              });
            } else {
              this.$message.error("图片未识别，请重新截图");
            }
          } else {
            this.confirmLoading = true;
            var params = {...this.formBroadcast};
            params.examineStatus = 1;
            params.regimentalPromotion = params.regimentalPromotion * 100;
            params.regimentalPromotionRate = params.regimentalPromotionRate * 10;
            params.commissionRate = params.commissionRate * 10;
            params.mediaId = this.mediaId;
            params.byteDanceItemType = this.byteDanceItemType;
            params.isPresale = this.isPresale;
            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>
