<template>
  <div class="page">
    <topBar v-if="topList.length > 0" :top-list="topList" :moren="moren" />
    <div class="main">
      <div class="tit">{{ $t("商品配置") }}</div>
      <div class="xian"></div>
      <div class="table">
        <!-- 批量操作 -->
        <table>
          <tr>
            <!-- <th colspan="1" class="tableLeft">
              <el-button
                type="primary"
                :disabled="lookOver"
                @click="addNewGoods"
                size="mini"
                >{{ '添加' }}
              </el-button>
            </th> -->
            <th colspan="6" style="padding-bottom: 0; border: 0">
              <div class="tableFlex">
                <div class="tableFlex_i">
                  <!-- <el-input
                    :placeholder="$t('商品')"
                    size="medium"
                    v-model="plcz.pkWares"
                    :disabled="lookOver"
                  ></el-input> -->
                </div>
                <div class="tableFlex_i">
                  <!-- <el-input
                    :placeholder="$t('分配总EV')"
                    size="medium"
                    v-model="plcz.orderAssAchieve"
                    :disabled="lookOver"
                  ></el-input> -->
                </div>
                <div class="tableFlex_i">
                  <!-- <el-input
                    :placeholder="$t('分配代数')"
                    size="medium"
                    v-model="plcz.totalAlgebra"
                    :disabled="lookOver"
                  ></el-input> -->
                </div>
              </div>
            </th>
            <th colspan="4" class="tableLeft" style="padding-bottom: 0">
              <div class="tableFlex">
                <div class="tableFlex_i">
                  <el-input
                    :placeholder="$t('分配EV')"
                    size="medium"
                    v-model="plcz.assAchieve"
                    :disabled="lookOver"
                  ></el-input>
                </div>
                <div class="tableFlex_i">
                  <el-input
                    :placeholder="$t('代数')"
                    size="medium"
                    v-model="plcz.algebra"
                    :disabled="lookOver"
                  ></el-input>
                </div>
                <div class="tableAdd"></div>
              </div>
            </th>
            <th colspan="2" style="padding-bottom: 0">
              <div class="tableFlex">
                <div class="tableFlex_i">
                  <el-button
                    type="primary"
                    :disabled="lookOver"
                    @click="toPlcz"
                    size="mini"
                    >{{ '批量操作' }}</el-button
                  >
                </div>
                <div class="tableFlex_i">
                  <el-button size="mini" :disabled="lookOver" @click="reset">
                    {{ '重置' }}</el-button
                  >
                </div>
              </div>
            </th>
          </tr>
        </table>
        <table class="table_b">
          <tr style="border-top: 0">
            <!-- <td colspan="2" style="border: 0"></td> -->
            <td colspan="12" style="padding-bottom: 0">
              <div class="tableFlex">
                <div class="tableFlex_i">{{ $t("商品") }}</div>
                <div class="tableFlex_i">{{ $t("分配总EV") }}</div>
                <div class="tableFlex_i">{{ $t("分配代数") }}</div>
              </div>
            </td>
            <td colspan="8" style="padding-bottom: 0">
              <div class="tableFlex">
                <div class="tableFlex_i">{{ $t("分配EV") }}</div>
                <div class="tableFlex_i">{{ $t("代数") }}</div>
                <div class="tableAdd"></div>
              </div>
            </td>
            <td colspan="4" style="border: 0"></td>
          </tr>
          <tr v-for="(item, index) in recommendUpgradeList" :key="index">
            <!-- <td colspan="2" style="border: 0"></td> -->
            <td colspan="12" style="padding-bottom: 0">
              <div class="tableFlex">
                <div class="tableFlex_i">
                  <el-input
                    :placeholder="$t('商品')"
                    v-model="item.waresName"
                    :disabled="lookOver"
                    @focus="getProduct(index, cndex)"
                  ></el-input>
                </div>
                <div class="tableFlex_i">
                  <el-input
                    :placeholder="$t('分配总EV')"
                    size="medium"
                    v-model="item.orderAssAchieve"
                    :disabled="true"
                  ></el-input>
                </div>
                <div class="tableFlex_i">
                  <el-input
                    :placeholder="$t('分配代数')"
                    size="medium"
                    v-model="item.totalAlgebra"
                    :disabled="lookOver"
                  ></el-input>
                </div>
              </div>
            </td>
            <td colspan="8" style="padding-bottom: 0">
              <div
                class="tableFlex"
                v-for="(ctem, cndex) in item.waresBonusItemsParamList"
                :key="cndex"
              >
                <div class="tableFlex_i">
                  <el-input
                    :placeholder="$t('分配EV')"
                    v-model="ctem.assAchieve"
                    type="number"
                    :step="0.01"
                    @input="updateEVSum(item)"
                  ></el-input>
                </div>
                <div class="tableFlex_i">
                  <el-input
                    :placeholder="$t('代数')"
                    v-model="ctem.algebra"
                  ></el-input>
                </div>
                <div class="tableAdd">
                  <img
                    src="@/assets/images/iconpop.png"
                    @click="reduceProduct(index, cndex)"
                    alt=""
                  />
                  <img
                    v-if="cndex == item.waresBonusItemsParamList.length - 1"
                    src="@/assets/images/iconadd.png"
                    @click="addProduct(index, cndex)"
                    alt=""
                  />
                </div>
              </div>
              <div
                class="tableAddPro"
                v-show="item.waresBonusItemsParamList.length == 0"
              >
                {{ $t("添加") }}
                <img
                  src="@/assets/images/iconadd.png"
                  @click="addProduct(index, cndex)"
                  alt=""
                />
              </div>
            </td>
            <td colspan="4" style="border: 0"></td>
          </tr>
          <!-- <tr v-if="recommendUpgradeList.length > 0">
            <td colspan="2"></td>
            <td colspan="20">
              <div class="tableAdd" style="margin: 0 auto">
                <img
                  style="cursor: pointer"
                  src="@/assets/images/iconpop.png"
                  @click="reduceNewGoods()"
                  alt=""
                />
              </div>
            </td>
          </tr> -->
        </table>
      </div>
      <el-dialog
        :title="'添加'"
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        width="50%"
        center
        :before-close="handleClose"
      >
        <div class="cpHeight">
          <!-- <el-row>
            <el-col :span="22">
              <el-input
                v-model="select.queryInfo"
                clearable
                :placeholder="'请输入'"
                @keyup.enter.native="getDataList"
                prefix-icon="el-icon-search"
              ></el-input>
            </el-col>
            <el-col :span="2">
              <el-button type="primary" size="small" @click="getDataList">
                {{ '搜索' }}</el-button
              >
            </el-col>
          </el-row>
          <div style="height: 10px"></div> -->
          <el-table
            :data="dialogList"
            ref="multipleTable"
            style="width: 100%"
            @select-all="onSelectAll"
            @select="selected"
            :header-cell-style="{ background: '#EEEEEE' }"
            :row-class-name="tableRowClassName"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column
              align="center"
              prop="waresName"
              :label="$t('商品名称')"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="waresCode"
              :label="$t('商品编号')"
            >
            </el-table-column>
            <!-- <el-table-column
              align="center"
              prop="productName"
              :label="'规格'"
            >
              <template slot-scope="scope">
                <div
                  class="blueCor"
                  v-show="
                    scope.row.selSkuNameList == '' ||
                    scope.row.selSkuNameList == undefined
                  "
                  @click="selSku(scope.row.pkId, scope.$index)"
                >
                  {{ '选择规格' }}
                </div>
                <div
                  class="blueCor"
                  v-show="
                    scope.row.selSkuNameList != '' &&
                    scope.row.selSkuNameList != undefined
                  "
                  @click="selSku(scope.row.pkId, scope.$index)"
                >
                  {{ scope.row.selSkuNameList }}
                </div>
              </template>
            </el-table-column> -->
            <!-- <el-table-column
              align="center"
              prop="productName"
              :label="'商品数量'"
            >
              <template slot-scope="scope">
                <el-input-number
                  size="mini"
                  v-model="scope.row.quantity"
                  :min="1"
                ></el-input-number>
              </template>
            </el-table-column> -->
          </el-table>
        </div>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getDataList"
        />
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">{{ '取消' }}</el-button>
          <el-button type="primary" @click="sureProduct">{{
            '确认'
          }}</el-button>
        </span>
      </el-dialog>
      <el-dialog
        :title="'规格'"
        :visible.sync="ggVisible"
        :close-on-click-modal="false"
        width="40%"
        center
        :before-close="handleCloseGg"
      >
        <div>
          <el-form>
            <el-form-item
              :label="item.typeName"
              v-for="(item, index) in skuList"
              :key="index"
            >
              <el-radio-group v-model="item.pkProductSku">
                <el-radio
                  v-for="(ctem, cndex) in item.specsList"
                  @change="getCheckBox(item.pkId, item.specsName)"
                  :key="ctem.pkId"
                  :label="ctem.pkId"
                  >{{ ctem.specsName }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleCloseGg">{{ '取消' }}</el-button>
          <el-button type="primary" @click="sureSku">{{
            '确认'
          }}</el-button>
        </span>
      </el-dialog>
    </div>
    <div class="footer">
      <el-button size="small" @click="goback()" class="cancelBtn">
        {{ '取消' }}</el-button
      >
      <el-button size="small" @click="submit()" class="sureBtn">
        {{ '确认' }}</el-button
      >
    </div>
  </div>
</template>

<script>
import * as api from "@/api/specialBusiness.js";
import topBar from "@/components/topBar";
import ImageUpload from "@/components/ImageUpload";
import { Message } from "element-ui";
export default {
  name: "WaresBonusRules",
  components: {
    ImageUpload,
    topBar,
  },
  props: {
    lookOver: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      dialogVisible: false,
      ggVisible: false,
      queryParams: {
        pageNum: 1,
        pageSize: 50,
      },
      total: 0,
      allData: [], //全部数据
      areaList: [], //全部专区
      isArea: "",
      plcz: {},
      select: {}, //产品筛选
      dialogList: [], //产品数组
      selectData: [], //选中
      skuList: [], //规格数组
      gradeList: [], //规格数组
      selSkuList: "",
      selSkuNameList: "",
      selIndex: "",
      showCndex: "",
      showIndex: "",
      pageData: {},
      recommendUpgradeList: [],
      allGoods: [],
      moren: "WaresBonusRules",
      topList: [
        {
          name: "特殊品奖金分配",
          path: "WaresBonusRules",
        },
      ],
      isEdit: "",
    };
  },
  // computed: {
  //   calculateTotalEV() {
  //     return this.recommendUpgradeList.map((item) => {
  //       return item.waresBonusItemsParamList.reduce((sum, ctem) => {
  //         return sum + parseFloat(ctem.assAchieve || 0);
  //       }, 0);
  //     });
  //   },
  // },
  watch: {
    recommendUpgradeList: {
      deep: true,
      handler() {
        this.recommendUpgradeList.forEach((item) => {
          this.updateEVSum(item);
        });
      },
    },
  },

  mounted() {
    // this.getData();
    this.addNewGoods();
    if (this.$route.query.isEdit) {
      this.isEdit = this.$route.query.isEdit;
    }
    if (this.$route.query.allData) {
      const allData = JSON.parse(this.$route.query.allData);
      this.recommendUpgradeList = [allData];
      this.recommendUpgradeList.forEach((item) => {
        if (item.bdWaresBonusItemsList) {
          this.$set(
            item,
            "waresBonusItemsParamList",
            JSON.parse(JSON.stringify(item.bdWaresBonusItemsList))
          );
        }
      });
    }
  },
  methods: {
    goback() {
      this.$router.go(-1);
    },
    updateEVSum(item) {
      const currentTotal = item.waresBonusItemsParamList.reduce(
        (sum, ctem) => sum + Number(ctem.assAchieve || 0),
        0
      );
      item.orderAssAchieve = currentTotal;
    },
    getPage(allData) {
      this.recommendUpgradeList = allData;
      console.log("🌈allData", allData);
    },
    sureSku() {
      this.$set(this.dialogList[this.selIndex], "selSkuList", this.selSkuList);
      this.$set(
        this.dialogList[this.selIndex],
        "selSkuNameList",
        this.selSkuNameList
      );
      this.ggVisible = false;
    },
    sureProduct() {
      console.log(this.selectData, "waresName");
      if (this.selectData.length == 0) {
        this.$message({
          message: '请选择产品',
          type: "warning",
        });
        return false;
      } else {
        this.recommendUpgradeList[this.showIndex].pkWares =
          this.selectData.pkId;

        this.recommendUpgradeList[this.showIndex].waresName =
          this.selectData.waresName;
        this.recommendUpgradeList[this.showIndex].waresCode =
          this.selectData.waresCode;
        this.handleClose();
        this.$forceUpdate();
      }
    },
    toPlcz() {
      this.recommendUpgradeList.forEach((stem) => {
        stem.waresBonusItemsParamList.forEach((ctem) => {
          ctem.assAchieve = this.plcz.assAchieve;
          ctem.algebra = this.plcz.algebra;
        });
      });
    },
    reset() {
      this.plcz = {};
    },
    getCheckBox() {
      let arr1 = [],
        arr2 = [];
      this.skuList.forEach((item) => {
        item.specsList.forEach((ctem) => {
          if (ctem.pkId == item.pkProductSku) {
            arr1.push(ctem.pkId);
            arr2.push(ctem.specsName);
          }
        });
      });
      this.selSkuList = arr1.join(",");
      this.selSkuNameList = arr2.join(",");
    },
    setArea(val) {
      this.isArea = val;
    },
    handleClose() {
      this.selectData = [];
      this.dialogVisible = false;
    },
    handleCloseGg() {
      this.ggVisible = false;
    },
    getProduct(index, cndex) {
      this.showIndex = index;
      this.showCndex = cndex;
      this.getDataList();
      this.dialogVisible = true;
    },
    addProduct(index, sndex) {
      if (!this.lookOver) {
        this.recommendUpgradeList[index].waresBonusItemsParamList.push({
          assAchieve: "",
          algebra: "",
        });
      }
    },
    reduceProduct(index, cndex) {
      if (!this.lookOver) {
        this.recommendUpgradeList[index].waresBonusItemsParamList.splice(
          cndex,
          1
        );
      }
    },
    reduceNewGoods() {
      this.recommendUpgradeList.splice(this.recommendUpgradeList.length - 1, 1);
    },
    addNewGoods() {
      this.recommendUpgradeList.push({
        orderAssAchieve: "",
        totalAlgebra: "",
        pkWares: "",
        waresBonusItemsParamList: [
          {
            assAchieve: "",
            algebra: "",
          },
        ],
      });
    },
    selSku(pkId, index) {
      this.selIndex = index;
      api
        .getProductSpecs({
          pkProduct: pkId,
        })
        .then((res) => {
          let arr1 = [],
            arr2 = [];
          res.data.forEach((item) => {
            item.pkProductSku = item.specsList[0].pkId;
            arr1.push(item.specsList[0].pkId);
            arr2.push(item.specsList[0].specsName);
          });
          this.selSkuList = arr1.join(",");
          this.selSkuNameList = arr2.join(",");

          this.skuList = res.data;
          this.ggVisible = true;
        });
    },
    getDataList() {
      api
        .waresBonusEvQuery(Object.assign(this.queryParams, this.select))
        .then((res) => {
          res.rows.forEach((item) => {
            item.quantity = 1;
          });
          this.dialogList = res.rows;
          this.total = res.total;
        });
    },
    submit() {
      // let obj = Object.assign({}, this.pageData, {
      //   waresConfigParam: this.allData,
      // });
      let obj = this.recommendUpgradeList[0];
      console.log(
        "%c [ obj ]-445",
        "font-size:13px; background:#6f1b1a; color:#b35f5e;",
        obj
      );
      if (this.isEdit == 1) {
        api.waresBonusUdate(obj).then((res) => {
          if (res.code == 200) {
            Message({
              message: res.msg,
              type: "success",
            });
            this.$router.push({
              path: "waresBonus",
            });
          }
        });
      } else {
        api.waresBonusInsert(obj).then((res) => {
          if (res.code == 200) {
            Message({
              message: res.msg,
              type: "success",
            });
            this.$router.push({
              path: "waresBonus",
            });
          }
        });
      }
    },
    onSelectAll() {
      this.$refs.multipleTable.clearSelection();
    },
    selected(selection, row) {
      // 清除 所有勾选项
      this.$refs.multipleTable.clearSelection();
      // 当表格数据都没有被勾选的时候 就返回
      // 主要用于将当前勾选的表格状态清除
      if (selection.length == 0) return;
      this.$refs.multipleTable.toggleRowSelection(row, true);
      this.selectData = row;
    },
    // 表格的选中 可以获得当前选中的数据
    selectionChange(val) {
      // 将选中的数据存储起来
      this.selectData = val;
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 == 1) {
        return "warning-row";
      } else if (rowIndex % 2 == 0) {
        return "success-row";
      }
      return "";
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  padding: 10px 20px;
  background: #f9f9f9;
  font-size: 14px;
}
.main {
  background: #ffffff;
  border-radius: 8px;
  height: calc(100vh - 164px);
  padding-bottom: 20px;
  box-shadow: 0px 2px 20px 0px rgba(238, 238, 238, 0.5);
}
::v-deep .el-select {
  width: 100%;
}
// }
.footer {
  height: 68px;
  background: #ffffff;
  box-shadow: 0px -3px 20px 0px rgba(204, 204, 204, 0.5);
  // margin: 0 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  .thebtn1 {
    background: #3181e5;
    color: #ffffff;
    padding: 9px 45px;
  }
  .thebtn2 {
    background: #cccccc;
    color: #ffffff;
    padding: 9px 45px;
  }
}
.tit {
  font-size: 14px;
  font-weight: bold;
  color: #333333;
  padding: 0 20px;
  border-left: 5px solid #c8161d;
  margin: 20px 0 10px 0;
}
.xian {
  height: 1px;
  background: rgba(0, 0, 0, 0.1);
}
.demo-ruleForm {
  padding: 20px 0;
}
::v-deep .el-date-editor--datetimerange {
  width: auto !important;
}
.flexed {
  display: flex;
}
.flexed_l {
  margin-right: 20px;
}
.table {
  padding: 0 20px;
  margin-top: 20px;
}

