<template>
  <div class="detail-container">
    <!-- 添加商品 -->
    <div class="form-container">
      <el-form ref="mainForm" :model="mainForm" :rules="mainFormRules">
        <el-button size="small" type="primary" @click="addGoods"
          >选择商品</el-button
        >
        <el-form-item
          :label="'商品名称:'"
          style="margin: 20px 0 40px 0"
          prop="goodName"
        >
          <el-input
            v-model="mainForm.categoryName"
            style="width: 40%"
            disabled
          ></el-input>
        </el-form-item>

        <div class="diy-table">
          <div class="table-head clearfix">
            <div class="right">
              <div class="item name">规格</div>
              <div class="item input">划线价格</div>
              <div class="item input">销售价</div>
              <div class="item input">分销金额</div>
              <div class="item input">佣金比例</div>
              <div class="item input">内部分销金额</div>
              <div class="item input">内部佣金比例</div>
              <div class="item input">库存</div>
              <div class="item input">销量</div>
            </div>
          </div>
          <div
            class="goods-item"
            v-for="(item, index) in goodsList"
            :key="index"
          >
            <div class="spec-list">
              <div
                class="spec-item"
                v-for="(it, idx) in item.goodsSpecs"
                :key="idx"
              >
                <div class="col name">{{ it.name }}</div>
                <div class="col input">
                  <el-input
                    type="number"
                    size="small"
                    v-model="it.orgPrice"
                    disabled
                  ></el-input>
                </div>
                <div class="col input">
                  <el-input
                    type="number"
                    size="small"
                    v-model="it.price"
                    disabled
                  ></el-input>
                </div>
                <div class="col input">
                  <el-input
                    type="number"
                    size="small"
                    v-model="it.shareAmount"
                    disabled
                  ></el-input>
                </div>
                <div class="col input">
                  <el-input
                    type="number"
                    size="small"
                    v-model="it.innerSharePercent"
                    disabled
                  ></el-input>
                </div>
                <div class="col input">
                  <el-input
                    type="number"
                    size="small"
                    v-model="it.innerShareAmount"
                    disabled
                  ></el-input>
                </div>
                <div class="col input">
                  <el-input
                    type="number"
                    size="small"
                    v-model="it.innerSharePercent"
                    disabled
                  ></el-input>
                </div>
                <div class="col input">
                  <el-input
                    type="number"
                    size="small"
                    v-model="it.stockNum"
                    disabled
                  ></el-input>
                </div>
                <div class="col input">
                  <el-input
                    type="number"
                    size="small"
                    v-model="it.soldNum"
                    disabled
                  ></el-input>
                </div>
              </div>
            </div>

            <div class="empty-text" v-if="goodsList.length < 1">暂无数据</div>
          </div>
        </div>

        <!-- <el-form-item
          label="商品状态"
          prop="goodsStatus"
          style="margin-top: 30px"
        >
          <el-radio-group v-model="mainForm.goodsStatus">
            <el-radio label="true">上架</el-radio>
            <el-radio label="false">下架</el-radio>
          </el-radio-group>
        </el-form-item> -->

        <div
          style="
            font-size: 14px;
            margin: 30px 0 20px 0;
            color: #606266;
            font-weight: 700;
          "
        >
          活动专区商品标签:
        </div>
        <el-form-item prop="LabelSetting">
          <el-card shadow="never">
            <el-tag
              v-for="(item, index) in TagsList"
              :key="index"
              @click="selectTag(item, index)"
              style="margin-right: 30px"
            >
              {{ item.name }}<i class="el-icon-check" v-if="item.checked"></i>
            </el-tag>
          </el-card>
        </el-form-item>
      </el-form>
    </div>

    <!-- 选择商品 -->
    <el-dialog
      title="选择商品"
      :visible.sync="addGoodsVisible"
      :show-close="false"
      width="50%"
      :close-on-click-modal="false"
    >
      <div class="dialog-container clearfix">
        <div class="left fl">
          <div class="item" @click="changeClassify('')">全部分类</div>
          <div class="group" v-for="(item, index) in classifyList" :key="index">
            <div class="item" @click="toggleOpen(index)">
              <i
                :class="
                  item.isOpen ? 'el-icon-caret-bottom' : 'el-icon-caret-right'
                "
              ></i>
              {{ item.name }}
            </div>
            <div class="child" v-if="item.isOpen">
              <div
                class="item"
                v-for="(childItem, childIndex) in item.children"
                :key="childIndex"
                @click="changeClassify(childItem.categoryId)"
              >
                {{ childItem.name }}
              </div>
            </div>
          </div>
        </div>

        <div class="right fl">
          <div class="search">
            <el-input
              placeholder="请输入商品名称进行搜索"
              v-model="keyword"
              class="input-with-select"
              clearable
              size="small"
              style="width: 250px"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                size="small"
                @click="getGoodsListByScreen"
              ></el-button>
            </el-input>
          </div>
          <div class="table" style="margin: 10px 0 20px">
            <el-table
              v-loading="table_listLoading"
              :data="table_dataList"
              element-loading-text="Loading"
              tooltip-effect="dark"
              style="width: 100%"
              max-height="270"
              @selection-change="handleChooseGoods"
            >
              <el-table-column
                align="center"
                type="selection"
                :selectable="checkboxSelect"
                width="45"
              ></el-table-column>
              <el-table-column
                align="center"
                prop="goodsName"
                label="商品名称"
                min-width="200"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                align="center"
                prop="goodsPrice"
                label="价格"
                width="80"
              ></el-table-column>
              <el-table-column
                align="center"
                prop="stockNum"
                label="库存"
                width="80"
              ></el-table-column>
            </el-table>
          </div>
          <div class="pagination clearfix">
            <div class="fr">
              <el-pagination
                @current-change="handleTableCurrentChange"
                :current-page="table_currentPage"
                :page-size="table_pageSize"
                background
                layout="prev, pager, next"
                :total="table_listTotal"
              >
              </el-pagination>
            </div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddGoods">保 存</el-button>
        <el-button @click="cancelAddGoods">取 消</el-button>
      </div>
    </el-dialog>

    <div class="page-footer">
      <div class="footer" :class="classObj">
        <el-button
          type="primary"
          @click="submitMainForm"
          :loading="formLoading"
          >{{ formLoading ? "提交中 ..." : "提 交" }}</el-button
        >
        <el-button @click="goBack">关 闭</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import AddGoods from "@/components/Mall/add-goods";
