<template>
  <ContainerQuery>
    <!--    <div slot="left">-->
    <!--      <el-button size="small" type="primary">导出</el-button>-->
    <!--    </div>-->
    <el-form
      v-if="$accessCheck($Access.PriceTableSearch)"
      slot="right"
      :inline="true"
      :model="form"
      size="small"
    >
      <el-form-item>
        <el-input
          v-model="keyword"
          placeholder="商品名称"
          clearable
          style="width: 220px"
          @keyup.enter.native="pageChange(1)"
          @clear="pageChange(1)"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="pageChange(1)"
          ></el-button>
        </el-input>
      </el-form-item>
      <el-form-item>
        <GoodsCategory
          v-model="form.categoryId"
          check-strictly
          clearable
          size="small"
          width="150"
          @change="categoryChange"
        />
      </el-form-item>
      <el-form-item v-if="systemType === 1">
        <SelectShop
          v-model="shopId"
          width="150"
          @change="shopConfirm"
          @clear="shopClear"
        />
      </el-form-item>
    </el-form>

    <el-table
      ref="priceTable"
      size="small"
      :data="tableData"
      @selection-change="selectionGoodsChange"
      @expand-change="showSpec"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        prop="id"
        label="ID"
        fixed="left"
        width="60"
      ></el-table-column>
      <el-table-column
        prop="shopName"
        label="商铺名称"
        show-overflow-tooltip
        min-width="160"
      ></el-table-column>
      <el-table-column
        prop="goodsName"
        label="商品名称"
        show-overflow-tooltip
        min-width="160"
      ></el-table-column>
      <el-table-column
        prop="code"
        label="商品编码"
        show-overflow-tooltip
        min-width="120"
      ></el-table-column>

      <el-table-column
        v-if="systemType === 3"
        prop="masterPrice.unitName"
        label="主单位"
        width="100"
      ></el-table-column>
      <el-table-column
        v-if="systemType === 3"
        prop="masterPrice.salePrice"
        label="主单位价格"
        width="100"
      >
        <template slot-scope="scope">
          {{ $_common.formattedNumber(scope.row.masterPrice.salePrice) }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="priceFlag"
        align="left"
        label="价格"
        width="80"
        type="expand"
      >
        <template slot-scope="scope">
          <ul class="sku-ul">
            <li
              v-for="(item, index) in scope.row.goods_sku_list"
              :key="index"
              class="sku-li"
            >
              <div class="clearfix">
                <div class="float_left">
                  <img class="sku-img" :src="item.specImage" alt="" />
                </div>
                <div class="sku-info float_left">
                  <p>
                    <span class="label">规格:</span>
                    {{ item.unitName }};{{ item.specValueName }}
                  </p>
                  <p>
                    <span class="label">阶梯价:</span>
                    {{ item.enabledLadder === 1 ? "是" : "否" }}；
                    <span v-if="!item.enabledLadder">
                      <span class="label">销售价:</span>
                      ¥{{ item.salePrice }}
                    </span>
                  </p>
                </div>
              </div>
              <div v-if="item.enabledLadder" class="clearfix">
                <div class="float_left" style="width: 50px; margin-right: 10px">
                  销售价:
                </div>
                <div class="float_left">
                  <p v-for="(price, indexP) in item.ladderPrice" :key="indexP">
                    <span>
                      数量:
                      <span style="color: #ff4040">
                        {{ price.from }}-{{
                          indexP === item.ladderPrice.length - 1
                            ? "∞"
                            : price.to
                        }}
                      </span>
                      ,
                    </span>
                    <span>
                      价格:
                      <span style="color: #ff4040">¥{{ price.price }}</span>
                      ;
                    </span>
                  </p>
                </div>
              </div>
            </li>
          </ul>
        </template>
      </el-table-column>
      <el-table-column
        v-if="inventoryFlag"
        prop="inventorTotal"
        label="总库存"
        align="left"
        min-width="100"
      >
        <template slot-scope="scope">
          <span
            :class="[
              scope.row.inventorTotal <= 0 ? 'danger-status' : 'success-status',
            ]"
          >
            {{ $_common.formatNub(scope.row.inventorTotal) }}
          </span>
        </template>
      </el-table-column>
      <!--      <el-table-column-->
      <!--        prop="costPrice"-->
      <!--        label="成本价"-->
      <!--        align="center"-->
      <!--        min-width="80"-->
      <!--      >-->
      <!--        <template slot-scope="scope">-->
      <!--          {{ scope.row.costPrice-0 }}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      销售价（标准价和阶梯价两种展示类型）-->
      <el-table-column
        v-if="classifyFlag"
        prop="categoryName"
        label="商品分类"
        min-width="100"
      ></el-table-column>
      <el-table-column prop="address" label="操作" min-width="80px">
        <template slot="header" slot-scope="scope">
          <span v-if="false">{{ scope.$index }}</span>
          <span class="operation">操作</span>
          <el-popover popper-class="custom-table-checkbox" trigger="click">
            <el-checkbox-group v-model="checkList">
              <el-checkbox
                v-for="(item, index) in columns"
                :key="index"
                :label="item.label"
                @change="change"
              ></el-checkbox>
            </el-checkbox-group>
            <el-button
              slot="reference"
              icon="el-icon-setting"
              type="text"
            ></el-button>
          </el-popover>
        </template>
        <template slot-scope="scope">
          <el-button
            v-if="$accessCheck($Access.AdjustPriceAdd)"
            type="text"
            @click="openDrawer(scope.row)"
          >
            调价
          </el-button>
          <span v-else>--</span>
        </template>
      </el-table-column>
    </el-table>
    <el-drawer
      class="edit-drawer"
      :title="goodsName"
      :visible.sync="drawer"
      size="50%"
      direction="rtl"
    >
      <AddGoodsAdjustPrice
        v-if="drawer"
        :good-id="goods_id"
        @handelSuccess="adSuccess"
      />
    </el-drawer>
    <FooterPage
      :page-size="pageSize"
      :total-page.sync="total"
      :current-page.sync="page"
      @pageChange="pageChange"
      @sizeChange="sizeChange"
    >
      <div
        v-if="$accessCheck($Access.AdjustPriceAdd)"
        slot="btn-div"
        class="foot-btn-div"
      >
        <span class="batch-checkbox">
          <el-checkbox
            v-model="checkedAll"
            @change="checkAllChange"
          ></el-checkbox>
        </span>
        <el-button size="small" @click="moreAdPrice">批量调价</el-button>
      </div>
    </FooterPage>
    <el-dialog
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      title="批量调价"
      :visible.sync="isMorePrice"
      width="40%"
    >
      <el-table border :data="morePrice">
        <el-table-column prop="resPrice" align="center">
          <template slot-scope="scope">{{ scope.row.resPrice }}=</template>
        </el-table-column>
        <el-table-column
          prop="type"
          label="价格类型"
          align="center"
        ></el-table-column>
        <el-table-column prop="symbolP" label="运算符号" align="center">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.symbolP"
              size="mini"
              placeholder="请选择"
            >
              <el-option
                v-for="(item, index) in symbolP_list"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="调价数字" align="center">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.num"
              style="width: 100%"
              :controls="false"
              size="mini"
            ></el-input-number>
          </template>
        </el-table-column>
      </el-table>
      <el-alert
        style="margin-top: 10px"
        type="warning"
        :closable="false"
        show-icon
      >
        <p>1.价格修改范围包含销售价，阶梯价等所有价格</p>
        <p>
          2.批量调价基于基本的运算公式进行调价，举例一个商品的销售价格是100元。
          <br />
          调价公式 ：订货价=销售价-1
          <br />
          结果等于 ： 99=100-1
        </p>
      </el-alert>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isMorePrice = false">取 消</el-button>
        <el-button
          :loading="is_batch_loading"
          type="primary"
          @click="batchPrice"
        >
          确 定
        </el-button>
      </span>
    </el-dialog>
  </ContainerQuery>
