<template>
  <div class="goods pagePadding">
    <div
      v-if="powers && powers.length > 0 && powers.some((item) => item == '001')"
    >
      <el-row style="margin-bottom: 10px">
        <el-col :span="6" style="width: 316px">
          <period-date-picker
            :start="parmValue.start"
            :end="parmValue.end"
            :type="1"
            :size="searchSize"
            @timeReturned="timeReturned($event)"
          ></period-date-picker>
        </el-col>
        <el-col :span="18" id="el-cor-full-style">
          <el-row :gutter="10">
            <el-col :span="6">
              <el-cascader
                v-model="parmValue.catid"
                style="width: 100%"
                filterable
                :size="searchSize"
                clearable
                placeholder="商品分类"
                :options="catOptions"
                :props="{ expandTrigger: 'hover', checkStrictly: true }"
                @change="handleChange"
              ></el-cascader>
            </el-col>
            <el-col :span="6">
              <el-select
                v-model="parmValue.status"
                filterable
                clearable
                :size="searchSize"
                placeholder="请选择状态"
                style="width: 100%"
              >
                <el-option
                  v-for="item in statusList"
                  :key="'status' + item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-col>

            <el-col :span="6">
              <el-input
                :size="searchSize"
                style="100%"
                v-model="parmValue.supplier_name"
                :maxlength="40"
                placeholder="供货商名称"
              ></el-input>
            </el-col>
            <el-col :span="6">
              <el-input
                :size="searchSize"
                style="100%"
                v-model="parmValue.good_code"
                :maxlength="40"
                placeholder="商品编码"
              ></el-input>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row style="margin-bottom: 18px">
        <el-col :span="6" style="width: 316px">
          <el-input
            :size="searchSize"
            :maxlength="10"
            placeholder="最低售价"
            v-model="parmValue.sale_price_start"
            style="width: 150px"
          ></el-input>
          <samp>至</samp>
          <el-input
            :size="searchSize"
            :maxlength="10"
            placeholder="最高售价"
            v-model="parmValue.sale_price_end"
            style="width: 150px"
          ></el-input>
        </el-col>

        <el-col :span="18" id="el-cor-full-style">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-input
                :size="searchSize"
                v-model="parmValue.goods_name"
                :maxlength="40"
                placeholder="商品名称"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="searchList"
                ></el-button>
              </el-input>
            </el-col>
            <el-col :span="12">
              <el-button
               v-if="powers.some((item) => item == '024')"
                type="warning"
                class="fl"
                :size="searchSize"
                @click="restSearch"
              >
                重置
              </el-button>
              <el-button
               v-if="powers.some((item) => item == '002')"
                type="primary"
                :size="searchSize"
                class="fr"
                style="margin-left: 5px"
                @click="searchList"
              >
                刷新
              </el-button>
              <el-button
               v-if="powers.some((item) => item == '003')"
                type="success"
                :size="searchSize"
                style="float: right"
                @click="openModal('add', false)"
              >
                添加
              </el-button>
            </el-col>
          </el-row></el-col
        >
      </el-row>
      <el-table
        :data="tableData"
        stripe
        v-loading="loading"
        border
        :size="size"
        style="width: 100%"
      >
        <el-table-column label="商品信息" align="left" min-width="165">
          <template slot-scope="item">
            <div class="good_name_title">
              {{ item.row.good_name }}
            </div>
            <div
              class="good_name_img"
              v-if="item.row.galleyList && item.row.galleyList.length > 0"
            >
              <img
                v-for="(img, i) in item.row.galleyList"
                :key="item.row.id + 'goodimg' + i"
                :src="img"
                @click="showGalley(item.row.galleyList, i)"
                alt=""
              />
            </div> </template
        ></el-table-column>
        <el-table-column label="供应商信息" show-overflow-tooltip align="left">
          <template slot-scope="item">
            <div v-if="item.row.supplier_info">
              <div class="good_name_title">
                企业：{{ item.row.supplier_info.company }}
              </div>
              <div class="good_name_title">
                联系人：{{ item.row.supplier_info.name }}
              </div>
            </div>
          </template></el-table-column
        >
        <el-table-column
          prop="good_code"
          label="商品编码"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <el-table-column
          prop="catName"
          label="商品分类"
          show-overflow-tooltip
          align="center"
        ></el-table-column>

        <el-table-column label="状态" show-overflow-tooltip align="center">
          <template slot-scope="scope">
            <el-tag
              v-if="scope.row.status === '1'"
              type="success"
              :class="{ 'hover-tag': powers.some((item) => item == '004') }"
              :size="tablebtnSize"
              @click="
                statusConfirm(
                  scope.row.id,
                  scope.row.status,
                  powers.some((item) => item == '026')
                )
              "
            >
              <i
                class="el-icon-thumb"
                v-if="powers.some((item) => item == '026')"
                style="margin-right: 1px"
              ></i>
              销售中</el-tag
            >
            <el-tag
              v-else
              :class="{ 'hover-tag': powers.some((item) => item == '026') }"
              :size="tablebtnSize"
              type="warning"
              @click="
                statusConfirm(
                  scope.row.id,
                  scope.row.status,
                  powers.some((item) => item == '026')
                )
              "
            >
              <i
                class="el-icon-thumb"
                v-if="powers.some((item) => item == '026')"
                style="margin-right: 1px"
              ></i>
              已下架</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="addtime"
          label="创建时间"
          show-overflow-tooltip
          align="center"
        ></el-table-column>
        <el-table-column fixed="right" label="操作" align="center">
          <template slot-scope="scope">
            <el-link
              v-if="powers.some((item) => item == '011')"
              type="primary"
              style="margin: 0 4px"
              :underline="false"
              :size="tablebtnSize"
              @click="
                showPrice(
                  scope.row.LimitPrice,
                  scope.row.left,
                  scope.row.right,
                  scope.row.lang
                )
              "
            >
              价格
            </el-link>
            <el-link
              v-if="powers.some((item) => item == '012')"
              type="primary"
              style="margin: 0 4px"
              :underline="false"
              :size="tablebtnSize"
              @click="copy(scope.row.id)"
            >
              复制
            </el-link>
            <el-link
              v-if="
                scope.row.status === '0' && powers.some((item) => item == '005')
              "
              type="primary"
              style="margin: 0 4px"
              :underline="false"
              :size="tablebtnSize"
              @click="openModal(scope.row.id, false)"
            >
              修改
            </el-link>
            <el-link
              v-if="powers.some((item) => item == '006')"
              type="primary"
              style="margin: 0 4px"
              :underline="false"
              :size="tablebtnSize"
              @click="deleteById(scope.row.id, scope.row.status)"
            >
              删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <div
        class="Pagination"
        style="text-align: right; margin-top: 10px"
        v-show="count > 0"
      >
        <el-pagination
          :size="searchSize"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          :current-page="parmValue.page"
          :page-sizes="[10, 15, 20, 30, 40]"
          :page-size="parmValue.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="count"
        ></el-pagination>
      </div>
      <add-edit
        :showModel="showModel"
        :id="modelId"
        :isDetail="isDetail"
        @refresh="searchList"
        @cancel="showModel = false"
      ></add-edit>
      <ladder-price
        :showModel="showLadderPrice"
        :left="left"
        :right="right"
        :lang="lang"
        @cancel="showLadderPrice = false"
      ></ladder-price>
      <imgShow
        :showModel="showImgModel"
        :imgList="imgList"
        :index="index"
        @cancel="showImgModel = false"
      ></imgShow>
    </div>
    <div v-else>
      <no-auth></no-auth>
    </div>
  </div>