table {
  width: 100%;
  background: #fff;
  border-collapse: collapse;
  border: 1px solid #cccccc;
  border-spacing: 0;
  table-layout: fixed;
  border-collapse: collapse;

  //   合并内外边距
  // (去除表格单元格默认的2个像素内外边距*/
}
.table_b {
  border-top: 0;
}
th {
  padding: 10px 10px;
  text-align: center;
  border: 1px solid #cccccc;
  overflow: hidden;
  border-top: 0;
}
td {
  padding: 10px 10px;
  text-align: center;
  border: 1px solid #cccccc;
  border-top: 0;
  overflow: hidden;
}
.tableFlex {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  .tableFlex_i {
    flex: 1;
    ::v-deep .el-input__inner {
      width: 90%;
    }
    ::v-deep .el-input__suffix {
      right: 15px;
    }
  }
}
.tableAdd {
  width: 50px;
  img {
    width: 19px;
    height: 19px;
  }
}
.tableAddPro {
  display: flex;
  align-items: center;
  justify-content: center;
  img {
    width: 19px;
    height: 19px;
    margin-left: 10px;
  }
}
.tableLeft {
  text-align: left;
}
.tabList {
  display: flex;
  align-items: center;
  padding: 20px 0px 0 20px;
  .tabList_i {
    padding: 10px;
    font-size: 14px;
    font-weight: 400;
    color: #999999;
    cursor: pointer;
  }
  .tabAct {
    background: #108ee9;
    color: #fff;
  }
}
.clearBtm {
  border-bottom: 0;
}
.cpHeight {
  height: 50vh;
  overflow-y: auto;
}
.blueCor {
  color: #589ff8;
  cursor: pointer;
}
::v-deep .el-input__icon {
  line-height: 33px;
}
::v-deep .el-button {
  margin-top: 0;
}
</style>
