<template>
  <div class="yqshop-wrapper">
    <bread-crumb
      :curmbFirst="curmbFirst"
      :curmbSecond="curmbSecond"
    ></bread-crumb>
    <div class="yqshop-content screenSet" id="screenSet">
      <div class="header-title">商品管理</div>
      <el-form
        ref="searchForm"
        :model="searchForm"
        label-width="100px"
        label-suffix=":"
        :inline="true"
      >
        <el-row :gutter="30" type="flex" style="margin-top: 10px">
          <el-col :span="6">
            <el-form-item label="商品名称">
              <el-input
                v-model="searchForm.goodsName"
                size="small"
                placeholder="请输入商品名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品ID">
              <el-input
                v-model="id"
                size="small"
                placeholder="请输入商品ID"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
                  <el-form-item label="商品类型">
                    <el-select
                        v-model="searchForm.goodsType"
                        placeholder="请选择商品类型"
                        size="small"
                        clearable>
                      <el-option
                          v-for="(item,index) in goodsTypes"
                          :key="index"
                          :label="item.categoryName"
                          :value="item.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                    </el-col> -->
        </el-row>
        <el-row :gutter="30" type="flex" style="margin-top: 10px">
          <el-col :span="6">
            <el-form-item label="分佣方式" v-if="commissionFlag == 2">
              <el-select
                v-model="searchForm.commissionType"
                placeholder="请选择分佣方式"
                size="small"
                clearable
              >
                <el-option
                  v-for="item in commissionTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="药代分佣方式" v-if="commissionFlag == 2">
              <el-select
                v-model="searchForm.proxyCommissionType"
                placeholder="请选择分佣方式"
                size="small"
                clearable
              >
                <el-option
                  v-for="item in commissionTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售方式" v-if="commissionFlag == 2">
              <el-select
                v-model="searchForm.saleType"
                placeholder="请选择销售方式"
                size="small"
                clearable
              >
                <el-option
                  v-for="item in saleTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: right">
            <el-button type="primary" size="small" @click="searchList"
              >查询</el-button
            >
            <el-button
              type="default"
              size="small"
              @click="resetForm"
              style="margin-left: 0"
              >重置</el-button
            >
          </el-col>
        </el-row>

        <el-row :gutter="30" type="flex" style="margin-top: 10px">
          <el-col :span="12">
            <el-button type="primary" size="small" @click="batchOpt('on')"
              >批量上架</el-button
            >
            <el-button type="primary" size="small" @click="batchOpt('off')"
              >批量下架</el-button
            >
          </el-col>

          <el-col :span="12" style="text-align: right">
            <el-button
              v-if="commissionFlag == 2"
              type="primary"
              size="small"
              @click="batchSetPrice()"
              :disabled="tableData.length == 0"
              >批量设置分佣</el-button
            >
            <el-button
              type="primary"
              size="small"
              @click="exportOpt"
              :disabled="tableData.length == 0"
              >批量导出商品</el-button
            >
            <el-button
              v-if="isSSO"
              type="primary"
              size="small"
              @click="batchOpt(3)"
              >批量导入商品</el-button
            >
            <el-button type="primary" size="small" @click="edit('add')"
              >新建单个商品</el-button
            >
          </el-col>
        </el-row>
      </el-form>
      <el-table
        ref="multipleTable"
        :data="tableData"
        class="item-table"
        style="width: 100%; margin-top: 10px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" fixed width="55"> </el-table-column>
        <el-table-column
          prop="goodsId"
          label="商品ID"
          width="120"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="goodsName"
          label="商品名称"
          width="160"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="medicationName"
          label="药品名称"
          width="160"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="goodsCategoryStrArr"
          label="商品分类"
          width="160"
          align="center"
        >
          <template v-slot="scope">
            <p
              v-for="(item, index) in scope.row.goodsCategoryStrArr"
              :key="index"
            >
              {{ item }}
            </p>
          </template>
        </el-table-column>
        <el-table-column
          prop="medicalCategoryStrArr"
          label="药品分类"
          width="100"
          align="center"
        >
          <template v-slot="scope">
            <span>{{ handleTableArry(scope.row.medicalCategoryStrArr) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="商品状态"
          width="100"
          align="center"
        >
          <template v-slot="scope">
            <span>{{ rangeStatus_filter(scope.row.goodsStatus) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsHisStock"
          label="商品总库存"
          width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="quantityOfSale"
          label="有效销量"
          width="120"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="quantityOfUnPaidSale"
          label="待付款销量"
          width="120"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="size" label="规格" width="120" align="center">
        </el-table-column>
        <el-table-column
          prop="costPrice"
          label="价格"
          width="120"
          align="center"
        >
          <template v-slot="scope">
            <span>{{ rangePrice_filter(scope.row.costPrice) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="realCostPrice"
          label="成本价"
          width="120"
          align="center"
        >
          <template v-slot="scope">
            <span>{{ rangePrice_filter(scope.row.realCostPrice) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="commissionType"
          v-if="commissionFlag == 2"
          label="分佣方式"
          width="150"
          align="center"
        >
          <template v-slot="scope">
            <span>{{
              commissionTypeFormat_filter(scope.row.commissionType)
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="commissionPrice"
          v-if="commissionFlag == 2"
          label="商品分佣"
          width="150"
          align="center"
        >
          <template v-slot="scope">
            <span v-if="scope.row.commissionType == 1"
              >{{ priceNum_filter(scope.row.commissionPrice) }}%</span
            >
            <span v-if="scope.row.commissionType == 2"
              >{{ priceNum_filter(scope.row.commissionPrice) }}元</span
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="commissionType"
          label="药代分佣方式"
          width="120"
          align="center"
        >
          <template v-slot="scope">
            <span>{{
              commissionTypeFormat_filter(scope.row.proxyCommissionType)
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="commissionPrice"
          label="药代分佣"
          width="120"
          align="center"
        >
          <template v-slot="scope">
            <span v-if="scope.row.proxyCommissionType == 1"
              >{{ priceNum_filter(scope.row.proxyCommissionPrice) }}%</span
            >
            <span v-if="scope.row.proxyCommissionType == 2"
              >{{ priceNum_filter(scope.row.proxyCommissionPrice) }}元</span
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="saleTypeStr"
          label="销售方式"
          width="170"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="saleTime"
          label="发布时间"
          width="170"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="modifiedIdStr"
          label="最近操作人"
          width="170"
          align="center"
        >
          <template v-slot="scope">
            <span>{{ scope.row.modifiedIdStr || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="modifiedTime"
          label="最近操作时间"
          width="170"
          align="center"
        >
          <template v-slot="scope">
            <span>{{ scope.row.modifiedTime || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template v-slot="scope">
            <div v-if="scope.row.commissionFlag == 2">
              <el-button
                @click="setPrice(scope.row, false)"
                type="text"
                size="small"
                >设置分佣</el-button
              >
            </div>
            <div v-if="scope.row.goodsStatus == 0">
              <el-button @click="edit(scope.row)" type="text" size="small"
                >编辑</el-button
              >
              <el-button
                @click="shelfOpt(scope.row, 2)"
                type="text"
                size="small"
                >上架销售</el-button
              >
              <!-- <el-button @click="shelfOpt(scope.row,3)" type="text" size="small">删除</el-button> -->
            </div>
            <div v-if="scope.row.goodsStatus == 1">
              <el-button @click="edit(scope.row)" type="text" size="small"
                >编辑</el-button
              >
              <el-button
                @click="shelfOpt(scope.row, 1)"
                type="text"
                size="small"
                >下架</el-button
              >
            </div>
            <div v-if="scope.row.goodsStatus == 2">
              <el-button @click="edit(scope.row)" type="text" size="small"
                >编辑</el-button
              >

              <el-button
                @click="shelfOpt(scope.row, 2)"
                type="text"
                size="small"
                >上架销售</el-button
              >
              <!-- <el-button @click="shelfOpt(scope.row,3)" type="text" size="small">删除</el-button> -->
            </div>
            <div v-if="scope.row.goodsStatus == 3">
              <!-- <el-button @click="edit(scope.row)" type="text" size="small">编辑</el-button>
                    <el-button @click="shelfOpt(scope.row,1)" type="text" size="small">下架</el-button>
                    <el-button @click="shelfOpt(scope.row,2)" type="text" size="small">上架销售</el-button>
                    <el-button @click="shelfOpt(scope.row,3)" type="text" size="small">删除</el-button> -->
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleNumChange"
          :current-page="searchForm.pageNo"
          :page-sizes="[10, 30, 50, 100]"
          :page-size="searchForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalRows"
        ></el-pagination>
      </div>
    </div>
    <el-dialog title="批量导入" v-model="batchDialog" width="30%" center>
      <el-dialog
        width="30%"
        title="导入失败原因"
        v-model="innerVisible"
        append-to-body
      >
        <div class="upload-error">
          <div
            class="error-tem"
            style="padding: 5px"
            v-for="(item, index) in validateFailedList"
            :key="index"
          >
            {{ '第' + item.rowNumber + '行：'
            }}{{ item.validateResultList.join(',') }}
          </div>
        </div>
      </el-dialog>
      <div class="batch-dia">
        <div class="batch-dia-item">
          <span class="s-l">1、下载模板</span>
          <span class="s-r" @click="uploadTemp"
            ><el-icon><el-icon-upload /></el-icon>下载</span
          >
        </div>
        <div class="batch-dia-item">
          <span class="s-l">2、根据模板填写信息</span>
        </div>
        <div class="batch-dia-item">
          <span class="s-l">3、上传文件</span>
          <span class="s-r">
            <el-upload
              class="upload-demo"
              action="#"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :before-upload="getBatchUpload"
              multiple
              :limit="1"
              :file-list="fileList"
            >
              <el-icon><el-icon-upload /></el-icon>上传
            </el-upload>
          </span>
        </div>
      </div>
      <template v-slot:footer>
        <span class="dialog-footer" style="text-align: right">
          <!-- <el-button @click="centerDialogVisible = false">取 消</el-button> -->
          <el-button type="primary" @click="batchDialog = false"
            >完成</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 设置分佣 -->
    <el-dialog title="店铺设置分佣" v-model="setPriceVisible" width="55%">
      <!--            <el-row :gutter="30" class="row search" type="flex" style="margin-bottom:0;">-->
      <el-form
        ref="setPriceForm"
        :rules="setPriceRules"
        :model="setPriceForm"
        label-width="250px"
        label-suffix=":"
        label-position="right"
        size="mini"
        style="width: 100%"
      >
        <!--        <div v-for="(item, index) in setPriceForm.adminCommissionGoodsRespList" :key="index" >-->
        <!--          <el-form-item v-if="item.commissionKind == 1" label="分佣方式">-->
        <!--            <el-col :span="18">-->
        <!--              <el-radio-group v-model="item.commissionType" size="small" style="line-height: 45px;">-->
        <!--                <div>-->
        <!--                  <el-radio :label="1" style="float: left;margin-top: 5px;line-height: 20px;">按比例分佣（%）</el-radio>-->
        <!--                  <span style="float: right;width: 100px;"><el-input-number v-model="item.commissionPrice1" size="small" :precision="2" :min="0"></el-input-number></span>-->
        <!--                </div>-->
        <!--                <div>-->
        <!--                  <el-radio :label="2" style="float: left;margin-top: 30px;line-height: 20px;">固定分佣金额（元）</el-radio>-->
        <!--                  <span style="float: right;width: 100px;margin-left: 14px;"><el-input-number v-model="item.commissionPrice2" size="small" :precision="2" :min="0" :max="9999.99"></el-input-number></span>-->
        <!--                </div>-->
        <!--              </el-radio-group>-->
        <!--            </el-col>-->
        <!--          </el-form-item>-->
        <!--          <el-form-item v-if="item.commissionKind == 2" label="药代分佣方式">-->
        <!--            <el-col :span="18">-->
        <!--              <el-radio-group v-model="item.commissionType" size="small" style="line-height: 45px;">-->
        <!--                <div>-->
        <!--                  <el-radio :label="1" style="float: left;margin-top: 5px;line-height: 20px;">按比例分佣（%）</el-radio>-->
        <!--                  <span style="float: right;width: 100px;"><el-input-number v-model="item.commissionPrice1" size="small" :precision="2" :min="0"></el-input-number></span>-->
        <!--                </div>-->
        <!--                <div>-->
        <!--                  <el-radio :label="2" style="float: left;margin-top: 30px;line-height: 20px;">固定分佣金额（元）</el-radio>-->
        <!--                  <span style="float: right;width: 100px;margin-left: 14px;"><el-input-number v-model="item.commissionPrice2" size="small" :precision="2" :min="0" :max="9999.99"></el-input-number></span>-->
        <!--                </div>-->
        <!--              </el-radio-group>-->
        <!--            </el-col>-->
        <!--          </el-form-item>-->
        <!--        </div>-->
        <el-form-item label="分佣方式">
          <el-col :span="18">
            <el-radio-group
              v-model="setPriceForm.commission.commissionType"
              size="small"
              style="line-height: 45px"
            >
              <div>
                <el-radio
                  :label="1"
                  style="float: left; margin-top: 5px; line-height: 20px"
                  >按比例分佣（%）</el-radio
                >
                <span style="float: right; width: 100px"
                  ><el-input-number
                    v-model="setPriceForm.commission.commissionPrice1"
                    size="small"
                    :precision="2"
                    :min="0"
                  ></el-input-number
                ></span>
              </div>
              <div>
                <el-radio
                  :label="2"
                  style="float: left; margin-top: 30px; line-height: 20px"
                  >固定分佣金额（元）</el-radio
                >
                <span style="float: right; width: 100px; margin-left: 14px"
                  ><el-input-number
                    v-model="setPriceForm.commission.commissionPrice2"
                    size="small"
                    :precision="2"
                    :min="0"
                    :max="9999.99"
                  ></el-input-number
                ></span>
              </div>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item label="药代分佣方式">
          <el-col :span="18">
            <el-radio-group
              v-model="setPriceForm.proxyCommission.commissionType"
              size="small"
              style="line-height: 45px"
            >
              <div>
                <el-radio
                  :label="1"
                  style="float: left; margin-top: 5px; line-height: 20px"
                  >按比例分佣（%）</el-radio
                >
                <span style="float: right; width: 100px"
                  ><el-input-number
                    v-model="setPriceForm.proxyCommission.commissionPrice1"
                    size="small"
                    :precision="2"
                    :min="0"
                  ></el-input-number
                ></span>
              </div>
              <div>
                <el-radio
                  :label="2"
                  style="float: left; margin-top: 30px; line-height: 20px"
                  >固定分佣金额（元）</el-radio
                >
                <span style="float: right; width: 100px; margin-left: 14px"
                  ><el-input-number
                    v-model="setPriceForm.proxyCommission.commissionPrice2"
                    size="small"
                    :precision="2"
                    :min="0"
                    :max="9999.99"
                  ></el-input-number
                ></span>
              </div>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <!--        <el-form-item label="分佣方式" prop="commissionType">-->
        <!--          <el-col :span="18">-->
        <!--            <el-radio-group v-model="setPriceForm.commissionType" size="small" style="line-height: 45px;">-->
        <!--              <div>-->
        <!--                <el-radio :label="1" style="float: left;margin-top: 5px;line-height: 20px;">按比例分佣（%）</el-radio>-->
        <!--                <span style="float: right;width: 100px;"><el-input-number v-model="setPriceForm.commissionPrice1" size="small" :precision="2" :min="0"></el-input-number></span>-->
        <!--              </div>-->
        <!--              <div>-->
        <!--                <el-radio :label="2" style="float: left;margin-top: 30px;line-height: 20px;">固定分佣金额（元）</el-radio>-->
        <!--                <span style="float: right;width: 100px;margin-left: 14px;"><el-input-number v-model="setPriceForm.commissionPrice2" size="small" :precision="2" :min="0" :max="9999.99"></el-input-number></span>-->
        <!--              </div>-->
        <!--            </el-radio-group>-->
        <!--          </el-col>-->
        <!--        </el-form-item>-->
      </el-form>
      <!--            </el-row>-->
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="setPriceVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmSetPrice">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Upload as ElIconUpload } from '@element-plus/icons'
let vm = null
import { openLoading, closeLoading } from '../../utils/utils'
import BreadCrumb from '@/components/breadcrumb.vue'
import { getGoodsExportUrl } from '../../utils/yqrange/yqrangeApi'
import { getGoodsList, batchOnOff, uploadExcel } from '@/utils/goods'
var typeList = [
  {
    categoryName: '短信额度',
    id: 1,
  },
  {
    categoryName: '学习卡',
    id: 2,
  },
  {
    categoryName: '职称考卡',
    id: 3,
  },
  {
    categoryName: '医疗器械',
    id: 4,
  },
  {
    categoryName: '药品',
    id: 5,
  },
  {
    categoryName: '检测服务',
    id: 337,
  },
]
export default {
  components: {
    BreadCrumb,
    ElIconUpload,
  },
  data() {
    return {
      curmbFirst: '云鹊店铺',
      curmbSecond: '商品管理',
      showAllFlag: false,
      showNewFlag: false,
      batchDialog: false,
      id: '',
      searchForm: {
        goodsIdList: [],
        goodsName: '',
        goodsType: '',
        pageNo: 1,
        pageSize: 10,
        storeId: 0,
        commissionType: 0,
        saleType: 0,
        proxyCommissionType: 0,
      },
      innerVisible: false,
      selectList: [],
      batchParm: {
        batchUpdateSaleStatusReq: {
          goodsIdList: [],
          userId: 0,
        },
        onOff: '',
      },
      fileList: [],
      totalRows: 0,
      tableData: [],
      goodsTypes: [],
      commissionTypeList: [
        {
          value: 0,
          label: '全部',
        },
        {
          value: 1,
          label: '按比例分佣',
        },
        {
          value: 2,
          label: '固定分佣',
        },
      ],
      saleTypeList: [
        {
          value: 0,
          label: '全部',
        },
        {
          value: 1,
          label: '零售',
        },
        {
          value: 2,
          label: '批发',
        },
      ],
      typeList: [],
      //uploadUrl:getBaseUrl('store/goods/import'),
      postData: {},
      validateFailedList: [],
      isSSO: 0, // 是否是sso后台管理员 1是 0否
      multipleSelection: [],
      batchUpdatePriceFlag: false,
      commissionFlag: 2,
      setPriceVisible: false,
      setPriceForm: {
        // commissionType: 1,
        // commissionPrice: '',
        // commissionPrice1: '',
        // commissionPrice2: '',
        // storeId: '',
        // goodsId: '',
        // maxPrice: ''
        adminCommissionGoodsRespList: [],
        commission: {
          commissionKind: '',
          commissionPrice: '',
          commissionPrice1: '',
          commissionPrice2: '',
          commissionType: '',
          goodsId: '',
          maxPrice: 0,
          storeId: '',
        },
        proxyCommission: {
          commissionKind: '',
          commissionPrice: '',
          commissionPrice1: '',
          commissionPrice2: '',
          commissionType: '',
          goodsId: '',
          maxPrice: 0,
          storeId: '',
        },
      },
      setPriceRules: {
        commissionType: [
          { required: true, message: '请选择分佣方式', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    vm = this
    this.getLists()
    this.getLever()
    const { storeId, commissionFlag, storeType } = this.$route.query
    this.searchForm.storeId = Number(storeId) || 0
    this.commissionFlag = commissionFlag
    this.storeType = storeType
    // if(storeId){
    //   this.searchForm.storeId = storeId
    // }
  },
  methods: {
    priceNum_filter(value) {
      if (value != '' && value != null && value != 'null') {
        return (value / 100).toFixed(2)
      } else if (value == 0) {
        return (value / 100).toFixed(2)
      } else {
        return value
      }
    },
    commissionTypeFormat_filter(value) {
      if (!value && value != 0) {
        return '-'
      } else {
        let hash = {
          1: '按比例分佣',
          2: '固定分佣',
        }
        return hash[value]
      }
    },
    rangePrice_filter(price) {
      let str = '￥'
      str += price / 100
      return str
    },
    rangeStatus_filter(status) {
      let str = '' //0待上架，1已上架，2已下架，3定时上架
      if (status == 1) {
        str = '已上架'
      } else if (status == 0) {
        str = '待上架'
      } else if (status == 2) {
        str = '已下架'
      } else if (status == 3) {
        str = '定时上架'
      }
      return str
    },
    rangeType_filter(type) {
      let name = ''
      for (let i = 0; i < typeList.length; i++) {
        if (type == typeList[i].id) {
          name = typeList[i].categoryName
          break
        }
      }
      return name
    },
    handlePreview() {},
    handleRemove() {},
    beforeRemove() {},
    handleSelectionChange(val) {
      this.selectList = val
    },
    handleTableArry(val) {
      let str = ''
      let newVal = []
      if (val.length > 0) {
        val.map((item) => {
          if (item !== '') {
            newVal.push(item)
          }
        })
      }
      if (newVal.length > 0) {
        str = newVal.join('/')
      }
      return str
    },
    //批量上传
    getBatchUpload(file) {
      let self = this
      let arr = file.type.split('/')
      let ext = '.' + arr[1]
      let name = file.name
      let type = name.substring(name.lastIndexOf('.') + 1)
      if (type !== 'xls' && type !== 'xlsx') {
        self.$message({
          message: '上传文件只能是 xls、xlsx格式!',
          type: 'warning',
        })
        return
      }
      let reader = new FileReader()
      reader.onload = function (e) {
        let fileJson = {
          fileName: file.name,
          file: e.target.result.substr(e.target.result.indexOf('base64,') + 7),
          ext: ext,
        }

        let fileArray = [
          {
            type: 'patient',
            base64: fileJson,
          },
        ]

        let req = {
          base64Str: e.target.result.substr(
            e.target.result.indexOf('base64,') + 7
          ),
          storeId: self.searchForm.storeId,
          //import_type: 2,
        }
        //req.token = localStorage.getItem('storageToken');
        //self.postData = JSON.stringify(req);

        uploadExcel(req)
          .then((res) => {
            if (res.code != '000000') {
              return self.$message({
                message: res.message || '上传失败，请重新上传!',
                type: 'error',
              })
            }
            if (res.data.allPass) {
              self.$message({
                message: '上传成功!',
                type: 'success',
              })
              self.batchDialog = false
              setTimeout(() => {
                self.getLists()
              }, 2000)
            } else {
              self.innerVisible = true
              self.validateFailedList = res.data.validateFailedList || []
            }
          })
          .catch((err) => {
            console.log(`上传报错`, err)
          })
      }
      reader.readAsDataURL(file)
    },
    uploadTemp() {
      // let url = "https://file.yunqueyi.com/trade/store/goods_import_template.xlsx 'https://file.yunqueyi.com/trade/store/20210129/goods_import_template.xlsx'"
      // const url = 'https://files.yunqueyi.com/template/goods_import_template_1.xlsx';
      const url =
        'https://files.yunqueyi.com/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet/common/20211105150219553.xlsx'

      window.location.href = url
    },
    getLever(id = 0) {
      this.GET('store/category/' + id).then((res) => {
        console.log(res)
        this.goodsTypes = res.data
      })
    },
    getLists() {
      openLoading(this)
      getGoodsList(this.searchForm).then((res) => {
        if (res.code != '000000') {
          return this.$message({
            message: res.message,
            type: 'error',
          })
        }
        closeLoading(this)
        if (res.data == null) {
          return this.$message({
            message: '分页数据加载失败',
            type: 'error',
          })
        }
        this.tableData = res.data.goodsList

        this.totalRows = res.data.totalCount
        this.isSSO = res.data.isSSO
      })
    },
    //获取商品id
    getIdsByArr(d) {
      let a = []
      for (let i = 0; i < d.length; i++) {
        a.push(d[i].goodsId)
      }
      return a
    },
    //批量 上下架操作
    batchOpt(type) {
      if (type == 3) {
        //批量导入
        this.batchDialog = true
      } else {
        if (this.selectList.length == 0) {
          return this.$message({
            message: '请选择商品',
            type: 'warning',
          })
        }
        this.batchParm.onOff = type
        this.batchParm.batchUpdateSaleStatusReq.goodsIdList = this.getIdsByArr(
          this.selectList
        )
        batchOnOff(this.batchParm).then((res) => {
          if (res.code == '000000') {
            this.selectList = []
            this.$refs.multipleTable.clearSelection()
            this.$message({
              message: '操作成功',
              type: 'success',
            })
            setTimeout(() => {
              this.getLists()
            }, 2000)
          }
        })
      }
    },
    edit(row) {
      const { goodsType, storeType } = row
      //  storeType 1: "供货商",2: "小药房",3: "医生小店"
      let url = ''
      if (row == 'add') {
        url = `/create-good-new?id=add&storeId=${this.searchForm.storeId}&inputType=1&commissionFlag=${this.commissionFlag}&storeType=${this.storeType}`
      } else {
        url = `/create-good-new?id=${row.goodsId}&storeId=${this.searchForm.storeId}&goodsType=${goodsType}&commissionFlag=${this.commissionFlag}&storeType=${storeType}`
      }
      // this.$store.dispatch('goodsManage/changeGoodsInfo', {...row});
      this.$router.push({
        path: url,
      })
    },
    //上架  下架
    shelfOpt(row, type) {
      let str = '',
        btn1 = '',
        btn2 = ''
      if (type == 1) {
        str = `确定下架商品吗？<br/>下架后将不再出售`
        btn1 = '下架'
      } else if (type == 2) {
        str = `确定上架商品吗？<br/>上架后将开始出售`
        btn1 = '上架'
      } else if (type == 3) {
        str = `确定删除商品吗？<br/>删除后商品信息将都不保留`
        btn1 = '删除'
      }
      this.$confirm(str, '', {
        confirmButtonText: btn1,
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'range-make-box',
        dangerouslyUseHTMLString: true,
      })
        .then(() => {
          //  confirm
          // this.updateStatus(row.id, "30");
          if (type != 3) {
            this.batchParm.onOff = type == 1 ? 'off' : 'on'
            this.batchParm.batchUpdateSaleStatusReq.goodsIdList = [row.goodsId]
            batchOnOff(this.batchParm).then((res) => {
              if (res.code == '000000') {
                this.getLists()
              } else {
                this.$message.error(res.message)
              }
            })
          }
        })
        .catch(() => {
          //  cancel
          // this.$message.error("上线失败");
        })
    },
    initPrivilege() {
      let idType = localStorage.getItem('storageIdType')
      this.searchForm.userType = idType
      // 内部用户:运营人员
      if (idType == '1') {
        this.showAllFlag = true
        this.showNewFlag = true
      }
      // 外部用户
      else if (idType == '2') {
        this.showAllFlag = false
        this.getUserAuth()
      }
    },
    // 外部用户权限
    getUserAuth() {
      let highMainManager = localStorage.getItem('highMainManager')
      let mainManager = localStorage.getItem('mainManager')
      let manager = localStorage.getItem('manager')

      if (highMainManager == '1' || mainManager == '1') {
        this.showNewFlag = true
      } else if (manager == '1') {
        this.showNewFlag = false
      }
    },
    searchList() {
      openLoading(this)
      if (this.id != '') {
        this.searchForm.goodsIdList = [this.id]
      } else {
        this.searchForm.goodsIdList = []
      }
      this.searchForm.pageNo = 1
      this.getLists()
    },
    resetForm() {
      // this.searchForm = {
      //  goodsIdList:[],
      //  goodsName:'',
      //  goodsType:'',
      //  pageNo:1,
      //  pageSize:	10,

      // };
      this.searchForm.goodsIdList = []
      this.searchForm.goodsName = ''
      this.searchForm.goodsType = ''
      this.searchForm.commissionType = 0
      this.searchForm.saleType = 0
      this.searchForm.pageNo = 1
      this.searchForm.pageSize = 10

      this.getLists()
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.searchForm.pageNo = 1
      this.searchList()
    },
    handleNumChange(val) {
      this.searchForm.pageNo = val
      this.getLists()
    },
    exportOpt() {
      const { goodsIdList, goodsType, goodsName, storeId, saleType } =
        this.searchForm
      getGoodsExportUrl({
        goodsIdList,
        goodsType,
        goodsName,
        storeId,
        saleType,
      }).then((res) => {
        if (res.code != '000000') {
          this.$message({ message: res.message, type: 'error' })
          return
        }
        window.open(res.data)
      })
    },
    batchSetPrice() {
      if (this.selectList.length == 0) {
        this.$message({
          message: '请先选择要操作的数据',
          type: 'warning',
        })
        return
      }
      this.setPrice(this.selectList[0], true)
    },
    setPrice(row, batchUpdatePriceFlag) {
      this.batchUpdatePriceFlag = batchUpdatePriceFlag
      // if(this.$refs.setPriceForm) {
      //   this.$refs.setPriceForm.resetFields()
      // }

      if (row.adminCommissionGoodsRespList) {
        this.setPriceForm.adminCommissionGoodsRespList =
          row.adminCommissionGoodsRespList
        for (
          let i = 0;
          i < this.setPriceForm.adminCommissionGoodsRespList.length;
          i++
        ) {
          if (
            this.setPriceForm.adminCommissionGoodsRespList[i].commissionType ==
            1
          ) {
            this.setPriceForm.adminCommissionGoodsRespList[i].commissionPrice1 =
              this.setPriceForm.adminCommissionGoodsRespList[i]
                .commissionPrice / 100
          } else if (
            this.setPriceForm.adminCommissionGoodsRespList[i].commissionType ==
            2
          ) {
            this.setPriceForm.adminCommissionGoodsRespList[i].commissionPrice2 =
              this.setPriceForm.adminCommissionGoodsRespList[i]
                .commissionPrice / 100
          }
          if (
            this.setPriceForm.adminCommissionGoodsRespList[i].commissionKind ==
            1
          ) {
            // this.setPriceForm.commission = this.setPriceForm.adminCommissionGoodsRespList[i];

            this.setPriceForm.commission.commissionKind =
              this.setPriceForm.adminCommissionGoodsRespList[i].commissionKind
            this.setPriceForm.commission.commissionPrice =
              this.setPriceForm.adminCommissionGoodsRespList[i].commissionPrice
            this.setPriceForm.commission.commissionPrice1 =
              this.setPriceForm.adminCommissionGoodsRespList[i].commissionPrice1
            this.setPriceForm.commission.commissionPrice2 =
              this.setPriceForm.adminCommissionGoodsRespList[i].commissionPrice2
            this.setPriceForm.commission.commissionType =
              this.setPriceForm.adminCommissionGoodsRespList[i].commissionType
            this.setPriceForm.commission.goodsId =
              this.setPriceForm.adminCommissionGoodsRespList[i].goodsId
            this.setPriceForm.commission.maxPrice =
              this.setPriceForm.adminCommissionGoodsRespList[i].maxPrice
            this.setPriceForm.commission.storeId =
              this.setPriceForm.adminCommissionGoodsRespList[i].storeId
          } else if (
            this.setPriceForm.adminCommissionGoodsRespList[i].commissionKind ==
            2
          ) {
            // this.setPriceForm.proxyCommission = this.setPriceForm.adminCommissionGoodsRespList[i];
            this.setPriceForm.proxyCommission.commissionKind =
              this.setPriceForm.adminCommissionGoodsRespList[i].commissionKind
            this.setPriceForm.proxyCommission.commissionPrice =
              this.setPriceForm.adminCommissionGoodsRespList[i].commissionPrice
            this.setPriceForm.proxyCommission.commissionPrice1 =
              this.setPriceForm.adminCommissionGoodsRespList[i].commissionPrice1
            this.setPriceForm.proxyCommission.commissionPrice2 =
              this.setPriceForm.adminCommissionGoodsRespList[i].commissionPrice2
            this.setPriceForm.proxyCommission.commissionType =
              this.setPriceForm.adminCommissionGoodsRespList[i].commissionType
            this.setPriceForm.proxyCommission.goodsId =
              this.setPriceForm.adminCommissionGoodsRespList[i].goodsId
            this.setPriceForm.proxyCommission.maxPrice =
              this.setPriceForm.adminCommissionGoodsRespList[i].maxPrice
            this.setPriceForm.proxyCommission.storeId =
              this.setPriceForm.adminCommissionGoodsRespList[i].storeId
          }
        }
        let newArray = this.setPriceForm.adminCommissionGoodsRespList.filter(
          function (item) {
            return item.commissionKind == 1
          }
        )
        if (newArray == null || newArray.length == 0) {
          this.setPriceForm.commission = {
            commissionKind: 1,
            commissionPrice: '',
            commissionPrice1: undefined,
            commissionPrice2: undefined,
            commissionType: 0,
            goodsId: row.goodsId,
            maxPrice: 0,
            storeId: row.storeId,
          }
        }
        let array = this.setPriceForm.adminCommissionGoodsRespList.filter(
          function (item) {
            return item.commissionKind == 2
          }
        )
        if (array == null || array.length == 0) {
          this.setPriceForm.proxyCommission = {
            commissionKind: 2,
            commissionPrice: '',
            commissionPrice1: undefined,
            commissionPrice2: undefined,
            commissionType: 0,
            goodsId: row.goodsId,
            maxPrice: 0,
            storeId: row.storeId,
          }
        }
      } else {
        this.setPriceForm.commission = {
          commissionKind: 1,
          commissionPrice: '',
          commissionPrice1: undefined,
          commissionPrice2: undefined,
          commissionType: 0,
          goodsId: row.goodsId,
          maxPrice: 0,
          storeId: row.storeId,
        }

        this.setPriceForm.proxyCommission = {
          commissionKind: 2,
          commissionPrice: '',
          commissionPrice1: undefined,
          commissionPrice2: undefined,
          commissionType: 0,
          goodsId: row.goodsId,
          maxPrice: 0,
          storeId: row.storeId,
        }
      }

      // this.setPriceForm.storeId = row.storeId;
      // this.setPriceForm.goodsId = row.goodsId;
      // this.setPriceForm.commissionType = "";
      // this.setPriceForm.commissionPrice1 = undefined;
      // this.setPriceForm.commissionPrice2 = undefined;
      // this.setPriceForm.commissionType = row.commissionType;
      // if(this.setPriceForm.commissionType == 1){
      //   this.setPriceForm.commissionPrice1 = row.commissionPrice/100;
      // }
      // else if(this.setPriceForm.commissionType == 2){
      //   this.setPriceForm.commissionPrice2 = row.commissionPrice/100;
      // }
      this.setPriceVisible = true
      // this.setPriceForm.price = row.price;
      // if(this.$refs.setPriceForm) {
      //   this.$refs.setPriceForm.resetFields()
      // }
      // this.getProfit(row);
    },
    confirmSetPrice() {
      if (
        this.setPriceForm.commission.commissionType == 1 &&
        (this.setPriceForm.commission.commissionPrice1 == undefined ||
          this.setPriceForm.commission.commissionPrice1 > 100)
      ) {
        this.$message({
          message: '请输入按比例分佣0-100',
          type: 'warning',
        })
        return
      }

      if (
        this.setPriceForm.commission.commissionType == 2 &&
        this.setPriceForm.commission.commissionPrice2 == undefined
      ) {
        this.$message({
          message: '请输入固定分佣金额',
          type: 'warning',
        })
        return
      }

      if (
        this.setPriceForm.proxyCommission.commissionType == 1 &&
        (this.setPriceForm.proxyCommission.commissionPrice1 == undefined ||
          this.setPriceForm.proxyCommission.commissionPrice1 > 100)
      ) {
        this.$message({
          message: '请输入按比例分佣0-100',
          type: 'warning',
        })
        return
      }
      if (
        this.setPriceForm.proxyCommission.commissionType == 2 &&
        this.setPriceForm.proxyCommission.commissionPrice2 == undefined
      ) {
        this.$message({
          message: '请输入固定分佣金额',
          type: 'warning',
        })
        return
      }

      // for(let i = 0; i < this.setPriceForm.adminCommissionGoodsRespList.length; i++){
      //   // if(this.setPriceForm.adminCommissionGoodsRespList[i].commissionKind == 1
      //   //   && (this.setPriceForm.adminCommissionGoodsRespList[i].commissionType == null || this.setPriceForm.adminCommissionGoodsRespList[i].commissionType == "")){
      //   //
      //   //   this.$message({
      //   //     message: '请选择分佣方式',
      //   //     type: "warning"
      //   //   });
      //   //   return;
      //   // }
      //   //
      //   // if(this.setPriceForm.adminCommissionGoodsRespList[i].commissionKind == 1
      //   //   && this.setPriceForm.adminCommissionGoodsRespList[i].commissionType == 1 && this.setPriceForm.adminCommissionGoodsRespList[i].commissionPrice1 == undefined ){
      //   //   this.$message({
      //   //     message: '请输入按比例分佣',
      //   //     type: "warning"
      //   //   });
      //   //   return;
      //   // }
      //   if(this.setPriceForm.adminCommissionGoodsRespList[i].commissionType == 1 && this.setPriceForm.adminCommissionGoodsRespList[i].commissionPrice1 > 100){
      //     this.$message({
      //       message: '请输入按比例分佣0-100',
      //       type: "warning"
      //     });
      //     return;
      //   }
      //   // if(this.setPriceForm.adminCommissionGoodsRespList[i].commissionKind == 1
      //   //   && this.setPriceForm.adminCommissionGoodsRespList[i].commissionType == 2 && this.setPriceForm.adminCommissionGoodsRespList[i].commissionPrice2 == undefined ){
      //   //   this.$message({
      //   //     message: '请输入固定分佣金额',
      //   //     type: "warning"
      //   //   });
      //   //   return;
      //   // }
      //
      //   if(this.setPriceForm.adminCommissionGoodsRespList[i].commissionType == 1){
      //     this.setPriceForm.adminCommissionGoodsRespList[i].commissionPrice = this.setPriceForm.adminCommissionGoodsRespList[i].commissionPrice1 * 100;
      //   }
      //   else if(this.setPriceForm.adminCommissionGoodsRespList[i].commissionType == 2){
      //     this.setPriceForm.adminCommissionGoodsRespList[i].commissionPrice = this.setPriceForm.adminCommissionGoodsRespList[i].commissionPrice2 * 100;
      //   }
      //
      // }

      let timeoutId = null
      timeoutId && clearTimeout(timeoutId)
      timeoutId = setTimeout(() => {
        this.clickHandle()
      }, 500)
    },
    // 防止按钮多次点击
    clickHandle() {
      // this.$refs.setPriceForm.validate((valid) => {
      //   if(valid) {
      vm.loading = true
      if (this.setPriceForm.commission.commissionType == 1) {
        this.setPriceForm.commission.commissionPrice = (
          this.setPriceForm.commission.commissionPrice1 * 100
        ).toFixed(0)
      } else if (this.setPriceForm.commission.commissionType == 2) {
        this.setPriceForm.commission.commissionPrice = (
          this.setPriceForm.commission.commissionPrice2 * 100
        ).toFixed(0)
      }
      if (this.setPriceForm.proxyCommission.commissionType == 1) {
        this.setPriceForm.proxyCommission.commissionPrice = (
          this.setPriceForm.proxyCommission.commissionPrice1 * 100
        ).toFixed(0)
      } else if (this.setPriceForm.proxyCommission.commissionType == 2) {
        this.setPriceForm.proxyCommission.commissionPrice = (
          this.setPriceForm.proxyCommission.commissionPrice2 * 100
        ).toFixed(0)
      }
      vm.setPriceForm.adminCommissionGoodsRespList[0] =
        this.setPriceForm.commission
      vm.setPriceForm.adminCommissionGoodsRespList[1] =
        this.setPriceForm.proxyCommission

      // 批量设置价格
      if (vm.batchUpdatePriceFlag) {
        let setPriceList = []
        // if(vm.setPriceForm.commissionType == 1){
        //   vm.setPriceForm.commissionPriceStr = vm.setPriceForm.commissionPrice1;
        // }
        // else if(vm.setPriceForm.commissionType == 2){
        //   vm.setPriceForm.commissionPriceStr = vm.setPriceForm.commissionPrice2;
        // }
        let parm = {
          adminCommissionGoodsReqList:
            vm.setPriceForm.adminCommissionGoodsRespList,
          // commissionPrice: vm.setPriceForm.commissionPriceStr * 100,
          // commissionType: vm.setPriceForm.commissionType,
          goodsIdList: [],
        }
        for (let i = 0; i < vm.selectList.length; i++) {
          parm.goodsIdList.push(vm.selectList[i].goodsId)
        }
        vm.POST('/store/commission/admin/batch/goods/save', parm).then(
          (res) => {
            vm.loading = false
            // closeLoading(this);
            if (res.code == '000000') {
              vm.$message({
                message: '设置价格成功',
                type: 'success',
              })
              vm.setPriceVisible = false
              vm.searchList()
            } else {
              vm.$message({
                message: res.message,
                type: 'error',
              })
            }
          }
        )
      } else {
        // if(vm.setPriceForm.commissionType == 1){
        //   vm.setPriceForm.commissionPriceStr = vm.setPriceForm.commissionPrice1;
        // }
        // else if(vm.setPriceForm.commissionType == 2){
        //   vm.setPriceForm.commissionPriceStr = vm.setPriceForm.commissionPrice2;
        // }
        // vm.setPriceForm.commissionPrice = vm.setPriceForm.commissionPriceStr * 100;
        vm.POST(
          '/store/commission/admin/goods/save',
          vm.setPriceForm.adminCommissionGoodsRespList
        ).then((res) => {
          vm.loading = false
          // closeLoading(this);
          if (res.code == '000000') {
            vm.$message({
              message: '设置价格成功',
              type: 'success',
            })
            vm.setPriceVisible = false
            vm.searchList()
          } else {
            vm.$message({
              message: res.message,
              type: 'error',
            })
          }
        })
      }

      //   }
      // })
    },
  },
}
</script>

<style lang="scss">
.yqshop-wrapper {
  .yqshop-content {
    background: #fff;
    padding: 10px;
    .header-title {
      padding: 10px 12px;
      font-size: 13px;
      color: #449284;
      border-bottom: 1px solid #efefef;
    }
  }
  .el-button--text {
    color: #449284;
    font-size: 14px;
    &::after {
      content: '';
      position: relative;
      height: 14px;
      /*border-right: 1px solid #EBEEF5;*/
      border-right: 1px solid #aaaaaa;
      padding-right: 10px;
    }
    &:last-of-type {
      &::after {
        content: '';
        position: relative;
        width: 1px;
        height: 14px;
        border-right: none;
      }
    }
  }
}
.batch-dia {
  .batch-dia-item {
    overflow: hidden;
    .s-l,
    .s-r {
      float: left;
      padding: 10px 0;
      color: #666;
    }
    .s-l {
      margin-right: 100px;
    }
    .s-r {
      color: #1989fa;
      cursor: pointer;
    }
    .el-icon-upload {
    }
  }
}
</style>