</template>
   <script>
import mixinPage from "@/mixins/elPaginationHandle";
import asyncRequest from "@/apis/service/goodStore/goods";
import addEdit from "./addEdit";
import ladderPrice from "./ladderPrice";
import imgShow from "./imgShow";
import PeriodDatePicker from "@/components/PeriodDatePicker";
import statusList from "@/assets/js/statusList";
import { timestampToTime } from "@/utils/validate";
import { mapGetters } from "vuex";
export default {
  name: "goods",
  components: {
    addEdit,
    PeriodDatePicker,
    ladderPrice,
    imgShow,
  },
  data() {
    return {
      imgList: [],
      index: 0,
      showImgModel: false,
      statusList: statusList,
      catOptions: [],
      showLadderPrice: false,
      loading: false,
      showModel: false,
      isDetail: false,
      modelId: 0,
      left: {},
      right: {},
      lang: "0px",
      parmValue: {
        catid: "", //种类id
        start: "", //起始时间,
        end: "", //结束时间
        sale_price_start: "", //最低售价
        sale_price_end: "", //最高售价
        status: "",
        goods_name: "", //商品名称
        good_code: "", //商品code
        supplier_name: "", //供货商
        page: 1, // 页码
        size: 10, // 每页显示条数
      },
      count: 0, // 总条数
      tableData: [],
      headLadder: {
        num: "起订量≥",
        price: "成本价",
      },
    };
  },
  mixins: [mixinPage],
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    powers() {
      let tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "goods"
        ) || {};
      if (tran && tran.action && tran.action.length > 0) {
        return tran.action;
      } else {
        return [];
      }
    },
  },
  mounted() {
    this.searchList();
    this.getAllCat();
  },

  methods: {
    restSearch() {
      this.parmValue = {
        catid: "", //种类id
        start: "", //起始时间,
        end: "", //结束时间
        sale_price_start: "", //最低售价
        sale_price_end: "", //最高售价
        status: "",
        goods_name: "", //商品名称
        good_code: "", //商品code
        supplier_name: "", //供货商
        page: 1, // 页码
        size: 10, // 每页显示条数
      };
      this.searchList();
    },
    async handleChange() {
      this.parmValue.page = 1;
      await this.searchList();
    },
    async timeReturned(e) {
      if (e.startTime !== "") {
        this.parmValue.start = timestampToTime(e.startTime);
      } else {
        this.parmValue.start = "";
      }

      if (e.endTime !== "") {
        this.parmValue.end = timestampToTime(e.endTime);
      } else {
        this.parmValue.end = "";
      }
      if (this.parmValue.start !== "" && this.parmValue.end !== "") {
        this.parmValue.page = 1;
        await this.searchList();
      }
    },
    openModal(id, isDetail) {
      if (id !== "add") {
        this.$message.warning("正在开发中！");
      } else {
        this.showModel = true;
        this.modelId = id;
        this.isDetail = isDetail;
      }
    },
    showGalley(list, i) {
      this.imgList = list;
      this.index = i;
      this.showImgModel = true;
    },
    async copy(id) {
      let res = await asyncRequest.copy({ id: id });
      if (res.code === 0) {
        this.$notify.success({
          title: "商品复制成功！",
          message: "",
        });
        this.searchList();
      }
    },
    async deleteById(id, status) {
      if (status === "0") {
        await this.$confirm("确定要删除该商品？", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            let res = await asyncRequest.delete({ goodids: id });
            if (res.code === 0) {
              this.$notify.success({
                title: "删除成功",
                message: "",
              });
              this.searchList();
            }
          })
          .catch(() => {
            console.log("取消");
          });
      } else {
        this.$message.warning("只有已下架的商品才能被删除！");
      }
    },
    showPrice(attr, left, right, lang) {
      if (attr && attr.length > 0) {
        this.left = left;
        this.right = right;
        this.lang = lang;
        this.showLadderPrice = true;
      } else {
        this.$message.warning("该商品暂无阶梯价格信息！");
      }
    },
    async searchList() {
      let obj = JSON.parse(JSON.stringify(this.parmValue));

      if (obj.catid === "") {
        obj.catid = "0";
      }
      this.loading = true;
      let res = await asyncRequest.list(obj);
      if (res.code === 0 && res.data) {
        let list = res.data.list;

        list = list.map((v1) => {
          v1.catName = "";
          v1.galleyList = v1.galley.split(",");
          v1.addtime = v1.addtime.replaceAll(".000", "");
          if (v1 && v1.cat && v1.cat.length > 0) {
            v1.cat.forEach((v2, index) => {
              v1.catName += index !== 0 ? "/" + v2.cat_name : v2.cat_name;
            });
          } else {
            v1.catName = "";
          }
          if (v1 && v1.LimitPrice && v1.LimitPrice.length > 0) {
            v1.left = {
              header: [],
              spec: [],
            };
            v1.right = {
              header: [],
              spec: [],
            };
            v1.left.header = v1.LimitPrice[0].spec;
            v1.lang = v1.left.header.length * 100 + "px";
            let ladderNum = 0;
            v1.LimitPrice.forEach((a) => {
              if (a.limit && a.limit.length > ladderNum) {
                ladderNum = a.limit.length;
              }
              if (a.spec && a.spec.length > 0) {
                v1.left.spec.push(a.spec);
              }
            });
            for (let i = 0; i < ladderNum; i++) {
              v1.right.header.push(this.headLadder);
            }

            v1.right.spec = v1.LimitPrice;
            v1.right.spec.map((v1) => {
              if (v1.limit && v1.limit.length > 0) {
                for (let j = 0; j < ladderNum; j++) {
                  if (!v1.limit[j]) {
                    v1.limit.push({
                      begin_num: "",
                      shop_price: "",
                    });
                  }
                }
              }
            });
          }
          return v1;
        });
        this.tableData = list;
        this.count = Number(res.data.count);
      } else {
        this.tableData = [];
        this.count = 0;
      }
      this.loading = false;
    },
    async getAllCat() {
      const res = await asyncRequest.catAll({});
      if (res.code === 0 && res.data) {
        let list = res.data;
        list.map((v1) => {
          v1.value = v1.id;
          v1.label = v1.cat_name;
          if (v1.child && v1.child.length > 0) {
            v1.child.map((v2) => {
              v2.value = v2.id;
              v2.label = v2.cat_name;
              if (v2.child && v2.child.length > 0) {
                v2.child.map((v3) => {
                  v3.value = v3.id;
                  v3.label = v3.cat_name;
                  return v3;
                });
                v2.children = v2.child;
              }
              return v2;
            });
            v1.children = v1.child;
          }
          return v1;
        });
        this.catOptions = list;
      }
    },
    async statusConfirm(id, status, type) {
      if (!type) {
        return;
      }
      await this.$confirm(
        `确定要改为${status === "1" ? "已下架" : "销售中"}？`,
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          this.loading = true;
          const model = {
            goodids: id,
            status: status === "1" ? "0" : "1",
          };
          const res = await asyncRequest.status(model);
          if (res.code === 0) {
            this.loading = false;
            this.$notify.success({
              title: "状态修改成功！",
              message: "",
            });
            await this.searchList();
          } else {
            this.loading = false;
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },
  },
};
</script>
   <style lang="scss" scoped>