</template>

<script>
  import GoodsCategory from "@/component/common/GoodsCategory.vue";
  import AddGoodsAdjustPrice from "./AddGoodsAdjustPrice";
  import SelectShop from "@/component/goods/SelectShop.vue";
  import { getGoodsInfo } from "@/api/goods";
  import { batchPrice, getAllGoodsPrice, searchPrice } from "@/api/Price";
  import { mapGetters } from "vuex";
  export default {
    name: "PriceTable",
    components: {
      AddGoodsAdjustPrice,
      GoodsCategory,
      SelectShop,
    },
    data() {
      return {
        is_batch_loading: false,
        checkedAll: false,
        morePrice: [
          {
            type: "销售价",
            symbolP: "",
            num: "",
            resPrice: "订货价",
          },
          {
            type: "阶梯价",
            symbolP: "",
            num: "",
            resPrice: "订货价",
          },
        ],
        symbolP_list: ["+", "-", "*", "/"],
        goods_item: {},
        isMorePrice: false,
        keyword: "",
        brandId: "",
        categoryId: "",
        enableStatus: "",
        shopId: "",
        drawer: false,
        sel_shop: false,
        spec_loading: false,
        tableData: [],
        options: [],
        goods_id: 0,
        total: 0,
        page: 1,
        pageSize: 10,
        goodsName: "",
        form: {
          shop: "",
          categoryId: [],
        },
        choose_data: [],
        checkList: ["商品分类", "主单位", "总库存", "价格"],
        columns: [
          {
            label: "商品分类",
          },
          {
            label: "主单位",
          },
          {
            label: "总库存",
          },
          {
            label: "价格",
          },
        ],
        classifyFlag: true,
        unitFlag: true,
        inventoryFlag: true,
        priceFlag: true,
      };
    },
    computed: {
      ...mapGetters({
        storeData: "MUser/storeData",
      }),
    },

    created() {
      this.getAllGoodsPrice();
    },
    activated() {
      if (this.$_isInit()) return;
      this.getData();
    },
    methods: {
      async showSpec(row) {
        const index = this.tableData.findIndex((item) => item.id === row.id);
        if (!this.tableData[index].goods_sku_list.length) {
          const { data } = await getGoodsInfo(row.id);

          if (data.specType === 2) {
            this.tableData[index].goods_sku_list = data.specMultiple.map(
              (item) => {
                const specValueName = item.specGroup
                  .map((itemS) => {
                    return itemS.specValueName;
                  })
                  .join(";");
                return {
                  ...item,
                  specValueName: specValueName,
                  specImage: item.specImage || data.images[0],
                };
              }
            );
          } else if (data.specType === 1) {
            this.tableData[index].goods_sku_list = data.specMultiple.map(
              (item) => {
                return {
                  ...item,
                  specValueName: "",
                  specImage: item.specImage || data.images[0],
                };
              }
            );
          }
        }
      },
      // 批量调价
      moreAdPrice() {
        if (this.choose_data.length) {
          this.isMorePrice = true;
        } else {
          this.$message.warning("请选择要操作的商品");
        }
      },
      async batchPrice() {
        this.is_batch_loading = true;
        const data = await batchPrice({
          rows: this.choose_data,
          sales: {
            adj: this.morePrice[0].symbolP,
            float: this.morePrice[0].num,
          },
          ladder: {
            adj: this.morePrice[1].symbolP,
            float: this.morePrice[1].num,
          },
        });
        this.is_batch_loading = false;

        this.isMorePrice = false;
        this.$message.success("操作成功");
        this.getData();
      },
      // 勾选商品
      selectionGoodsChange(val) {
        this.choose_data = val.map((item) => {
          return {
            goodsId: item.id,
            shopId: item.shopId,
          };
        });
        this.checkedAll = val.length === this.tableData.length;
      },
      // 打开抽屉组件
      openDrawer(row) {
        this.goods_id = row.goodsId;
        this.goodsName = row.goodsName;
        this.drawer = true;
      },
      // 抽屉组件添加成功的回调
      adSuccess() {
        this.drawer = false;
        this.getData();
      },
      // 获取列表
      async getAllGoodsPrice() {
        const params = {
          page: this.page,
          pageSize: this.pageSize,
          shopId: this.shopId,
        };
        // 多商户传商户id
        if (this.systemType === 3) {
          params.merchantId = this.storeData.merchantData.id;
        }
        const { data, pageTotal } = await getAllGoodsPrice(params);

        this.tableData = data.map((item) => {
          return {
            ...item,
            goods_sku_list: [],
          };
        });
        // this.tableData = data.data.map(item => {
        //   const masterUnit = item.skuData.find(itemS => itemS.isMaster === 5)
        //   return {
        //     ...item,
        //     masterUnit: masterUnit
        //   }
        // })
        this.total = pageTotal;
      },
      // 判断当前使用方法为列表接口还是搜索引擎接口 获取列表数据
      getData() {
        const obj = {
          keyword: this.keyword,
          shopId: this.shopId,
          categoryId: this.categoryId,
        };
        const isKey = this.$_common.isSerch(obj);
        if (isKey) {
          this.searchPrice();
        } else {
          this.getAllGoodsPrice();
        }
      },
      //  价格管理的搜索
      async searchPrice() {
        const params = {
          page: this.page,
          pageSize: this.pageSize,
          keyword: this.keyword,
          shopId: this.shopId,
          categoryId: this.categoryId,
        };
        // 多商户传商户id
        if (this.systemType === 3) {
          params.merchantId = this.storeData.merchantData.id;
        }
        const { data, pageTotal } = await searchPrice(params);

        this.tableData = data.map((item) => {
          return {
            ...item,
            goods_sku_list: [],
          };
        });
        this.total = pageTotal;
      },
      // 分类
      categoryChange(val) {
        if (val && val.length) {
          this.categoryId = val[val.length - 1];
        } else {
          this.categoryId = "";
        }
        this.pageChange(1);
      },
      // 商铺搜索
      shopConfirm(val, row) {
        this.shopId = row ? row[0].id : 0;
        this.form.shop = row ? row[0].name : "";
        this.pageChange(1);
      },
      // 商铺清空
      shopClear() {
        this.shopId = "";
        this.pageChange(1);
      },
      pageChange(page) {
        this.page = page;
        this.getData();
      },
      sizeChange(size) {
        this.pageSize = size;
        this.pageChange(1);
      },
      checkAllChange() {
        this.$refs.priceTable.toggleAllSelection();
      },
      change() {
        this.classifyFlag = this.checkList.some((item) => item === "商品分类");
        this.unitFlag = this.checkList.some((item) => item === "主单位");
        this.inventoryFlag = this.checkList.some((item) => item === "总库存");
        this.priceFlag = this.checkList.some((item) => item === "价格");
      },
    },
  };
</script>

<style scoped lang="scss">
  .price-view {
    border-bottom: 1px solid #eee;
  }
  .ladprice-span {
    color: #f56c6c;
    min-width: 50px;
    height: 30px;
    line-height: 30px;
    display: inline-block;
    border: 1px solid #eee;
    text-align: center;
    margin: 5px 0;
  }
  .ladprice-p {
    padding-bottom: 5px;
  }
  .price-label {
    font-weight: 600;
    display: inline-block;
  }
  .custom-table-checkbox {
    .el-checkbox {
      display: block !important;
      margin: 0 0 $base-padding/4 0;
    }
  }
  .sku-ul {
    .sku-li {
      display: inline-block;
      margin-right: 10px;
      border: 1px solid #ebeef5;
      padding: 10px;
      width: 294px;
      vertical-align: middle;
      .sku-img {
        width: 50px;
        height: 50px;
        object-fit: cover;
        margin-right: 8px;
      }
      .sku-info {
        line-height: 23px;
        color: #111111;
        .label {
          display: inline-block;
          width: 50px;
          color: #666666;
          text-align: right;
        }
      }
    }
  }
</style>
