<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <el-form-item label="活动日期:" prop="dateRange">
        <el-date-picker
          v-model="queryParams.dateRange"
          :picker-options="pickerOptions"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          style="width: 225px"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="活动名称:" prop="activitieName">
        <el-input
          v-model="queryParams.activitieName"
          placeholder="请输入活动名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="活动编码:" prop="activitieCode">
        <el-input
          v-model="queryParams.activitieCode"
          placeholder="多个活动编码使用逗号隔开"
          clearable
        />
      </el-form-item>
      <el-form-item label="返利类型:" prop="rebateTypeCode">
        <el-select
          v-model="queryParams.rebateTypeCode"
          placeholder="请选择返利类型"
          style="width: 220px"
          clearable
        >
          <el-option
            v-for="(dict, index) in rebateTypeCodeList"
            :key="index"
            :label="dict.name"
            :value="dict.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="活动状态:" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择活动状态"
          style="width: 220px"
          clearable
        >
          <el-option
            v-for="(dict, index) in statusList"
            :key="index"
            :label="dict.name"
            :value="dict.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="返利发放状态:" label-width="120px" prop="rebateSendStatus">
        <el-select
          v-model="queryParams.rebateSendStatus"
          placeholder="请选择返利发放状态"
          clearable
        >
          <el-option
            v-for="(dict, index) in rebateSendStatusList"
            :key="index"
            :label="dict.name"
            :value="dict.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="品牌:" prop="brandCodes">
        <el-select
          v-model="queryParams.brandCodes"
          filterable
          placeholder="请选择品牌"
          clearable
          multiple
        >
          <el-option
            v-for="(dict, index) in brandNameList"
            :key="index"
            :label="dict.brandName"
            :value="dict.brandCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="供货商:" prop="suppliers">
        <el-select
          v-model="queryParams.suppliers"
          multiple
          filterable
          placeholder="请选择供货商"
          clearable
        >
          <el-option
            v-for="(dict, index) in suppliersList"
            :key="index"
            :label="dict.supplierName"
            :value="dict.supplierCode"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="商品编码:" prop="skuNos">
        <el-input
          v-model="queryParams.skuNos"
          placeholder="多个商品编码使用逗号隔开"
          clearable
        />
      </el-form-item>
      <el-form-item label="商品名称:" prop="skuNo">
        <LoadMoreSelect
          :skuNo="queryParams.skuNo"
          @queryParams="(val) => (queryParams.skuNo = val)"
        />
      </el-form-item>
      <el-row :gutter="10" class="mb8" type="flex" justify="end">
        <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-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain size="mini" @click="expandChange">{{
          expandText
        }}</el-button>
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          >新建活动</el-button
        >
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :disabled="ids.length == 0"
          @click="handlePause2"
          >批量下载返利订单</el-button
        >
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      ref="proTable"
      border
      v-loading="loading"
      row-key="ssId"
      :tree-props="{ children: 'activitieListSkuDTOList' }"
      :key="treeKey"
      :data="postList"
      :height="tableHeight"
      :default-expand-all="isExpand"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="left" />
      <el-table-column
        label="活动名称/编码"
        min-width="140"
        align="left"
        prop="activitieCode"
      >
        <template slot-scope="scope">
          <span v-if="!scope.row.skuName"
            >{{ scope.row.activitieName }}/{{ scope.row.activitieCode }}</span
          >
        </template>
      </el-table-column>
      <el-table-column label="活动时间" min-width="140" align="left" prop="activitieDate">
      </el-table-column>
      <el-table-column label="返利类型" min-width="100" align="left" prop="rebateType">
      </el-table-column>
      <el-table-column label="品牌" min-width="90" align="left" prop="brand" />
      <el-table-column
        label="参与门槛"
        min-width="320"
        align="left"
        prop="activitieSupplier"
      >
        <template slot-scope="scope">
          <el-tooltip class="item" content="Top center" placement="top">
            <div slot="content" style="width: auto">
              <div v-if="!scope.row.skuName">渠道：{{ scope.row.activitieChannel }}</div>
              <div v-if="!scope.row.skuName">
                供应商：{{ scope.row.activitieSupplier }}
              </div>
            </div>
            <div class="table-overflow">
              <div v-if="!scope.row.skuName">渠道：{{ scope.row.activitieChannel }}</div>
              <div v-if="!scope.row.skuName">
                供应商：{{ scope.row.activitieSupplier }}
              </div>
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="状态" min-width="110" align="left" prop="status">
        <template slot-scope="scope">
          <span v-show="scope.row.status == 0">待提交/</span>
          <span v-show="scope.row.status == 1">待审批/</span>
          <span v-show="scope.row.status == 2">审批打回/</span>
          <span v-show="scope.row.status == 3">启用/</span>
          <span v-show="scope.row.status == 4">下线/</span>
          <span v-show="scope.row.status == 5">挂起/</span>
          <span v-show="scope.row.status == 6">变更待审批/</span>
          <span v-show="scope.row.status == 7">变更审批打回/</span>
          <span v-show="scope.row.status == 8">变更待提交/</span>
          <span v-show="scope.row.rebateSendStatus == 0">未发放返利</span>
          <span v-show="scope.row.rebateSendStatus == 1">发放返利中</span>
          <span v-show="scope.row.rebateSendStatus == 2">已完成返利发放</span>
        </template>
      </el-table-column>
      <el-table-column
        label="返利商品"
        min-width="220"
        align="left"
        prop="activitieListSkuDTOList"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.skuName">
            {{ scope.row.skuName }}/ {{ scope.row.skuNo }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="商品返利金额(元)"
        min-width="220"
        align="left"
        prop="curSale"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.remarkAmount" v-html="scope.row.remarkAmount"></span>
        </template>
      </el-table-column>
      <el-table-column
        label="活动返利金额(元)"
        min-width="220"
        align="left"
        prop="curSale"
      >
        <template slot-scope="scope">
          <div v-if="!scope.row.skuName">
            预估返利：{{ scope.row.estimateAmount || 0 }}
          </div>
          <div v-if="!scope.row.skuName">
            销售返利：{{ scope.row.rebateTotalAmount || 0 }}
          </div>
        </template>
      </el-table-column>

      <!-- <el-table-column label="指定返利串码" min-width="120" align="left" prop="skuSn">
      </el-table-column>
      <el-table-column label="指定串码返利金额" min-width="120" align="left" prop="skuSnPrice">
      </el-table-column> -->
      <el-table-column label="操作" width="180" align="left" fixed="right">
        <template slot-scope="scope">
          <div v-if="!scope.row.skuName">
            <el-button
              size="mini"
              type="text"
              v-if="scope.row.status == 0 || scope.row.status == 2"
              @click="submitItem(scope.row)"
              :disabled="userName!=scope.row.createdBy"
              >提交审核</el-button
            >
            <el-button
              size="mini"
              type="text"
              v-if="scope.row.status == 1 || scope.row.status == 6"
              @click="recallItem(scope.row)"
              :disabled="userName!=scope.row.createdBy"
              >撤回</el-button
            >
            <el-button
              size="mini"
              v-if="
                scope.row.status == 0 || scope.row.status == 2 || scope.row.status == 7
              "
              type="text"
              @click="handleEdit(scope.row, 1)"
              :disabled="userName!=scope.row.createdBy"
              >编辑</el-button
            >
            <el-button
              size="mini"
              v-if="scope.row.status == 7 || scope.row.status == 8"
              type="text"
              @click="handleEdit(scope.row, 3)"
              :disabled="userName!=scope.row.createdBy"
              >变更编辑</el-button
            >
            <el-button size="mini" type="text" @click="handleEdit(scope.row, 2)"
              >查看详情</el-button
            >
            <el-button
              size="mini"
              v-if="scope.row.status == 3"
              type="text"
              @click="handleEdit(scope.row, 4)"
              :disabled="userName!=scope.row.createdBy"
              >变更</el-button
            >
            <el-button
              size="mini"
              v-if="scope.row.status == 3"
              type="text"
              @click="handleOff(scope.row)"
              :disabled="userName!=scope.row.createdBy"
              >下线</el-button
            >
            <el-button
              size="mini"
              v-if="scope.row.rebateSendStatus == 1 || scope.row.rebateSendStatus == 2"
              type="text"
              @click="handlePause2(scope.row)"
              >下载返利订单</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      class="fixed-pagination"
    />

    <el-dialog
      :title="title"
      :visible.sync="open2"
      top="50px"
      width="1100px"
      append-to-body
    >
      <el-tabs type="card" v-model="activeName">
        <el-tab-pane label="返利活动" name="1">
          <el-row>
            <h3 style="margin-top: 0"><span></span>返利活动信息</h3>
            <el-form
              :model="addForm"
              ref="addForm"
              size="small"
              :inline="true"
              :disabled="disabledForm"
              label-width="170px"
            >
              <el-row>
                <el-col :span="24">
                  <el-form-item label="返利类型:" prop="rebateTypeCode">
                    <el-radio-group
                      v-model="addForm.rebateTypeCode"
                      @change="fltypeChange"
                    >
                      <el-radio label="JLF">激励返</el-radio>
                      <el-radio label="THGDF">提货固定返</el-radio>
                      <el-radio label="THDLF">提货达量返</el-radio>
                      <el-radio label="XSDLF">销售达量返</el-radio>
                      <el-radio label="THJJTF">提货价阶梯返</el-radio>
                      <el-radio label="ZDCMF">指定串码返利</el-radio>
                    </el-radio-group>
                    <div class="color-r" v-show="addForm.rebateTypeCode == 'JLF'">
                      品牌方给出的临时返利激励政策，如激活返、礼品激励等
                    </div>
                    <div class="color-r" v-show="addForm.rebateTypeCode == 'THGDF'">
                      品牌方提供的长期提货固定返点
                    </div>
                    <div class="color-r" v-show="addForm.rebateTypeCode == 'THDLF'">
                      提货达到一定数量给与的返利，可以设置多档
                    </div>
                    <div class="color-r" v-show="addForm.rebateTypeCode == 'XSDLF'">
                      销售达到一定数量给与的返利，可以设置多档
                    </div>
                    <div class="color-r" v-show="addForm.rebateTypeCode == 'THJJTF'">
                      按指定价提货给与的返利，如小米的闪降，可以设置多档
                    </div>
                    <div class="color-r" v-show="addForm.rebateTypeCode == 'ZDCMF'">
                      指定范围的串码才能享受的返利，如价保等
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="返利活动名称:"
                    :rules="[
                      {
                        required: true,
                        message: '请输入返利活动名称',
                        trigger: 'change',
                      },
                    ]"
                    prop="activitieName"
                  >
                    <el-input
                      v-model="addForm.activitieName"
                      max-Length="50"
                      style="width: 300px"
                      placeholder="请输入返利活动名称"
                      clearable
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="返利活动编码:"
                    v-if="disabledForm"
                    prop="activitieName"
                    >{{ addForm.activitieCode }}
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="活动状态:" prop="status">
                    <span v-show="addForm.status == 0">待提交</span>
                    <span v-show="addForm.status == 1">待审批</span>
                    <span v-show="addForm.status == 2">审批打回</span>
                    <span v-show="addForm.status == 3">启用</span>
                    <span v-show="addForm.status == 4">下线</span>
                    <span v-show="addForm.status == 5">挂起</span>
                    <span v-show="addForm.status == 6">变更待审批</span>
                    <span v-show="addForm.status == 7">变更审批打回</span>
                    <span v-show="addForm.status == 8">变更待提交</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="返利发放状态:" prop="status">
                    <span v-show="addForm.rebateSendStatus == 0">未发放返利</span>
                    <span v-show="addForm.rebateSendStatus == 1">发放返利中</span>
                    <span v-show="addForm.rebateSendStatus == 2">已完成返利发放</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label="返利活动日期:"
                    :rules="[
                      {
                        required: true,
                        message: '请选择返利活动日期',
                        trigger: 'change',
                      },
                    ]"
                    prop="dateRange"
                  >
                    <el-date-picker
                      v-model="addForm.dateRange"
                      :picker-options="pickerOptions"
                      type="daterange"
                      range-separator="-"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="yyyy-MM-dd"
                      style="width: 225px"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="品牌:"
                    :rules="[
                      { required: true, message: '请选择品牌', trigger: 'change' },
                    ]"
                    prop="brandName"
                  >
                    <el-select
                      v-model="addForm.brandName"
                      filterable
                      placeholder="请选择品牌"
                      clearable
                      @change="brandChange"
                      :disabled="title == '变更返利活动'"
                    >
                      <el-option
                        v-for="(dict, index) in brandNameList"
                        :key="index"
                        :label="dict.brandName"
                        :value="dict.brandName"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="享受返利政策的供货商:" prop="suppliers">
                    <el-select
                      v-model="addForm.suppliers"
                      filterable
                      placeholder="请选择供货商"
                      :reserve-keyword="true"
                      clearable
                      multiple
                    >
                      <el-option
                        v-for="(dict, index) in suppliersList"
                        :key="index"
                        :label="dict.supplierName"
                        :value="dict.supplierCode"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="享受返利政策的渠道:" prop="channels">
                    <el-select
                      v-model="addForm.channels"
                      filterable
                      :reserve-keyword="true"
                      placeholder="请选择渠道"
                      clearable
                      multiple
                    >
                      <el-option
                        v-for="(dict, index) in channelList"
                        :key="index"
                        :label="dict.channelName"
                        :value="dict.channelCode"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label="返利核算销售业绩比例:"
                    :rules="[
                      {
                        required: true,
                        message: '请输入返利核算销售业绩比例',
                        trigger: 'change',
                      },
                    ]"
                    prop="saleRabe"
                  >
                    <el-input
                      v-model="addForm.saleRabe"
                      placeholder="请输入返利核算销售业绩比例"
                      clearable
                      :min="0.0001"
                      :max="100"
                      type="number"
                      style="width: 190px"
                    />%
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="返利核算销售业绩时点:" prop="salePoint">
                    <el-radio
                      :disabled="true"
                      v-model="addForm.salePoint"
                      label="销售出库"
                      >销售出库</el-radio
                    >
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="返利金额计算方式:" prop="calcType">
                    <el-radio
                      @change="calcTypeChange"
                      :disabled="
                        addForm.rebateTypeCode != 'THGDF' &&
                        addForm.rebateTypeCode != 'THDLF'
                      "
                      v-model="addForm.calcType"
                      label="固定金额"
                      >固定金额</el-radio
                    >
                    <el-radio
                      @change="calcTypeChange"
                      :disabled="
                        addForm.rebateTypeCode != 'THGDF' &&
                        addForm.rebateTypeCode != 'THDLF'
                      "
                      v-model="addForm.calcType"
                      label="采购价百分比"
                      >采购价百分比</el-radio
                    >
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="发放返利条件:" prop="sendFilter">
                    <el-radio :disabled="true" v-model="addForm.sendFilter" label="每台"
                      >每台</el-radio
                    >
                    <el-radio :disabled="true" v-model="addForm.sendFilter" label="达量"
                      >达量</el-radio
                    >
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="设置多档阶梯返利:" prop="isSetStage">
                    <el-radio :disabled="true" v-model="addForm.isSetStage" :label="1"
                      >是</el-radio
                    >
                    <el-radio :disabled="true" v-model="addForm.isSetStage" :label="0"
                      >否</el-radio
                    >
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="退货二次销售是否返利:" prop="refundIsCacl">
                    <el-radio v-model="addForm.refundIsCacl" :label="1">是</el-radio>
                    <el-radio v-model="addForm.refundIsCacl" :label="0">否</el-radio>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="统计提货入库返利额:" prop="isCalcEstimateAmount">
                    <el-radio
                      :disabled="true"
                      v-model="addForm.isCalcEstimateAmount"
                      :label="1"
                      >是</el-radio
                    >
                    <el-radio
                      :disabled="true"
                      v-model="addForm.isCalcEstimateAmount"
                      :label="0"
                      >否</el-radio
                    >
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="多档阶梯依据:"
                    v-if="
                      addForm.rebateTypeCode == 'THDLF' ||
                      addForm.rebateTypeCode == 'XSDLF' ||
                      addForm.rebateTypeCode == 'THJJTF'
                    "
                    prop="stageType"
                  >
                    <el-radio :disabled="true" v-model="addForm.stageType" label="提货量"
                      >提货量</el-radio
                    >
                    <el-radio :disabled="true" v-model="addForm.stageType" label="销量"
                      >销量</el-radio
                    >
                    <el-radio :disabled="true" v-model="addForm.stageType" label="提货价"
                      >提货价</el-radio
                    >
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <h3><span></span>返利商品</h3>
            <el-row
              style="margin-bottom: 8px"
              v-show="addForm.rebateTypeCode != 'ZDCMF' && !disabledForm"
            >
              <el-popover placement="bottom" width="600" v-model="goodsVisible">
                <el-input
                  v-model="goodsText"
                  type="textarea"
                  :rows="8"
                  placeholder="多个商品编码使用逗号隔开"
                  clearable
                />
                <div style="text-align: right; margin-top: 4px">
                  <el-button size="mini" type="text" @click="goodsVisible = false"
                    >取消</el-button
                  >
                  <el-button
                    type="primary"
                    :loading="saveGoodsLoading"
                    size="mini"
                    @click="saveGoods"
                    >确定</el-button
                  >
                </div>
                <el-button slot="reference">添加商品</el-button>
              </el-popover>
              <el-button
                style="margin-left: 8px"
                type="primary"
                @click="upload.open = true"
                >导入商品&返利</el-button
              >
            </el-row>

            <el-table
              ref="goodsTable"
              border
              :data="goodsTableList"
              v-show="addForm.rebateTypeCode != 'ZDCMF'"
            >
              <el-table-column label="商品" align="left" prop="sku" min-width="140">
                <template slot-scope="scope">
                  <span>{{ scope.row.skuName }}/{{ scope.row.skuNo }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="返利金额"
                min-width="180"
                align="left"
                prop="skuName"
              >
                <template slot="header" slot-scope="scope">
                  <div v-show="addForm.rebateTypeCode == 'JLF'">
                    每台返
                    <el-input
                      v-model="headerValue"
                      size="mini"
                      :min="0"
                      type="number"
                      placeholder=""
                      style="width: 110px"
                      clearable
                    />元
                    <el-button size="mini" type="text" @click="priceCopy(1)"
                      >应用</el-button
                    >
                  </div>

                  <div v-show="addForm.rebateTypeCode == 'THGDF'">
                    每台返
                    <el-input
                      v-model="headerValue2"
                      size="mini"
                      :min="0"
                      type="number"
                      placeholder=""
                      style="width: 110px"
                      clearable
                    />
                    <span v-if="addForm.calcType == '固定金额'">元</span
                    ><span v-else>%</span>
                    <el-button size="mini" type="text" @click="priceCopy(1)"
                      >应用</el-button
                    >
                  </div>

                  <div v-show="addForm.rebateTypeCode == 'THDLF'">
                    <div
                      class="table-box2"
                      v-for="(item, index) in stageInfos"
                      :key="index"
                    >
                      提货量达
                      <el-input
                        v-model="item.stage"
                        :min="0"
                        type="number"
                        placeholder=""
                        style="width: 100px"
                        size="mini"
                        clearable
                      />
                      每台返
                      <el-input
                        v-model="item.ratePrice"
                        :min="0"
                        type="number"
                        placeholder=""
                        style="width: 100px"
                        size="mini"
                        clearable
                        v-if="addForm.calcType != '固定金额'"
                      /><el-input
                        v-model="item.price"
                        :min="0"
                        type="number"
                        placeholder=""
                        style="width: 100px"
                        size="mini"
                        clearable
                        v-else
                      />
                      <span v-if="addForm.calcType == '固定金额'">元</span
                      ><span v-else>%</span>
                      <el-button
                        type="text"
                        v-show="index != 0"
                        size="mini"
                        @click="removeStage(stageInfos, index)"
                        >删除阶梯</el-button
                      >
                    </div>

                    <el-button
                      icon="el-icon-plus"
                      size="mini"
                      type="text"
                      @click="addStage(stageInfos, 1)"
                      >新增阶梯</el-button
                    >
                    <el-button size="mini" type="text" @click="priceCopy(2)"
                      >应用</el-button
                    >
                  </div>

                  <div v-show="addForm.rebateTypeCode == 'XSDLF'">
                    <div
                      class="table-box2"
                      v-for="(item, index) in stageInfos"
                      :key="index"
                    >
                      销量达
                      <el-input
                        v-model="item.stage"
                        :min="0"
                        type="number"
                        placeholder=""
                        style="width: 100px"
                        size="mini"
                        clearable
                      />
                      每台返
                      <el-input
                        v-model="item.price"
                        :min="0"
                        type="number"
                        placeholder=""
                        style="width: 100px"
                        size="mini"
                        clearable
                      />
                      元
                      <el-button
                        type="text"
                        v-show="index != 0"
                        size="mini"
                        @click="removeStage(stageInfos, index)"
                        >删除阶梯</el-button
                      >
                    </div>

                    <el-button
                      icon="el-icon-plus"
                      size="mini"
                      type="text"
                      @click="addStage(stageInfos, 1)"
                      >新增阶梯</el-button
                    >
                    <el-button size="mini" type="text" @click="priceCopy(2)"
                      >应用</el-button
                    >
                  </div>

                  <div v-show="addForm.rebateTypeCode == 'THJJTF'">
                    <div
                      class="table-box2"
                      v-for="(item, index) in stageInfos"
                      :key="index"
                    >
                      采购价
                      <el-input
                        v-model="item.stage"
                        :min="0"
                        type="number"
                        placeholder=""
                        style="width: 100px"
                        size="mini"
                        clearable
                      />
                      每台返
                      <el-input
                        v-model="item.price"
                        :min="0"
                        type="number"
                        placeholder=""
                        style="width: 100px"
                        size="mini"
                        clearable
                      />
                      元
                      <el-button
                        type="text"
                        v-show="index != 0"
                        size="mini"
                        @click="removeStage(stageInfos, index)"
                        >删除阶梯</el-button
                      >
                    </div>

                    <el-button
                      icon="el-icon-plus"
                      size="mini"
                      type="text"
                      @click="addStage(stageInfos, 1)"
                      >新增阶梯</el-button
                    >
                    <el-button size="mini" type="text" @click="priceCopy(2)"
                      >应用</el-button
                    >
                  </div>
                </template>
                <template slot-scope="scope">
                  <div v-show="addForm.rebateTypeCode == 'JLF'">
                    每台返
                    <el-input
                      v-model="scope.row.price"
                      :min="0"
                      size="mini"
                      type="number"
                      placeholder=""
                      style="width: 110px"
                      clearable
                    />元
                  </div>
                  <div v-show="addForm.rebateTypeCode == 'THGDF'">
                    每台返
                    <el-input
                      v-model="scope.row.ratePrice"
                      :min="0"
                      type="number"
                      placeholder=""
                      style="width: 110px"
                      size="mini"
                      clearable
                      v-if="addForm.calcType != '固定金额'"
                    /><el-input
                      v-model="scope.row.price"
                      :min="0"
                      type="number"
                      placeholder=""
                      style="width: 110px"
                      size="mini"
                      clearable
                      v-else
                    />
                    <span v-if="addForm.calcType == '固定金额'">元</span
                    ><span v-else>%</span>
                  </div>
                  <div v-show="addForm.rebateTypeCode == 'THDLF'">
                    <div
                      class="table-box2"
                      v-for="(item, index) in scope.row.stageInfos"
                      :key="index"
                    >
                      提货量达
                      <el-input
                        v-model="item.stage"
                        :min="0"
                        type="number"
                        placeholder=""
                        style="width: 100px"
                        size="mini"
                        clearable
                      />
                      每台返
                      <el-input
                        v-model="item.ratePrice"
                        :min="0"
                        type="number"
                        placeholder=""
                        style="width: 100px"
                        size="mini"
                        clearable
                        v-if="addForm.calcType != '固定金额'"
                      /><el-input
                        v-model="item.price"
                        :min="0"
                        type="number"
                        placeholder=""
                        style="width: 110px"
                        size="mini"
                        clearable
                        v-else
                      />
                      <span v-if="addForm.calcType == '固定金额'">元</span
                      ><span v-else>%</span>
                      <el-button
                        type="text"
                        v-show="index != 0"
                        size="mini"
                        @click="removeStage(scope.row.stageInfos, index)"
                        >删除阶梯</el-button
                      >
                    </div>

                    <el-button
                      icon="el-icon-plus"
                      size="mini"
                      type="text"
                      @click="addStage(scope.row.stageInfos)"
                      >新增阶梯</el-button
                    >
                  </div>
                  <div v-show="addForm.rebateTypeCode == 'XSDLF'">
                    <div
                      class="table-box2"
                      v-for="(item, index) in scope.row.stageInfos"
                      :key="index"
                    >
                      销量达
                      <el-input
                        v-model="item.stage"
                        :min="0"
                        type="number"
                        placeholder=""
                        style="width: 100px"
                        size="mini"
                        clearable
                      />
                      每台返
                      <el-input
                        v-model="item.price"
                        :min="0"
                        type="number"
                        placeholder=""
                        style="width: 100px"
                        size="mini"
                        clearable
                      />
                      元
                      <el-button
                        type="text"
                        v-show="index != 0"
                        size="mini"
                        @click="removeStage(scope.row.stageInfos, index)"
                        >删除阶梯</el-button
                      >
                    </div>

                    <el-button
                      icon="el-icon-plus"
                      size="mini"
                      type="text"
                      @click="addStage(scope.row.stageInfos)"
                      >新增阶梯</el-button
                    >
                  </div>
                  <div v-show="addForm.rebateTypeCode == 'THJJTF'">
                    <div
                      class="table-box2"
                      v-for="(item, index) in scope.row.stageInfos"
                      :key="index"
                    >
                      采购价达
                      <el-input
                        v-model="item.stage"
                        :min="0"
                        type="number"
                        placeholder=""
                        style="width: 100px"
                        size="mini"
                        clearable
                      />
                      每台返
                      <el-input
                        v-model="item.price"
                        :min="0"
                        type="number"
                        placeholder=""
                        style="width: 100px"
                        size="mini"
                        clearable
                      />
                      元
                      <el-button
                        type="text"
                        v-show="index != 0"
                        size="mini"
                        @click="removeStage(scope.row.stageInfos, index)"
                        >删除阶梯</el-button
                      >
                    </div>

                    <el-button
                      icon="el-icon-plus"
                      size="mini"
                      type="text"
                      @click="addStage(scope.row.stageInfos)"
                      >新增阶梯</el-button
                    >
                  </div>
                  <el-button
                    style="float: right"
                    size="mini"
                    type="text"
                    @click="deleteGoods(scope.$index)"
                    >删除此商品</el-button
                  >
                </template>
              </el-table-column>
            </el-table>

            <div v-show="addForm.rebateTypeCode == 'ZDCMF'" style="margin: 8px 0 36px 0">
              输入串码列表：<br /><el-input
                v-model="addForm.skuSn"
                type="textarea"
                :rows="8"
                placeholder="最多支持2000个串码，支持逗号和换行分隔"
                style="width: 600px"
                clearable
              /><br />
              返利金额<br />
              <el-input
                v-model="addForm.skuSnPrice"
                type="text"
                placeholder="每台返，2位小数"
                style="width: 200px"
                clearable
              />
            </div>

            <h3><span></span>官方返利资料</h3>
            <div class="color-r">
              上传官方提供的返利政策图片或文件（上限最多5个文件，最大20M）
            </div>
            <el-upload
              class="upload-demo"
              :action="fileAction"
              :on-preview="handlePreview"
              :before-remove="beforeRemove"
              :on-remove="handleRemove"
              :on-success="handleFileSuccess2"
              :headers="upload.headers"
              :before-upload="beforeAvatarUpload"
              :disabled="disabledForm"
              multiple
              :limit="5"
              :on-exceed="handleExceed"
              :file-list="fileList"
            >
              <el-button size="small" type="primary" :disabled="disabledForm"
                >点击上传</el-button
              >
            </el-upload>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="日志" name="2">
          <el-table ref="logTable" border :data="historyLogTableList">
            <el-table-column
              label="操作步骤"
              min-width="140"
              align="left"
              prop="logType"
            />
            <el-table-column label="操作描述" min-width="140" align="left" prop="logMsg">
              <template slot-scope="scope">
                <span v-html="scope.row.logMsg"></span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作人"
              min-width="100"
              align="left"
              prop="createBy"
            />
            <el-table-column
              label="操作时间"
              min-width="90"
              align="left"
              prop="createTime"
            />
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button
          :loading="saveLoading"
          type="primary"
          @click="saveDept"
          v-show="!disabledForm"
          >提交</el-button
        >
        <el-button @click="open2 = false">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="商品导入" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div> -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getChannelList } from "@/api/bizMonitor/index";