.goods {
  $gBC: #dfe6ec;
  .list-table {
    position: relative;
    width: 100%;
    border-top: 1px solid $gBC;
    border-left: 1px solid $gBC;
    .left {
      position: absolute;
      top: 0;
      left: 0;
      z-index: 2;
      background: #fff;
      .header {
        width: 100%;
        display: flex;
        .header-item {
          width: 100px;
          flex: 1;
          padding: 0 10px;
          height: 50px;
          line-height: 50px;
          border-right: 1px solid $gBC;
          border-bottom: 1px solid $gBC;
        }
      }
      .header-body {
        width: 100%;
        position: relative;
        .header-body-row {
          width: 100%;
          display: flex;
          .heder-body-col {
            flex: 1;
            padding: 0 10px;
            height: 30px;
            border-right: 1px solid $gBC;
            border-bottom: 1px solid $gBC;
            line-height: 30px;
          }
        }
      }
    }
    .right {
      position: relative;
      width: 100%;
      display: block;
      overflow-x: scroll;
      .header {
        width: 100%;
        display: flex;
        .header-col {
          min-width: 240px;
          flex: 1;
          height: 50px;
          line-height: 50px;

          // position: relative;
          .header-col-jieti {
            height: 50px;
            line-height: 50px;
            // position: relative;
            width: 100%;
            .header-col-jieti-title {
              // position: relative;
              width: 100%;
              line-height: 25px;
              border-right: 1px solid $gBC;
              border-bottom: 1px solid $gBC;
              height: 25px;
            }
            .header-col-jieti-main {
              // position: relative;
              width: 100%;
              .header-col-item {
                // position: relative;
                height: 25px;
                line-height: 25px;
                width: 50%;
                border-right: 1px solid $gBC;
                border-bottom: 1px solid $gBC;
              }
            }
          }
        }
      }
      .right-body {
        position: relative;
        .right-body-col {
          position: relative;
          width: 100%;
          display: flex;
          .right-body-col-item {
            min-width: 240px;
            flex: 1;

            position: relative;
            overflow: hidden;
            .right-body-col-item-div {
              position: relative;
              height: 30px;
              line-height: 30px;
              width: 50%;
              padding: 0 10px;
              border-right: 1px solid $gBC;
              border-bottom: 1px solid $gBC;
            }
          }
        }
      }
    }
  }
  .good_name_img {
    position: relative;
    width: 156px;
    img {
      position: relative;
      width: 30px;
      height: 30px;
      display: inline-block;
      border-top: 1px solid #dfe6ec;
      border-right: 1px solid #dfe6ec;
      border-bottom: 1px solid #dfe6ec;
      &:hover {
        cursor: pointer;
      }
      &:first-child {
        border-left: 1px solid #dfe6ec;
      }
    }
  }
}
</style>
   