<template>
  <div class="activeAdd">
    <el-table :data="good_list" stripe border :size="'mini'" style="width: 100%">
      <el-table-column
        prop="yz_good_code"
        label="商品上线编码"
        show-overflow-tooltip
        width="170"
      />
      <el-table-column
        prop="plat_code"
        label="平台商品编码"
        show-overflow-tooltip
        width="170"
      />

      <el-table-column prop="good_name" label="商品名称" show-overflow-tooltip />
      <el-table-column prop="stock_num" label="活动库存" width="180">
        <template slot-scope="scope">
          <el-input-number
            v-show="type !== 'view'"
            style="width: 100%"
            v-model="scope.row.stock_num"
            :min="1"
            :max="100000000000"
            :precision="0"
            :size="'mini'"
            label="活动库存"
          ></el-input-number>
          <span v-show="type === 'view'">{{ scope.row.stock_num }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="origin_price"
        label="划线价"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column
        prop="final_price"
        label="销售价"
        width="100"
        show-overflow-tooltip
      />

      <el-table-column fixed="right" width="80">
        <template slot="header" slot-scope="scope">
          <span>操作</span>
          <el-tooltip
            class="item"
            effect="dark"
            v-if="status === ''"
            content="添加活动商品"
            placement="top"
          >
            <i
              class="el-icon-circle-plus-outline fr"
              style="font-size: 18px; margin-top: 2px"
              @click="showModel = true"
            />
          </el-tooltip>
        </template>
        <template slot-scope="scope">
          <el-tooltip effect="dark" content="删除" placement="top">
            <i
              class="el-icon-delete tb-icon"
              @click="deleteRow(scope.$index, good_list)"
            ></i>
          </el-tooltip>
          <el-tooltip effect="dark" content="查看商品信息" placement="top">
            <i
              class="el-icon-view tb-icon"
              @click="showGoodModelFun(scope.row.yz_good_code)"
            ></i>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <search-youzan-txx-good-online-modal
      :once="once"
      :sitem="ruleForm"
      :active="true"
      :platform_code="36"
      :show-model="showModel"
      @resultList="resultList"
      @cancel="showModel = false"
    />
    <show-good-data-modal
      :show-model="showGoodModel"
      :skuCode="showGoodId"
      :spuCode="''"
      @cancel="showGoodModel = false"
    />
    <!-- <add-stock
      :show-model="addStockModel"
      :sitem="addStockSitem"
      @refresh="$emit('refresh', true)"
      @cancel="addStockModel = false"
    /> -->
    <el-col
      :span="24"
      v-if="status === ''"
      style="text-align: right; padding: 15px 0 15px 0; border-top: 1px solid #dcdfe6"
    >
      <el-button :size="'mini'" type="primary" @click="submitForm">保 存 </el-button>
    </el-col>
  </div>
</template>
<script>
import asyncRequest from "@/apis/service/youzan/luckDraw";
import resToken from "@/mixins/resToken";
import { mapGetters } from "vuex";
import searchYouzanTxxGoodOnlineModal from "@/components/search-youzan-txx-good-online-modal";
import showGoodDataModal from "@/components/show-good-data-modal";
// import addStock from "./addStock";

export default {
  name: "activeAdd",
  mixins: [resToken],
  props: ["showModel", "id", "type", "sitem", "newTime"],
  components: {
    searchYouzanTxxGoodOnlineModal,
    showGoodDataModal,
    // addStock,
  },
  watch: {
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size", "business_companyNo"]),
    // powers() {
    //   const tran =
    //     this.$store.getters.btnList.find((i) => i.menu_route == "activeDetail") || {};
    //   const { action } = tran ?? {};
    //   return action ?? [];
    // },
  },
  data() {
    return {
      size: "small",
      activeName: "3",
      status: "",

      loading: false,
      // showModel: false,
      once: false,
      rulesThis: this.rules,
      showGoodModel: false,
      showGoodId: "",
      addStockModel: false,
      addStockSitem: null,
      ruleForm: {},
      // 表格 - 数据
      tableData: [],
      good_list: [],
    };
  },
  mounted() {
    this.initForm();
  },
  methods: {
    async initForm() {
      this.loading = true;
      this.tableData = [];
      this.good_list = [];
      await this.initData();
      this.loading = false;
    },

    //添加活动库存弹窗
    addStock(index) {
      this.addStockSitem = this.good_list[index];
      this.addStockModel = true;
    },
    showGoodModelFun(skuCode) {
      this.showGoodModel = true;
      this.showGoodId = skuCode;
    },
    openCostEditDelete(index) {
      this.good_list.splice(index, 1);
    },
    async deleteRow(index, rows) {
      await this.$confirm("确定要删除？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          rows.splice(index, 1);
        })
        .catch(() => {
          console.log("取消");
        });
    },
    resultList(e) {
      console.log(e);
      this.showModel = false;
      let list = JSON.parse(JSON.stringify(e));
      let oldList = JSON.parse(JSON.stringify(this.good_list));
      list.forEach((e, ei) => {
        let index = oldList.findIndex((a) => e.skuCode === a.skuCode);
        if (index === -1) {
          let item = JSON.parse(JSON.stringify(list[ei]));
          item.stock_num = "1";
          item.newTime = new Date().valueOf();
          item.yz_good_code = item.skuCode;
          console.log(item.stock_num);
          this.good_list.push(item);
        }
      });
    },

    handleClick(row) {
      console.log(row);
    },

    async submitForm() {
      if (!this.loading) {
        this.loading = true;
        if (this.good_list.length === 0) {
          this.$message.warning("请选择活动商品信息！");
          this.loading = false;
          return;
        }

        let res = {};
        if (this.tableData.length === 0) {
          let addModel = {
            actCode: this.id,
            snArr: [],
          };
          this.good_list.forEach((e) => {
            addModel.snArr.push({ skuCode: e.skuCode, stock_num: e.stock_num });
          });
          res = await asyncRequest.goodAdd(addModel);
        } else {
          let goodArr = [];
          console.log(this.tableData);
          console.log(this.good_list);
          this.tableData.forEach((s, si) => {
            let index = this.good_list.findIndex((a) => a.skuCode === s.skuCode);
            if (index === -1) {
              goodArr.push({
                is_del: "1",
                actCode: this.id,
                yz_good_code: s.yz_good_code,
                stock_num: s.stock_num,
              });
            }
          });
          this.good_list.forEach((s, si) => {
            goodArr.push({
              is_del: "0",
              actCode: this.id,
              yz_good_code: s.yz_good_code,
              stock_num: s.stock_num,
            });
          });
          res = await asyncRequest.goodUpdate({ goodArr });
        }
        const { code, data, message } = res;
        this.loading = false;
        if (code === 0) {
          this.$notify.success({
            title: this.type === "add" ? "新建成功！" : "编辑成功！",
            message: "",
          });
          this.showModelThis = false;
          // 刷新
          this.$emit("refresh", true);
        } else if (code >= 100 && code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(message);
        }
      }
    },
    async initData() {
      this.loading = true;
      const { code, data, message } = await asyncRequest.goodList({
        actCode: this.id,
        page: 1,
        size: 99999,
      });
      this.loading = false;
      if (code === 0) {
        const { list, count } = data;
        let arr = list.length > 0 ? JSON.parse(JSON.stringify(list)) : [];
        arr.map((a) => {
          a.skuCode = a.yz_good_code;
          return a;
        });
        console.log(arr);
        this.tableData = arr.length > 0 ? JSON.parse(JSON.stringify(arr)) : [];
        this.good_list = arr.length > 0 ? JSON.parse(JSON.stringify(arr)) : [];
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.tableData = [];
        this.good_list = [];
        this.$message.error(message);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.activeAdd {
  .activeAdd-title {
    border-top: 1px solid #ebeef5;
    span {
      height: 50px;
      line-height: 50px;
      font-family: "微软雅黑", sans-serif;
      font-weight: 400;
      font-style: normal;
      font-size: 16fpx;
      text-align: left;
    }
  }
  /deep/ .ddiv {
    border-top: 1px solid #dcdfe6;
  }
  /deep/ .dtitle {
    width: 40px;
    text-align: center;
    height: 100%;
    min-height: 100%;
    ul {
      padding: 20px 0 0 0;
    }
  }
  /deep/ .dmain {
    padding: 20px 0 0 0;
    width: calc(100% - 40px);
    border-left: 1px solid #dcdfe6;
  }
}
</style>