import { getBrandNameList, getList } from "@/api/goods/index";
import {
  getActivitieList,
  activitieSuppliers,
  activitieAdd,
  activitieUpdate,
  activitieLogs,
  activitieAuditSubmit,
  activitieAuditCancel,
  activitieRepUpdate,
  activitieDown,
  activitieDetail,
  activitieUpdateDetail,
} from "@/api/activitie/index";
import LoadMoreSelect from "@/components/LoadMoreSelect/index";
import { getToken } from "@/utils/auth";

export default {
  name: "ActivitieIndex",
  dicts: ["sys_yes_no", "sys_commerce_platform"],
  components: {
    LoadMoreSelect,
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      spuList: [],
      historyTableList: [],
      historyLogTableList: [],
      fileAction: process.env.VUE_APP_BASE_API_NEW + "/activitie/upload/file",
      goodsTableList: [],
      goodsVisible: false,
      saveGoodsLoading: false,
      headerValue: "",
      headerValue2: "",
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API_NEW + "/activitie/analysis/sku/file",
      },
      stageInfos: [
        {
          price: 0,
          ratePrice: 0,
          stage: 1,
        },
        {
          price: 0,
          ratePrice: 0,
          stage: 1,
        },
      ],
      detailQuery: {
        total: 0,
        pageSize: 10,
        pageNum: 1,
        dates: [],
      },
      detailTableList: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open2: false,
      goodsOpen: false,
      channelTableLoading: false,
      activeName: "1",
      rebateTypeCodeList: [
        { code: "JLF", name: "激励返" },
        { code: "THGDF", name: "提货固定返" },
        { code: "THDLF", name: "提货达量返" },
        { code: "XSDLF", name: "销售达量返" },
        { code: "THJJTF", name: "提货价阶梯返" },
        { code: "ZDCMF", name: "指定串码返利" },
      ],
      statusList: [
        { code: 0, name: "待提交" },
        { code: 1, name: "待审批" },
        { code: 2, name: "审批打回" },
        { code: 3, name: "启用" },
        { code: 4, name: "下线" },
        { code: 5, name: "挂起" },
        { code: 6, name: "变更待审批" },
        { code: 7, name: "变更审批打回" },
        { code: 8, name: "变更待提交" },
      ],
      rebateSendStatusList: [
        { code: 0, name: "未发放返利" },
        { code: 1, name: "发放返利中" },
        { code: 2, name: "已完成返利发放" },
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        activitieName: "",
        activitieCode: "",
        brandCodes: [],
        endDate: "",
        rebateSendStatus: "",
        rebateTypeCode: "",
        skuNos: "",
        skuNo: "",
        startDate: "",
        status: "",
        suppliers: [],
        dateRange: [],
      },
      addForm: {
        activitieCode: "",
        activitieName: "",
        brandCode: "",
        brandName: "",
        calcType: "固定金额",
        endTime: "",
        isSetStage: 0,
        rebateSendStatus: "",
        rebateTypeCode: "JLF",
        refundIsCacl: 0,
        salePoint: "销售出库",
        saleRabe: 100,
        sendFilter: "每台",
        skuSn: "",
        stageType: "提货量",
        startTime: "",
        status: 0,
        dateRange: [],
        channels: [],
        suppliers: [],
        isCalcEstimateAmount: 0,
      },
      dateRange: [],
      fileList: [],
      goodsText: "",
      bindForm: {
        bindSkuNo: "",
      },
      // 表单参数
      form: {},
      expandRowKeys: [],
      treeKey: "",
      isExpand: false,
      brandNameList: [],
      saveLoading: false,
      bindModal: {
        open: false,
        id: "",
      },
      timer: null,
      chartLading: true,
      loadDataStatus: true,
      tableHeight: "auto",
      channelList: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近三天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近半个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      pickerOptions2: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.67e7 ;
        },
        shortcuts: [
          {
            text: "最近三天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近半个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      today: "",
      expandText: "全部展开",
      suppliersList: [],
      disabledForm: false,
    };
  },
  watch: {
    showSearch(n, _) {
      this.$nextTick(() => {
        const height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 210;
        this.tableHeight = height + "px";
      });
    },
  },
  computed: {
    roles() {
      return this.$store.getters.roles;
    },
    userName() {
      return this.$store.getters.name;
    },
  },
  created() {
    this.treeKey = new Date();

    if (localStorage.getItem("activitie-query")) {
      this.queryParams = JSON.parse(localStorage.getItem("activitie-query"));
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
    }

    // 获取当前月的第一天
    const currentMonthFirstDay = new Date();
    currentMonthFirstDay.setDate(1);

    // 获取当前月的最后一天
    const currentMonthLastDay = new Date();
    currentMonthLastDay.setMonth(currentMonthLastDay.getMonth() + 1);
    currentMonthLastDay.setDate(0);

    const year = currentMonthFirstDay.getFullYear();
    const month =
      currentMonthFirstDay.getMonth() + 1 < 10
        ? "0" + (currentMonthFirstDay.getMonth() + 1)
        : currentMonthFirstDay.getMonth() + 1;
    const day =
      currentMonthFirstDay.getDate() < 10
        ? "0" + currentMonthFirstDay.getDate()
        : currentMonthFirstDay.getDate();
    this.queryParams.dateRange = [];
    this.queryParams.dateRange[0] = year + "-" + month + "-" + day;
    const year2 = currentMonthLastDay.getFullYear();
    const month2 =
      currentMonthLastDay.getMonth() + 1 < 10
        ? "0" + (currentMonthLastDay.getMonth() + 1)
        : currentMonthLastDay.getMonth() + 1;
    const day2 =
      currentMonthLastDay.getDate() < 10
        ? "0" + currentMonthLastDay.getDate()
        : currentMonthLastDay.getDate();
    this.queryParams.dateRange[1] = year2 + "-" + month2 + "-" + day2;

    this.getList();
    this.getBrandNameList();
  },
  mounted() {},
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.annexs = [];
      fileList.forEach((item) => {
        this.annexs.push({
          annexName: item.name,
          annexPath: item.path ? item.path : item.response.data,
        });
      });
      console.log(this.annexs);
    },
    brandChange(val) {
      const brandCodes = this.brandNameList.filter((sp) => {
        return sp.brandName == val;
      });
      const brandCode = brandCodes[0].brandCode;

      this.getConfigKey("activitie." + brandCode)
        .then((res) => {
          this.addForm.suppliers = [];
          if (res.code == 200 && res.msg) {
            this.addForm.suppliers = res.msg.split(",");
          }
        })
        .catch((err) => {
          this.addForm.suppliers = [];
        });
    },
    calcTypeChange(val) {
      this.goodsTableList.forEach((item) => {
        item.price = "";
        item.ratePrice = "";
        item.stageInfos.forEach((data, i) => {
          data.price = "";
          data.ratePrice = "";
        });
      });
    },
    handlePreview(file) {
      console.log(file);
      if (file.response && file.response.data) {
        window.open(
          "https://newfirst.oss-cn-shanghai.aliyuncs.com/" + file.response.data
        );
      } else {
        window.open("https://newfirst.oss-cn-shanghai.aliyuncs.com/" + file.path);
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      // return this.$confirm(`确定移除 ${ file.name }？`).then(res=>{
      // console.log(3)
      // });
      return true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      response.data.forEach((item) => {
        let status = true;
        this.goodsTableList.forEach((it) => {
          if (it.skuNo == item.skuNo) {
            status = false;
          }
        });
        if (status) {
          this.goodsTableList.push(item);
        }
      });
      this.$refs.upload.clearFiles();
    },
    handleFileSuccess2(response, file, fileList) {
      console.log(fileList);
      this.annexs = [];
      fileList.forEach((item) => {
        this.annexs.push({
          annexName: item.name,
          annexPath: item.path ? item.path : item.response.data,
        });
      });
    },
    beforeAvatarUpload(file) {
      return new Promise((resolve, reject) => {
        console.log(file.size / 1024 / 1024);
        const isLt1M = file.size / 1024 / 1024 > 20;
        if (isLt1M) {
          this.$message.error("上传文件大小不能超过 20MB!");
          reject();
        }

        resolve();
      });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    addGoods() {
      // this.goodsTableList.push({})
    },
    deleteGoods(index) {
      this.goodsTableList.splice(index, 1);
    },
    priceCopy(type) {
      if (type == 1) {
        this.goodsTableList.forEach((item) => {
          if(this.addForm.rebateTypeCode == 'JLF'){
            item.price = this.headerValue;
          } else {
            if (this.addForm.calcType == "固定金额") {
              item.price = this.headerValue2;
            } else {
              item.ratePrice = this.headerValue2;
            }
          }
        });
      } else {
        this.goodsTableList.forEach((item) => {
          item.stageInfos.forEach((data, i) => {
            data.price = this.stageInfos[i].price;
            data.ratePrice = this.stageInfos[i].ratePrice;
            data.stage = this.stageInfos[i].stage;
          });
        });
      }
    },
    saveGoods() {
      this.saveGoodsLoading = true;
      getList({ sku: this.goodsText })
        .then((res) => {
          if (res.rows.length != 0) {
            res.rows.forEach((item) => {
              let status = true;
              this.goodsTableList.forEach((it) => {
                if (it.skuNo == item.sku) {
                  status = false;
                }
              });
              if (status) {
                this.goodsTableList.push({
                  price: "",
                  ratePrice: "",
                  skuName: item.skuName,
                  skuNo: item.sku,
                  stageInfos: [
                    {
                      price: 0,
                      ratePrice: 0,
                      stage: 1,
                    },
                    {
                      price: 0,
                      ratePrice: 0,
                      stage: 1,
                    },
                  ],
                });
              }
            });
          }

          this.goodsVisible = false;
          this.saveGoodsLoading = false;
        })
        .catch((err) => {});
    },
    expandChange() {
      this.treeKey = new Date();
      this.isExpand = !this.isExpand;
      this.expandText == "全部展开"
        ? (this.expandText = "全部收起")
        : (this.expandText = "全部展开");
    },
    getBrandNameList() {
      getBrandNameList().then((res) => {
        this.brandNameList = res.data;
      });
      activitieSuppliers().then((res) => {
        this.suppliersList = res.data.supplierListResDTOS;
      });
      getChannelList().then((res) => {
        this.channelList = res.data || [];
      });
    },
    rowStyle({ row, rowIndex }) {
      if (row.skuName == "合计" || row.skuName == "总计") {
        return { background: "#f5f7fa" };
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.activitieCode);
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    submitItem(row) {
      this.$confirm("确定要提交审核吗？", "提示", { type: "warning" }).then(() => {
        this.loading = true;
        activitieAuditSubmit({ activitieCode: row.activitieCode })
          .then((res) => {
            if (res.status == 200) {
              this.$message.success("提交审核成功");
              this.getList();
            }
            this.loading = false;
          })
          .catch((_) => {
            this.loading = false;
          });
      });
    },
    recallItem(row) {
      this.$confirm("撤回后审批人将无法审批当前返利活动，确定要撤回吗？", "提示", {
        type: "warning",
      }).then(() => {
        this.loading = true;
        activitieAuditCancel({ activitieCode: row.activitieCode })
          .then((res) => {
            if (res.status == 200) {
              this.$message.success("撤回成功");
              this.getList();
            }
            this.loading = false;
          })
          .catch((_) => {
            this.loading = false;
          });
      });
    },
    addStage(stageInfos, type) {
      stageInfos.push({
        price: 0,
        ratePrice: 0,
        stage: 1,
      });
      if (type == 1) {
        this.goodsTableList.forEach((item) => {
          item.stageInfos.push({
            price: 0,
            ratePrice: 0,
            stage: 1,
          });
        });
      }
    },
    removeStage(stageInfos, index) {
      stageInfos.splice(index, 1);
    },
    /** 查询岗位列表 */
    getList() {
      const data = { ...this.queryParams };
      if (data.dateRange && data.dateRange.length != 0) {
        data.startDate = data.dateRange[0];
        data.endDate = data.dateRange[1];
      } else {
        data.startDate = "";
        data.endDate = "";
      }

      localStorage.setItem("activitie-query", JSON.stringify(data));

      this.loading = true;
      getActivitieList(data).then((response) => {
        response.data.activitieListResDTOS.forEach((item) => {
          item.ssId = item.activitieCode + "/" + item.activitieStatus;
          item.activitieListSkuDTOList.forEach((it) => {
            it.ssId = item.activitieCode + "/" + it.skuNo;
          });
        });
        this.postList = response.data.activitieListResDTOS;
        this.total = response.data.total;
        this.loading = false;

        this.$nextTick(() => {
          const height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 210;
          this.tableHeight = height + "px";
        });
      });
    },
    handleOff(row) {
      this.$confirm("下线后返利活动将失效，确认要执行吗？", "提示", {
        type: "warning",
      }).then(() => {
        this.loading = true;
        activitieDown({ activitieCode: row.activitieCode })
          .then((res) => {
            if (res.status == 200) {
              this.$message.success("下线成功");
              this.getList();
            }
            this.loading = false;
          })
          .catch((_) => {
            this.loading = false;
          });
      });
    },
    handleEdit(row, type) {
      if (type == 2) {
        this.$router.push({
          path: "/activitie/detail",
          query: { activitieCode: row.activitieCode },
        });
      } else if (type == 4) {
        activitieDetail({ activitieCode: row.activitieCode }).then((res) => {
          this.addForm = Object.assign(
            this.addForm,
            JSON.parse(JSON.stringify(res.data))
          );
          this.addForm.dateRange = [this.addForm.startTime, this.addForm.endTime];
          this.annexs = res.data.annexs;
          this.goodsTableList = res.data.skuInfos || [];
          this.fileList = [];
          res.data.annexs.forEach((item) => {
            this.fileList.push({ name: item.annexName, path: item.annexPath });
          });
          this.activeName = "1";
          // if(type==4){
          this.disabledForm = false;
          this.title = "变更返利活动";
          // }
          this.open2 = true;
        });
      } else if (type == 3 || type == 1) {
        activitieUpdateDetail({ activitieCode: row.activitieCode }).then((res) => {
          this.addForm = Object.assign(
            this.addForm,
            JSON.parse(JSON.stringify(res.data))
          );
          this.addForm.dateRange = [this.addForm.startTime, this.addForm.endTime];
          this.annexs = res.data.annexs;
          this.goodsTableList = res.data.skuInfos || [];
          this.fileList = [];
          res.data.annexs.forEach((item) => {
            this.fileList.push({ name: item.annexName, path: item.annexPath });
          });
          this.activeName = "1";
          if (type == 1) {
            this.disabledForm = false;
            this.title = "编辑返利活动";
          } else if (type == 3) {
            this.disabledForm = false;
            this.title = "变更返利活动";
          }
          this.open2 = true;
        });
      }

      activitieLogs({ activitieCode: row.activitieCode }).then((res) => {
        this.historyLogTableList = res.data.activitieLogResDTOList;
      });
    },
    fltypeChange(value) {
      if (value == "JLF") {
        this.addForm.calcType = "固定金额";
        this.addForm.sendFilter = "每台";
        this.addForm.isSetStage = 0;
        this.addForm.isCalcEstimateAmount = 0;
      }

      if (value == "THGDF") {
        this.addForm.calcType = "采购价百分比";
        this.addForm.sendFilter = "每台";
        this.addForm.isSetStage = 0;
        this.addForm.isCalcEstimateAmount = 1;
      }

      if (value == "THDLF") {
        this.addForm.stageType = "提货量";
        this.addForm.calcType = "固定金额";
        this.addForm.sendFilter = "达量";
        this.addForm.isSetStage = 1;
        this.addForm.refundIsCacl = 0;
        this.addForm.isCalcEstimateAmount = 1;
      }
      if (value == "XSDLF") {
        this.addForm.stageType = "销量";
        this.addForm.calcType = "固定金额";
        this.addForm.sendFilter = "达量";
        this.addForm.isSetStage = 1;
        this.addForm.refundIsCacl = 0;
        this.addForm.isCalcEstimateAmount = 0;
      }
      if (value == "THJJTF") {
        this.addForm.stageType = "提货价";
        this.addForm.calcType = "固定金额";
        this.addForm.sendFilter = "每台";
        this.addForm.isSetStage = 1;
        this.addForm.refundIsCacl = 0;
        this.addForm.isCalcEstimateAmount = 0;
      }
      if (value == "ZDCMF") {
        this.addForm.calcType = "固定金额";
        this.addForm.sendFilter = "每台";
        this.addForm.isSetStage = 0;
        this.addForm.isCalcEstimateAmount = 0;
      }
    },
    // 表单重置
    reset() {
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.addForm = {
        activitieCode: "",
        activitieName: "",
        brandCode: "",
        brandName: "",
        calcType: "固定金额",
        endTime: "",
        isSetStage: 0,
        rebateSendStatus: "",
        rebateTypeCode: "JLF",
        refundIsCacl: 0,
        salePoint: "销售出库",
        saleRabe: 100,
        sendFilter: "每台",
        skuSn: "",
        stageType: "提货量",
        startTime: "",
        status: "",
        dateRange: [],
        channels: [],
        suppliers: [],
        isCalcEstimateAmount: 0,
      };

      this.historyLogTableList = [];
      this.annexs = [];
      this.fileList = [];
      this.goodsTableList = [];
      this.activeName = "1";
      this.open2 = true;
      this.disabledForm = false;
      this.title = "新建返利活动";
      this.$nextTick(() => {
        if (this.$refs["addForm"]) {
          this.$refs["addForm"].clearValidate();
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 导出按钮操作 */
    handleExport() {
      const data = { ...this.queryParams };
      if (data.dateRange && data.dateRange.length != 0) {
        data.startDate = data.dateRange[0];
        data.endDate = data.dateRange[1];
      } else {
        data.startDate = "";
        data.endDate = "";
      }
      delete data.pageNum;
      delete data.pageSize;
      this.newDownload("activitie/export", data, `返利活动_${new Date().getTime()}.xlsx`);
    },
    handlePause2(row) {
      const data = {
        activieCodes: row && row.activitieCode ? [row.activitieCode] : this.ids,
      };
      this.newDownload(
        "activitie/rebate/export",
        data,
        `返利订单_${new Date().getTime()}.xlsx`
      );
    },
    saveDept() {
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          const suppliers = [];
          if(this.addForm.suppliers){
            this.addForm.suppliers.forEach((item) => {
              const sp = this.suppliersList.filter((sp) => {
                return sp.supplierCode == item;
              });
              suppliers.push({
                supplierCode: sp[0].supplierCode,
                supplierName: sp[0].supplierName,
              });
            });
          }
          

          const channels = [];
          if(this.addForm.channels){
            this.addForm.channels.forEach((item) => {
              const fl = this.channelList.filter((sp) => {
                return sp.channelCode == item;
              });
              channels.push({
                channelCode: fl[0].channelCode,
                channelName: fl[0].channelName,
              });
            });
          }
          
          const brandCodes = this.brandNameList.filter((sp) => {
            return sp.brandName == this.addForm.brandName;
          });

          this.addForm.brandCode = brandCodes[0].brandCode;

          const datas = JSON.parse(JSON.stringify(this.addForm));
          const goodsTableList = JSON.parse(JSON.stringify(this.goodsTableList));

          let goodsTableListStatus = true;
          if (
            datas.rebateTypeCode != "THDLF" &&
            datas.rebateTypeCode != "XSDLF" &&
            datas.rebateTypeCode != "THJJTF" &&
            datas.rebateTypeCode != "ZDCMF"
          ) {
            goodsTableList.forEach((item) => {
              delete item.stageInfos;
              if (datas.rebateTypeCode == "JLF") {
                if (item.price <= 0 || item.price == "") {
                  goodsTableListStatus = false;
                }
              }
              if (datas.rebateTypeCode == "THGDF") {
                if (this.addForm.calcType == "固定金额") {
                  if (item.price <= 0 || item.price == "") {
                    goodsTableListStatus = false;
                  }
                } else {
                  if (item.ratePrice <= 0 || item.ratePrice == "") {
                    goodsTableListStatus = false;
                  }
                }
              }
            });
          } else {
            goodsTableList.forEach((item) => {
              if (datas.rebateTypeCode != "ZDCMF") {
                item.stageInfos.forEach((it) => {
                  if (datas.rebateTypeCode != "THDLF") {
                    if (
                      it.price <= 0 ||
                      it.price == "" ||
                      it.stage <= 0 ||
                      it.stage == ""
                    ) {
                      goodsTableListStatus = false;
                    }
                  } else {
                    if (it.stage <= 0 || it.stage == "") {
                      goodsTableListStatus = false;
                    }
                  }
                });
              }
            });
            if (datas.rebateTypeCode == "ZDCMF") {
              if (datas.skuSn == "" || datas.skuSnPrice == "") {
                goodsTableListStatus = false;
              }
            }
          }
          if (!goodsTableListStatus) {
            this.$message.warning("请填写完整返利商品和金额");
            return false;
          }

          datas.channels = channels;
          datas.suppliers = suppliers;
          datas.skuInfos = goodsTableList;
          datas.startTime = this.addForm.dateRange[0];
          datas.endTime = this.addForm.dateRange[1];
          datas.annexs = this.annexs;

          if (this.annexs.length == 0) {
            this.$message.warning("请上传官方返利资料！");
            return false;
          }

          this.saveLoading = true;
          if (this.title == "编辑返利活动") {
            activitieUpdate(datas)
              .then((res) => {
                this.saveLoading = false;
                if (res.status == "200") {
                  this.$message.success("编辑成功");
                  this.open2 = false;
                  this.getList();
                }
              })
              .catch((err) => {
                this.saveLoading = false;
              });
          } else if (this.title == "新建返利活动") {
            activitieAdd(datas)
              .then((res) => {
                this.saveLoading = false;
                if (res.status == "200") {
                  this.$message.success("新建成功");
                  this.open2 = false;
                  this.getList();
                }
              })
              .catch((err) => {
                this.saveLoading = false;
              });
          } else if (this.title == "变更返利活动") {
            activitieRepUpdate(datas)
              .then((res) => {
                this.saveLoading = false;
                if (res.status == "200") {
                  this.$message.success("变更成功");
                  this.open2 = false;
                  this.getList();
                }
              })
              .catch((err) => {
                this.saveLoading = false;
              });
          }
        }
      });
    },
    /** 下载模板操作 */
    importTemplate() {
      window.open(
        "https://newfirst.oss-cn-shanghai.aliyuncs.com/activitie/temp/%E8%BF%94%E5%88%A9%E5%95%86%E5%93%81%E6%A8%A1%E7%89%88.xlsx"
      );
      // this.newDownload(
      //   "whole_goods/importTemplate",
      //   {},
      //   `goods_template_${new Date().getTime()}.xlsx`
      // );
    },
  },
};
</script>
<style scoped lang="scss">
.color-r {
  color: #e6a23c;
}
.charts-box {
  height: 350px;
  margin-top: 30px;
}
.erpPrice > span {
  color: #409eff;
}
.iconEdit {
  cursor: pointer;
}
.app-container {
  padding-bottom: 60px;
}

.table-dp {
  display: flex;
  align-items: center;
  color: #999;
  span {
    color: #333;
  }
  .colorRed {
    color: red;
  }
}
.rate-span {
  margin-left: 5px;
  color: #999;
}
.dept-box {
  height: 40px;
  line-height: 40px;
  border-bottom: solid 1px #dfe6ec;
}

.el-tab-pane {
  .pagination-container {
    margin-bottom: 20px;
  }
}
.channel-box {
  margin: 5px 0;
  span {
    margin-right: 5px;
  }
}
.change-input {
  color: red;
  ::v-deep .el-input__inner {
    color: red;
  }
}
.up-png {
  width: 12px;
}
.colorG {
  color: #999;
}
.table-box2 {
  margin: 5px;
}

h3 {
  font-weight: bold;
  display: flex;
  align-items: center;
  margin-top: 36px;
  span {
    display: block;
    width: 2px;
    height: 14px;
    background: #f56c6c;
    margin-right: 6px;
  }
}
</style>
