<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="商品分类" prop="cateId">
         <treeselect  v-model="queryParams.cateId"  style="width:205.4px" :options="categoryOptions" :normalizer="normalizer" placeholder="请选择分类" />
      </el-form-item>

      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

       <el-form-item label="商品编号" prop="barCode">
        <el-input
          v-model="queryParams.barCode"
          placeholder="请输入商品编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item label="商品类型" prop="productType">
        <el-select   v-model="queryParams.productType" placeholder="请选择商品类型" clearable size="small" >
         <el-option
                v-for="item in productTypeOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
        </el-select>
      </el-form-item>

      <el-form-item label="所属仓库" prop="productType">
        <el-select v-model="queryParams.warehouseCode" placeholder="请选择仓库" clearable size="small">
          <el-option
            v-for="item in warehouseOptions"
            :key="item.warehouseCode"
            :label="item.warehouseName"
            :value="item.warehouseCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['store:storeProduct:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['store:storeProduct:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['store:storeProduct:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['store:storeProduct:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['store:storeProduct:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
        v-if="activeName==0"
          type="success"
          icon="el-icon-edit"
          size="mini"
          @click="putOn"
          v-hasPermi="['store:storeProduct:putOn']"
        >上架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-if="activeName==1"
          type="success"
          icon="el-icon-edit"
          size="mini"
          @click="pullOff"
          v-hasPermi="['store:storeProduct:pullOff']"
        >下架</el-button>
      </el-col>
	    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-tabs type="card" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="出售中" name="1"></el-tab-pane>
      <el-tab-pane label="待上架" name="0"></el-tab-pane>
    </el-tabs>

    <el-table  height="500" border v-loading="loading" :data="storeProductList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="productId" />
      <el-table-column label="商品图片" align="center" width="120">
        <template slot-scope="scope">
          <el-popover
            placement="right"
            title=""
            trigger="hover">
            <img slot="reference" :src="scope.row.image" width="100">
            <img :src="scope.row.image" style="max-width: 150px;">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" show-overflow-tooltip align="center" prop="productName" />
      <el-table-column label="分类" align="center" prop="cateName" />
      <el-table-column label="售价" align="center" prop="price" >
          <template slot-scope="scope" >
              <span v-if="scope.row.price!=null">{{scope.row.price.toFixed(2)}}</span>
          </template>
      </el-table-column>
      <el-table-column label="原价" align="center" prop="otPrice" >
          <template slot-scope="scope" >
              <span v-if="scope.row.otPrice!=null">{{scope.row.otPrice.toFixed(2)}}</span>
          </template>
      </el-table-column>
      <el-table-column label="销量" align="center" prop="sales" />
      <el-table-column label="库存" align="center" prop="stock" />
      <el-table-column label="仓库代码" align="center" prop="warehouseCode" />
      <el-table-column label="类型" align="center" prop="productType" >
          <template slot-scope="scope">
              <el-tag prop="productType" v-for="(item, index) in productTypeOptions"    v-if="scope.row.productType==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="isShow" >
          <template slot-scope="scope">
              <el-tag prop="status" v-for="(item, index) in isShowOptions"    v-if="scope.row.isShow==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['store:storeProduct:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['store:storeProduct:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" v-if="open" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row >
          <el-col :span="12">
            <el-form-item label="商品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品分类" prop="cateId">
               <treeselect v-model="form.cateId" :options="categoryOptions" :normalizer="normalizer" placeholder="请选择上级分类" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="关键字" prop="keyword">
              <el-input v-model="form.keyword" placeholder="请输入关键字" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位名" prop="unitName">
              <el-input v-model="form.unitName" placeholder="请输入单位名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="税收分类码" prop="taxClassificationCode">
              <el-input v-model="form.taxClassificationCode" placeholder="请输入税收分类码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品发票名称" prop="invoiceName">
              <el-input v-model="form.invoiceName" placeholder="请输入商品发票名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品简介" prop="productInfo">
              <el-input v-model="form.productInfo" type="textarea" :rows="2" placeholder="请输入商品简介" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="商品图片" prop="image">
          <Material v-model="imageArr" type="image" :num="1" :width="150" :height="150" />
        </el-form-item>
        <el-form-item label="轮播图" prop="sliderImage">
          <Material v-model="photoArr" type="image" :num="10" :width="150" :height="150" />
        </el-form-item>
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品规格：" props="specType">
              <el-radio-group v-model="form.specType" >
                <el-radio :label="0" class="radio">单规格</el-radio>
                <el-radio :label="1">多规格</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
           <!-- 多规格添加-->
          <el-col :span="24" v-if="form.specType === 1" class="noForm">
           <el-col :span="24">
              <el-form-item label="选择规格：" prop="">
                <div  class="acea-row row-middle">
                  <el-select v-model="form.selectRule" style="width: 23%;">
                    <el-option v-for="(item, index) in ruleList" :value="item.ruleName" :key="index">{{ item.ruleName }}</el-option>
                  </el-select>
                  <el-button style="margin-left:10px;" type="primary" class="mr20" @click="confirm">确认</el-button>
                </div>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item v-if="attrs!=null&&attrs.length!==0">
                <div  v-for="(item, index) in attrs" :key="index">
                  <div class="acea-row row-middle"><span class="mr5">{{item.value}}</span>
                    <i class="el-icon-circle-close"  @click="handleRemoveRole(index)"></i>
                  </div>
                  <div class="rulesBox">
                    <el-tag type="dot" closable color="primary" v-for="(j, indexn) in item.detail" :key="indexn" :name="j" class="mr20" @close="handleRemove2(item.detail,indexn)">{{j}}</el-tag>
                    <el-input placeholder="请输入属性名称" v-model="item.detail.attrsVal"
                              style="width: 200px">
                      <el-button slot="append" type="primary" @click="createAttr(item.detail.attrsVal,index)">添加</el-button>
                    </el-input>
                  </div>
                </div>
              </el-form-item>
            </el-col>

             <el-col :span="24" v-if="createBnt">
              <el-form-item>
                <el-button type="primary" size="small" icon="md-add" @click="addBtn" class="mr15">添加新规格</el-button>
                <el-button type="success" size="small"  @click="generate">立即生成</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="showIput">
              <el-col  :xl="6" :lg="9" :md="10" :sm="24" :xs="24" >
                <el-form-item label="规格：">
                  <el-input  placeholder="请输入规格" v-model="formDynamic.attrsName"  />
                </el-form-item>
              </el-col>
              <el-col  :xl="6" :lg="9" :md="10" :sm="24" :xs="24">
                <el-form-item label="规格值：">
                  <el-input v-model="formDynamic.attrsVal" placeholder="请输入规格值"  />
                </el-form-item>
              </el-col>
              <el-col :xl="6" :lg="5" :md="10" :sm="24" :xs="24" >
                  <el-button type="primary"    @click="createAttrName">确定</el-button>
                  <el-button type="danger" @click="closeAttrName" >取消</el-button>
              </el-col>
            </el-col>
            <!-- 多规格设置-->
            <el-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24" v-if="manyFormValidate!=null&&manyFormValidate.length">
              <!-- 多规格表格-->
              <el-col :span="24">
                <el-form-item label="商品属性：" class="labeltop">

                  <el-table :data="manyFormValidate" size="small" style="width: 90%;">
                    <el-table-column
                      v-for="(item,index) in manyTableColumns"
                      :key="item.slot || index"
                      :min-width="item.minWidth"
                      :width="item.width"
                      :label="item.title"
                      :prop="item.slot"
                      :property="item.slot"
                      align="center"
                    >
                      <template slot-scope="scope">
                        <div v-if="scope.column.property == 'image'" align="center">
                          <single-img v-model="scope.row[scope.column.property]" type="image" :num="1" :width="60" :height="60" />
                        </div>
                        <div v-else-if="scope.column.property && scope.column.property.indexOf('value') === 0" align="center">
                         {{ scope.row[scope.column.property] }}
                        </div>
                        <div v-else-if="scope.column.property == 'taxRate'" align="center">
                          <el-input
                            v-model="scope.row.taxRate"
                            placeholder="请输入税率"
                            @input="handleTaxRateInput($event, scope.row)"
                          />
                        </div>
                        <div v-else align="center">
                          <el-input v-model="scope.row[scope.column.property]" align="center" />
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" fixed="right" width="80" align="center">
                      <template slot-scope="scope">
                        <el-button type="text" size="mini" @click="delAttrTable(scope.$index)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>

                </el-form-item>
              </el-col>
            </el-col>
          </el-col>

          <!-- 单规格表格-->
          <el-col :xl="23" :lg="24" :md="24" :sm="24" :xs="24" v-if="form.specType === 0">
            <el-form-item >
              <el-table :data="oneFormValidate"  size="small" style="width: 90%;">
                <el-table-column prop="image" label="图片" align="center">
                  <template slot-scope="scope">
                    <single-img v-model="scope.row.image" type="image" :num="1" :width="60" :height="60" />
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="售价" align="center">
                  <template slot-scope="scope">
                    <el-input type="text" v-model="scope.row.price"/>
                  </template>
                </el-table-column>
                <el-table-column prop="agentPrice" label="代理价" align="center">
                  <template slot-scope="scope">
                    <el-input type="text" v-model="scope.row.agentPrice"/>
                  </template>
                </el-table-column>
                <el-table-column prop="cost" label="成本价" align="center">
                  <template slot-scope="scope">
                    <el-input type="text" v-model="scope.row.cost"/>
                  </template>
                </el-table-column>
                <el-table-column prop="otPrice" label="原价" align="center">
                  <template slot-scope="scope">
                    <el-input type="text" v-model="scope.row.otPrice"/>
                  </template>
                </el-table-column>
                <el-table-column prop="stock" label="库存" align="center">
                  <template slot-scope="scope">
                    <el-input type="text" v-model="scope.row.stock" maxlength="7"/>
                  </template>
                </el-table-column>
                <el-table-column prop="barCode" label="商品编号" width="130px" align="center">
                  <template slot-scope="scope">
                    <el-input type="text" v-model="scope.row.barCode"/>
                  </template>
                </el-table-column>
                <el-table-column prop="barCode" label="组合编号" width="130px" align="center">
                  <template slot-scope="scope">
                    <el-input type="text" v-model="scope.row.groupBarCode"/>
                  </template>
                </el-table-column>
                <el-table-column prop="weight" label="重量（KG）" align="center">
                  <template slot-scope="scope">
                    <el-input type="text" v-model="scope.row.weight"/>
                  </template>
                </el-table-column>
                <el-table-column prop="volume" label="体积(m³)" align="center">
                  <template slot-scope="scope">
                    <el-input type="text" v-model="scope.row.volume"/>
                  </template>
                </el-table-column>
                <el-table-column prop="volume" label="所需积分" align="center">
                  <template slot-scope="scope">
                    <el-input type="text" v-model="scope.row.integral"/>
                  </template>
                </el-table-column>
                <el-table-column prop="volume" label="一级返佣" align="center">
                  <template slot-scope="scope">
                    <el-input type="text" v-model="scope.row.brokerage"/>
                  </template>
                </el-table-column>
                <el-table-column prop="volume" label="二级返佣" align="center">
                  <template slot-scope="scope">
                    <el-input type="text" v-model="scope.row.brokerageTwo"/>
                  </template>
                </el-table-column>
                <el-table-column prop="volume" label="三级返佣" align="center">
                  <template slot-scope="scope">
                    <el-input type="text" v-model="scope.row.brokerageThree"/>
                  </template>
                </el-table-column>
                <el-table-column prop="taxRate" label="税率" align="center">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.taxRate"
                      placeholder="请输入税率"
                      @input="handleTaxRateInput($event, scope.row)"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="运费模板：" prop="tempId">
              <div class="acea-row">
                <el-select v-model="form.tempId"  class="mr20" filterable>
                  <el-option v-for="(item,index) in templateList" :value="item.id" :key="index" :label="item.name">
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="商品详情" prop="description">
           <editor ref="myeditor"   @on-text-change="updateText" />
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item label="商品状态" prop="isShow">
              <el-radio-group v-model="form.isShow">
                <el-radio :label="item.dictValue" v-for="item in isShowOptions" >{{item.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
           <el-form-item label="是否热卖" prop="isHot">
              <el-radio-group v-model="form.isHot">
                <el-radio :label="item.dictValue" v-for="item in isHotOptions" >{{item.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="猜你喜欢" prop="isGood">
              <el-radio-group v-model="form.isGood">
                <el-radio :label="item.dictValue" v-for="item in isGoodOptions" >{{item.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
         <el-row>
          <el-col :span="8">
            <el-form-item label="精品推荐" prop="isBest">
              <el-radio-group v-model="form.isBest">
                <el-radio :label="item.dictValue" v-for="item in isBestOptions" >{{item.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
           <el-form-item label="新品首发" prop="isNew">
              <el-radio-group v-model="form.isNew">
                <el-radio :label="item.dictValue" v-for="item in isNewOptions" >{{item.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="返还积分">
              <el-input-number  v-model="form.giveIntegral" :min="0" placeholder="请输入积分" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="商城展示" prop="isDisplay">
              <el-radio-group v-model="form.isDisplay">
                <el-radio :label="item.dictValue" v-for="item in isDisplayOptions" >{{item.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">

            <el-form-item label="排序" prop="sort">
               <el-input-number :min="0"  v-model="form.sort" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
           <el-col :span="8">
            <el-form-item label="销量" prop="sales">
               <el-input-number :min="0"  v-model="form.sales" placeholder="请输入销量" />
            </el-form-item>
          </el-col>

        </el-row>
        <el-form-item label="推广分类" prop="tuiCateId">
          <el-select style="width: 240px" v-model="form.tuiCateId" placeholder="请选择推广分类" clearable size="small" >
            <el-option
                    v-for="item in productTuiCateOptions"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
            </el-select>
        </el-form-item>
        <el-form-item label="商品类型" prop="productType">
          <el-select style="width: 240px" v-model="form.productType" placeholder="请选择商品类型" clearable size="small" >
            <el-option
                    v-for="item in productTypeOptions"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
            </el-select>
        </el-form-item>
        <el-form-item label="所属仓库" prop="warehouseCode">
          <el-select v-model="warehouseModel" placeholder="请选择仓库" clearable size="small" filterable>
            <el-option
              v-for="item in warehouseOptions"
              :key="item.id"
              :label="item.warehouseName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="国药准字" v-if="form.productType==2" prop="prescribeCode">
          <el-input v-model="form.prescribeCode" placeholder="请输入国药准字" />
        </el-form-item>
        <el-form-item label="规格" v-if="form.productType==2" prop="prescribeSpec">
          <el-input v-model="form.prescribeSpec" placeholder="请输入规格" />
        </el-form-item>
        <el-form-item label="生产厂家" v-if="form.productType==2" prop="prescribeFactory">
          <el-input v-model="form.prescribeFactory" placeholder="请输入生产厂家" />
        </el-form-item>
        <el-form-item label="处方名" v-if="form.productType==2" prop="prescribeName">
          <el-input v-model="form.prescribeName" placeholder="请输入处方名" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="upload.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 + '?updateSupport=' + upload.updateSupport"
        :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 {genFormatAttr, putOn,pullOff,listStoreProduct, getStoreProduct, delStoreProduct, addOrEdit, exportStoreProduct,importTemplate } from "@/api/store/storeProduct";
import { getAllStoreProductCategory } from "@/api/store/storeProductCategory";
import { getAllStoreProductRule } from "@/api/store/storeProductRule";
import { getAllShippingTemplates } from "@/api/store/shippingTemplates";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Editor from '@/components/Editor/wang';
import Material from '@/components/Material'
import singleImg from '@/components/Material/single'
import {listWarehousesAll} from "../../../api/store/warehouses";
export default {
  name: "StoreProduct",
  components: {
    Treeselect,
    Editor,
    Material,
    singleImg,
  },
  watch: {
    imageArr: function(val) {
      this.form.image = val.join(',')
    },
    photoArr: function(val) {
      this.form.sliderImage = val.join(',')
    }
  },
  data() {
    return {
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/store/storeProduct/importData"
      },
      productTuiCateOptions:[],
      // 仓库列表
      warehouseOptions: [],
      showIput: false,
      createBnt:true,
      // 规格数据
      formDynamic: {
        attrsName: '',
        attrsVal: ''
      },
      isBtn: false,
      columns: [],
      attrs:[],
      templateList:[],
      ruleList:[],
      // 多规格表格data
      manyFormValidate: [],
      // 编辑请求序号，用于忽略过期的异步回调
      editSeq: 0,
      // 单规格表格data
      oneFormValidate: [
        {
          image: '',
          price: 0,
          cost: 0,
          agentPrice: 0,
          otPrice: 0,
          stock: 0,
          barCode: '',
          weight: 0,
          volume: 0,
          integral: 0
        }
      ],
      photoArr:[],
      imageArr:[],
      activeName:"1",
      productTypeOptions:[],
      isDisplayOptions:[],
      isGoodOptions:[],
      isNewOptions:[],
      isBestOptions:[],
      isHotOptions:[],
      isShowOptions:[],
      categoryOptions:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      storeProductList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        productType: null,
        isShow: "1",
        barCode:null,

      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        warehouseCode: [
          {required: true,message: '仓库代码不能为空!',trigger: "blur"}
        ],
        image: [
          { required: true, message: "商品图片不能为空", trigger: "blur" }
        ],
        sliderImage: [
          { required: true, message: "轮播图不能为空", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        productInfo: [
          { required: true, message: "商品简介不能为空", trigger: "blur" }
        ],
        unitName: [
          { required: true, message: "单位名不能为空", trigger: "blur" }
        ],
        keyword: [
          { required: true, message: "关键字不能为空", trigger: "blur" }
        ],
        cateId: [
          { required: true, message: "分类id不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "商品价格不能为空", trigger: "blur" }
        ],
        prescribeCode: [
          { required: true, message: "国药准字不能为空", trigger: "blur" }
        ],
        prescribeSpec: [
          { required: true, message: "规格不能为空", trigger: "blur" }
        ],
        prescribeFactory: [
          { required: true, message: "生产厂家不能为空", trigger: "blur" }
        ],
        prescribeName: [
          { required: true, message: "处方药不能为空", trigger: "blur" }
        ],


      }
    };
  },
  computed:{
    manyTableColumns() {
      if (!this.form.header || !this.form.header.length) {
        return [];
      }
      return this.form.header.filter(item => item.slot !== 'action');
    },
    warehouseModel:{
      get(){
        return this.form.warehouseId;
      },
      set(newVal){
        console.log(newVal);
        this.form.warehouseId = newVal;
        // 根据id找出code
        let option = this.warehouseOptions?.find(e => e.id === newVal);
        if (option) {
          this.form.warehouseCode = option.warehouseCode;
        } else {
          // 可选：处理没有找到匹配项的情况
          this.form.warehouseCode = ''; // 或 null, undefined, 或其他默认值
        }
      }
    }
  },
  created() {
    this.getDicts("store_product_tui_cate").then((response) => {
      this.productTuiCateOptions = response.data;
    });
    this.getDicts("store_product_enable").then((response) => {
      this.isNewOptions = response.data;
      this.isBestOptions = response.data;
      this.isHotOptions = response.data;
      this.isGoodOptions=response.data;
      this.isDisplayOptions=response.data;
    });
    this.getDicts("store_product_type").then((response) => {
      this.productTypeOptions = response.data;
    });
    this.getDicts("store_product_is_show").then((response) => {
      this.isShowOptions = response.data;
    });
    getAllShippingTemplates().then(response => {
      this.templateList =response.data;
    });
    getAllStoreProductRule().then(response => {
      this.ruleList =response.data;
    });
    this.getTreeselect();
    this.getList();

    this.loadWarehouseOptions();
  },
  methods: {
    // 加载仓库数据
    loadWarehouseOptions(){
      listWarehousesAll({
        isActive: 1
      }).then((response) => {
        this.warehouseOptions = response.data;
      });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    handleImport() {
      this.upload.title = "商品导入";
      this.upload.open = true;
    },
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 删除表格中的属性行（仅前端列表，保存时提交剩余行）
    delAttrTable (index) {
      this.manyFormValidate.splice(index, 1);
    },
    resetSpecState() {
      this.attrs = [];
      this.manyFormValidate = [];
      this.$set(this.form, 'header', []);
      this.createBnt = true;
      this.showIput = false;
      this.clearAttr();
    },
    buildSpecHeaderFromAttrs(attrs) {
      const align = 'center';
      const valueHeaders = (attrs || []).map((attr, index) => ({
        title: attr.value,
        minWidth: '130',
        align,
        key: 'value' + (index + 1),
        slot: 'value' + (index + 1)
      }));
      const fixedHeaders = [
        { title: '图片', slot: 'image', align, minWidth: 80 },
        { title: '售价', slot: 'price', align, minWidth: 120 },
        { title: '代理价', slot: 'agentPrice', align, minWidth: 120 },
        { title: '成本价', slot: 'cost', align, minWidth: 140 },
        { title: '原价', slot: 'otPrice', align, minWidth: 140 },
        { title: '库存', slot: 'stock', align, minWidth: 140 },
        { title: '商品编号', slot: 'barCode', align, minWidth: 140 },
        { title: '组合编号', slot: 'groupBarCode', align, minWidth: 200 },
        { title: '重量(KG)', slot: 'weight', align, minWidth: 140 },
        { title: '体积(m³)', slot: 'volume', align, minWidth: 140 },
        { title: '所需积分', slot: 'integral', align, minWidth: 140 },
        { title: '一级返佣', slot: 'brokerage', align, minWidth: 140 },
        { title: '二级返佣', slot: 'brokerageTwo', align, minWidth: 140 },
        { title: '三级返佣', slot: 'brokerageThree', align, minWidth: 140 }
      ];
      return valueHeaders.concat(fixedHeaders);
    },
    parseAttrsFromResponse(attrList) {
      this.attrs = [];
      if (!attrList || !attrList.length) {
        return;
      }
      attrList.forEach(item => {
        this.attrs.push({
          value: item.attrName,
          detail: item.attrValues ? item.attrValues.split(',') : []
        });
      });
    },
    // 编辑多规格：同步用数据库 values 填表，避免再次打开时表头/数据空白
    loadMultiSpecTable(attrs, values, seq) {
      if (seq !== undefined && seq !== this.editSeq) {
        return;
      }
      const safeAttrs = attrs || [];
      this.$set(this.form, 'header', this.buildSpecHeaderFromAttrs(safeAttrs));
      if (values && values.length > 0) {
        this.manyFormValidate = values.map(v => this.mapAttrValueToRow(v, safeAttrs));
      } else if (safeAttrs.length > 0) {
        this.manyFormValidate = [];
        this.generate();
      } else {
        this.manyFormValidate = [];
      }
      this.createBnt = true;
    },
    loadEditorContent() {
      this.$nextTick(() => {
        if (!this.$refs.myeditor) {
          return;
        }
        this.$refs.myeditor.setText(this.form.description || '');
      });
    },
    mapAttrValueToRow(value, attrs) {
      const row = Object.assign({}, value);
      if (value.detail && typeof value.detail === 'object') {
        attrs.forEach((attr, index) => {
          const key = 'value' + (index + 1);
          if (value.detail[attr.value] !== undefined) {
            row[key] = value.detail[attr.value];
          }
        });
      }
      const skuParts = (value.sku || '').split(',');
      attrs.forEach((attr, index) => {
        const key = 'value' + (index + 1);
        if (row[key] === undefined && skuParts[index] !== undefined) {
          row[key] = skuParts[index];
        }
      });
      return row;
    },
    addBtn () {
      this.clearAttr();
      this.createBnt = false;
      this.showIput = true;
    },
    //生成SKU
    generate () {
      genFormatAttr(this.form.productId, { attrs: this.attrs }).then(res => {
        if(this.form.specType === 0){
            this.oneFormValidate = res.value;
            this.form.header = res.header;
            let header = res.header;
            header.pop();
            this.oneFormValidate.map((item) => {
              if(this.imageArr.length>0){
                item.image = this.imageArr[0]
              }
            });
        }else if(this.form.specType === 1) {
            this.manyFormValidate = res.value;
            const header = (res.header || []).filter(h => h.slot !== 'action');
            this.form.header = header;
        }

      }).catch(res => {
      })
    },
    // 取消添加新规格
    closeAttrName () {
      this.showIput = false;
      this.createBnt = true;
    },
    clearAttr () {
      this.formDynamic.attrsName = '';
      this.formDynamic.attrsVal = '';
    },
    // 删除规格
    handleRemoveRole (index) {
      this.attrs.splice(index, 1);
      if (this.attrs.length === 0) {
        this.manyFormValidate = [];
        this.form.header = [];
        return;
      }
      this.generate();
    },
    // 删除属性
    handleRemove2 (item, index) {
      item.splice(index, 1);
    },
    // 添加规则名称
    createAttrName () {
      if (this.formDynamic.attrsName && this.formDynamic.attrsVal) {
        let data = {
          value: this.formDynamic.attrsName,
          detail: [
            this.formDynamic.attrsVal
          ]
        };
        this.attrs.push(data);
        var hash = {};
        this.attrs = this.attrs.reduce(function (item, next) {
          hash[next.value] ? '' : hash[next.value] = true && item.push(next);
          return item
        }, [])
        this.clearAttr();
        this.showIput = false;
        this.createBnt = true;
      } else {
        this.$message.warning('请添加完整的规格！');
      }
    },
    // 添加属性
    createAttr (num, idx) {
      if (num) {
        this.attrs[idx].detail.push(num);
        var hash = {};
        this.attrs[idx].detail = this.attrs[idx].detail.reduce(function (item, next) {
          hash[next] ? '' : hash[next] = true && item.push(next);
          return item
        }, [])
      } else {
        this.$message.warning('请添加属性！');
      }
    },
    confirm () {
      let that = this;
      that.createBnt = true;
      if (that.form.selectRule==null||that.form.selectRule.trim().length <= 0) {
        return this.$message({
          message:'请选择属性',
          type: 'error'
        });
      }
      that.ruleList.forEach(function (item, index) {
        if (item.ruleName === that.form.selectRule) {
          that.attrs =JSON.parse( item.ruleValue);

        }
      });

    },
    updateText(text){
      this.form.description=text
    },
    handleClick(tab, event) {
      this.queryParams.isShow=tab.name;
      this.getList();
    },
    /** 转换商品分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.cateId,
        label: node.cateName,
        children: node.children
      };
    },
    getTreeselect() {
      getAllStoreProductCategory().then(response => {
        this.categoryOptions = [];
        const data = this.handleTree(response.data, "cateId", "pid");
        this.categoryOptions=data;
      });
    },
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      listStoreProduct(this.queryParams).then(response => {
        this.storeProductList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.editSeq += 1;
      this.resetSpecState();
      this.form = {
        productId: 0,
        image: null,
        sliderImage: null,
        productName: null,
        productInfo: null,
        keyword: null,
        barCode: null,
        cateId: null,
        price: null,
        vipPrice: null,
        otPrice: null,
        postage: null,
        unitName: null,
        sort: null,
        sales: null,
        stock: null,
        isShow: "0",
        isHot: "0",
        isBenefit: "0",
        isBest: "0",
        isNew: "0",
        description: null,
        createTime: null,
        updateTime: null,
        isPostage: null,
        isDel: null,
        giveIntegral: null,
        cost: null,
        isGood: "0",
        browse: null,
        codePath: null,
        tempId: "",
        specType: 0,
        isIntegral: null,
        integral: null,
        productType: "1",
        prescribeCode: null,
        prescribeSpec: null,
        prescribeFactory: null,
        prescribeName: null,
        isDisplay:"1",
        warehouseCode: null,
        warehouseId: null,
        taxClassificationCode: null,
        invoiceName: null
      };
      this.resetForm("form");
      this.oneFormValidate = [
        {
          image: '',
          price: 0,
          agentPrice: 0,
          cost: 0,
          otPrice: 0,
          stock: 0,
          barCode: '',
          weight: 0,
          volume: 0,
          integral: 0,
          brokerage:0,
          brokerageTwo:0,
          warehouseCode:null,
          taxRate: null
        }
      ];
      this.photoArr=[];
      this.imageArr=[];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();

      this.open = true;
      this.title = "添加商品";
      setTimeout(() => {
        this.$refs.myeditor.setText("");
      }, 500);

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const seq = this.editSeq;
      const productId = row && row.productId ? row.productId : (Array.isArray(this.ids) ? this.ids[0] : this.ids);
      if (!productId) {
        return this.$message.warning('请先选择要修改的商品');
      }
      getStoreProduct(productId).then(response => {
        if (seq !== this.editSeq) {
          return;
        }
        this.form = response.data;
        this.form.isShow = response.data.isShow.toString();
        this.form.isHot = response.data.isHot.toString();
        this.form.isGood = response.data.isGood.toString();
        this.form.isBest = response.data.isBest.toString();
        this.form.isNew = response.data.isNew.toString();
        this.form.productType = response.data.productType.toString();
        this.form.isDisplay = response.data.isDisplay.toString();
        if (this.form.tuiCateId != null) {
          this.form.tuiCateId = response.data.tuiCateId.toString();
        }
        this.parseAttrsFromResponse(response.attrs);
        if (this.form.image != null) {
          this.imageArr = this.form.image.split(",");
        } else {
          this.imageArr = [];
        }
        if (this.form.sliderImage != null) {
          this.photoArr = this.form.sliderImage.split(",");
        } else {
          this.photoArr = [];
        }
        this.open = true;
        this.title = "修改商品";
        this.$nextTick(() => {
          if (seq !== this.editSeq) {
            return;
          }
          this.loadEditorContent();
          if (this.form.specType === 0) {
            this.manyFormValidate = [];
            this.generate();
          } else if (this.form.specType === 1) {
            this.oneFormValidate = [
              {
                image: '',
                price: 0,
                agentPrice: 0,
                cost: 0,
                otPrice: 0,
                stock: 0,
                barCode: '',
                weight: 0,
                volume: 0,
                integral: 0,
                brokerage: 0,
                brokerageTwo: 0,
                taxRate: null
              }
            ];
            this.loadMultiSpecTable(this.attrs, response.values || [], seq);
          }
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.specType ===0 ){
            this.form.items = [];
            this.form.values = this.oneFormValidate;
          }else{
            this.form.items = this.attrs;
            this.form.values = this.manyFormValidate;
          }
          if(this.form.specType === 1 && this.manyFormValidate.length===0){
            return this.$message.warning('请点击生成规格！');
          }
          addOrEdit(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess("修改成功");
              this.open = false;
              this.reset();
              this.getList();
            }
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids;
      this.$confirm('是否确认删除商品编号为"' + productIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delStoreProduct(productIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    putOn() {
       const productIds =this.ids;
      if(productIds==null||productIds==""){
         return this.$message("未选择商品");
      }
      this.$confirm('是否确认批量上架商品?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return putOn(productIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("上架成功");
        }).catch(function() {});
    },
    pullOff() {
      const productIds =this.ids;
      if(productIds==null||productIds==""){
         return this.$message("未选择商品");
      }

      this.$confirm('是否确认批量下架商品?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return pullOff(productIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("下架成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有商品数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportStoreProduct(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    /** 处理税率输入过滤 */
    handleTaxRateInput(value, row) {
      // 只保留数字和小数点
      let filteredValue = value.replace(/[^\d.]/g, '');
      // 确保只有一个小数点
      const parts = filteredValue.split('.');
      if (parts.length > 2) {
        filteredValue = parts[0] + '.' + parts.slice(1).join('');
      }
      // 限制小数点后最多2位
      if (parts.length === 2 && parts[1].length > 2) {
        filteredValue = parts[0] + '.' + parts[1].substring(0, 2);
      }
      // 限制最大值100
      if (filteredValue && parseFloat(filteredValue) > 100) {
        filteredValue = '100';
      }
      row.taxRate = filteredValue;
    }
  }
};
</script>