import { getGoodsList, getClassifyList } from "@/api/special";
export default {
  props: ["allTags"],
  components: { AddGoods },
  data() {
    return {
      tags: [],
      tag: "",
      goodsTagList: [],
      goodsTagsList: [
        {
          tag: "",
          goodsId: "",
        },
      ],
      goodsNameList: [], // 总商品名
      categoryName: "", // 商品类别名称
      baseURL: process.env.VUE_APP_BASE_API,
      myHeaders: { "x-token": getToken() },
      formLoading: false,
      TagsList: [],
      mainForm: {
        // goodName:"", // 商品名称
        categoryName: "", // 商品名称
        // goodsStatus: "true", // 商品状态
        LabelSetting: "", // 商品标签
        goodsList: [], // 总商品
      },
      goodsStatus: 1,
      mainFormRules: {
        // goodsStatus: [
        //   {
        //     required: true,
        //     message: "请选择商品状态",
        //     trigger: "blur",
        //   },
        // ],
        LabelSetting: [
          {
            required: true,
            message: "请添加活动专区商品标签设置",
            trigger: "blur",
          },
        ],
      },
      goodsList: [], // 列表数据
      addGoodsVisible: false, // 选择商品弹窗
      classifyList: [],
      keyword: "",
      table_dataList: null, // 列表数据
      table_listLoading: false, // 列表加载loading
      table_currentPage: 1, // 当前页码
      table_pageSize: 10, // 每页数量
      table_listTotal: 0, // 列表总数
      table_chooseGoods: [], // table中 当前选择商品
    };
  },
  computed: {
    sidebar() {
      return this.$store.state.app.sidebar;
    },
    classObj() {
      return {
        hideSidebar: !this.sidebar.opened,
        openSidebar: this.sidebar.opened,
      };
    },
  },
  created() {
    let list = [];
    this.allTags.forEach((item) => {
      list.push({
        name: item,
        checked: false,
      });
    });
    console.log("全部标签2", list);
    this.TagsList = list;
  },
  updated() {
    // this.table_chooseGoods.forEach((item) => {
    //   item.status = JSON.parse(this.mainForm.goodsStatus);
    // });
    console.log("选择的商品,更改是否上架状态", this.table_chooseGoods);
    const ids = this.table_chooseGoods.map((item) => {
      return item.goodsId;
    });
    console.log("所选商品的id列表", ids);

    let goodsTagsList = [];
    ids.forEach((item) => {
      goodsTagsList.push({
        goodsId: item,
        tag: this.tag,
      });
    });
    console.log(goodsTagsList);
    this.goodsTagsList = goodsTagsList;
  },
  methods: {
    // 返回
    goBack() {
      this.$emit("backSpecialSet", "false");
    },
    // 提交
    submitMainForm() {
      this.mainForm.goodsTagsList = this.goodsTagsList;
      this.$emit("addGoods", this.mainForm);
      this.$emit("addGoods1", this.mainForm);
    },
    // 选择商品
    addGoods() {
      this.addGoodsVisible = true;
      this.getClassifyList();
    },
    // 取消 选择商品
    cancelAddGoods() {
      this.addGoodsVisible = false;
    },

    // 提交 选择商品
    submitAddGoods() {
      if (this.table_chooseGoods.length !== 1) {
        return this.$errorMsg("请选择一个商品");
      }
      let oldgoodsList = this.goodsList;
      let newgoodsList = this.table_chooseGoods;
      this.goodsList = oldgoodsList.concat(newgoodsList);
      this.mainForm.goodsList = this.goodsList;
      this.goodsNameList = this.goodsList.map((item) => {
        return item.categoryName;
      });
      // this.table_chooseGoods.forEach((item) => {
      //   item.status = JSON.parse(this.mainForm.goodsStatus);
      // });
      const str = this.goodsNameList.join(",");
      this.addGoodsVisible = false;
      this.mainForm.categoryName = str;
    },
    // 搜索
    getGoodsListByScreen() {
      if (this.table_chooseGoods.length > 0) {
        return this.$errorMsg("当前已选择商品，不可搜索");
      }
      this.table_currentPage = 1;
      this.getGoodsList();
    },
    // table点击选择商品
    handleChooseGoods(val) {
      this.table_chooseGoods = val;
    },
    // 查询重复值并禁选
    checkboxSelect(row, rowIndex) {
      if (row.selected) {
        return false; // 禁用
      } else {
        return true; // 不禁用
      }
    },
    // 更改列表当前页
    handleTableCurrentChange(val) {
      if (this.table_chooseGoods.length > 0) {
        return this.$errorMsg("当前已选择商品，不可切换分页");
      }
      this.table_currentPage = val;
      this.getGoodsList();
    },
    // 搜索
    getGoodsListByScreen() {
      if (this.table_chooseGoods.length > 0) {
        return this.$errorMsg("当前已选择商品，不可搜索");
      }
      this.table_currentPage = 1;
      this.getGoodsList();
    },
    // 选择标签
    selectTag(item, index) {
      this.TagsList[index].checked = !item.checked;
      this.$set(this.TagsList, index, item);
      this.TagsList.forEach((item) => {
        if (item.checked) {
          this.tags.push(item.name);
        } else {
          this.tags.splice(index, 1);
        }
      });
      this.tags = [...new Set(this.tags)];
      const tag = this.tags.join(",");
      this.tag = tag;
    },

    // 获取分类列表
    getClassifyList() {
      getClassifyList({ categoryLevel: 1, status: true }).then((res) => {
        res.data.forEach((item) => {
          item.isOpen = false;
        });
        this.classifyList = res.data;
        this.classifyCurrent = "";
        this.getGoodsList();
      });
    },

    // 展开/收起 分类
    toggleOpen(index) {
      this.classifyList[index].isOpen = !this.classifyList[index].isOpen;
    },

    // 切换分类
    changeClassify(cid) {
      if (this.table_chooseGoods.length > 0) {
        return this.$errorMsg("当前已选择商品，不可切换分类");
      }
      this.classifyCurrent = cid;
      this.table_currentPage = 1;
      this.getGoodsList();
    },

    // 获取商品列表
    getGoodsList() {
      getGoodsList({
        pageNum: this.table_currentPage,
        pageSize: this.table_pageSize,
        keyword: this.keyword,
        categoryId: this.classifyCurrent,
      }).then((res) => {
        let oldgoodsList = this.goodsList;
        let newgoodsList = res.data.records;
        for (let i = 0; i < oldgoodsList.length; i++) {
          let oldItem = oldgoodsList[i];
          for (let j = 0; j < newgoodsList.length; j++) {
            let newItem = newgoodsList[j];
            if (newItem.goodsId === oldItem.goodsId) {
              newgoodsList[j].selected = true;
              break;
            }
          }
        }
        // for (let j = 0; j < newgoodsList.length; j++) {
        //   let newItem = newgoodsList[j];
        //   if (newItem.promotionGroup === true) {
        //     newgoodsList[j].selected = true;
        //   }
        // }
        this.table_dataList = newgoodsList;
        this.table_listTotal = res.data.total;
        this.table_listLoading = false;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.form-container {
  margin-top: 40px;
  // padding: 0 6%;
  .title {
    font-size: 16px;
    margin-bottom: 30px;
    padding-left: 10px;
    font-weight: bold;
  }
  .tips {
    margin-top: 10px;
    span {
      display: inline-block;
      width: 300px;
      text-align: center;
      line-height: 32px;
      background: #ffefef;
      font-size: 14px;
      color: #f66460;
    }
  }
  .tips2 {
    font-size: 12px;
    color: #999999;
    line-height: 30px;
  }
  .container {
    padding: 10px 20px 0;
    background: #f5f5f5;
    border-radius: 10px;
  }
  .addBtn {
    padding: 10px 0;
  }
}

.diy-table {
  overflow-x: scroll;
  border-left: 1px solid #f5f5f5;
  margin-top: 20px;
  width: 100%;
  // margin-left: 77px;
  // min-width: 1185px;
  max-width: 100%;
  .table-head {
    display: flex;
    .item {
      height: 40px;
      line-height: 40px;
      float: left;
      font-weight: 500;
      font-size: 14px;
      background: #f5f5f5;
      text-align: center;
    }
    .right {
      float: left;
      width: 80%;
      min-width: 1000px;
      flex-shrink: 0;
      height: 40px;
    }
    .goods {
      width: 20%;
      min-width: 250px;
    }
    .name {
      width: 12%;
      min-width: 100px;
    }
    .input {
      width: 11%;
      min-width: 100px;
    }
    .opera {
      width: 10%;
      min-width: 80px;
      // text-align: right;
    }
    .blank {
      background: #f5f5f5;
      width: 6%;
      min-width: 90px;
    }
  }
  .goods-item {
    display: flex;
    align-content: center;
    .goods-info {
      flex-shrink: 0;
      width: 20%;
      min-width: 250px;
      padding: 0 10px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #f5f5f5;
      border-right: 1px solid #f5f5f5;
      font-size: 14px;
      &:last-child {
        border-bottom: none;
      }
      img {
        width: 40px;
        height: 40px;
        margin-right: 10px;
        flex-shrink: 0;
      }
    }
    .spec-list {
      width: 80%;
      min-width: 1000px;
      border-bottom: 1px solid #f5f5f5;
      border-right: 1px solid #f5f5f5;
      &:last-child {
        border-bottom: none;
      }
      .spec-item {
        display: flex;
        align-items: center;
        border-bottom: 1px solid #f5f5f5;
        &:last-child {
          border-bottom: none;
        }
        .col {
          flex-shrink: 0;
          height: 50px;
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 0 10px;
          border-right: 1px solid #f5f5f5;
          &:last-child {
            border-right: none;
          }
        }
        .name {
          width: 12%;
          min-width: 100px;
          font-size: 14px;
          text-align: center;
        }
        .input {
          width: 11%;
          min-width: 100px;
        }
        .btn {
          width: 11%;
          min-width: 80px;
        }
      }
    }
    .operation {
      flex-shrink: 0;
      width: 6%;
      min-width: 90px;
      padding: 0 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-bottom: 1px solid #f5f5f5;
      border-right: 1px solid #f5f5f5;
    }
  }
  .empty-text {
    line-height: 60px;
    text-align: center;
    color: #909399;
  }
}

.dialog-container {
  .left {
    width: 140px;
    height: 350px;
    overflow-y: scroll;
    .group {
      margin-top: 10px;
    }
    .child {
      margin-top: 5px;
      .item {
        padding-left: 18px;
      }
    }
    .item {
      cursor: pointer;
      line-height: 24px;
    }
  }
  .right {
    width: calc(100% - 140px);
    height: 350px;
    box-sizing: border-box;
    padding-left: 20px;
  }
}

::v-deep .el-form-item__label {
  margin-left: 0px !important;
}
</style>
