<template>
  <ContainerTit>
    <div slot="headr">
      <el-button :loading="sub_load" type="primary" @click="submit">
        提交保存
      </el-button>
    </div>
    <div class="detail-tab-item">
      <div class="detail-tab-title">积分规则</div>
      <div class="detail-tab-main">
        <el-form
          ref="add_form"
          label-position="right"
          :model="add_form"
          :rules="form_rules"
          size="small"
          label-width="100px"
        >
          <el-form-item label="规则说明">
            <el-tooltip effect="light" placement="bottom">
              <div slot="content">
                当客户下单时，同时满足多个积分奖励规则时，
                <br />
                按照商品积分规则>商品分类规则>订单积分规则的顺序执行积分政策
                <br />
                【例如】：客户下单时，既有订单积分奖励，也有商品分类和某个商品的积分奖励，
                <br />
                计算订单中的订单积分时，需要将满足商品分类和商品积分的金额减去，
                <br />
                再算根据剩余的订单金额计算奖励积分，再将商品分类所得积分和商品所得积分累加，
                <br />
                即该笔订单总获得积分。
              </div>
              <i style="color: #6c6c6c" class="el-icon-question"></i>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="规则名称" prop="title">
            <el-input
              v-model="add_form.title"
              style="width: 300px"
              size="small"
              placeholder="规则名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="规则类型">
            <div>
              <el-checkbox v-model="order_checked">按订单奖励积分</el-checkbox>
            </div>
            <div v-if="order_checked">
              <span>单笔订单满</span>
              <el-input-number
                v-model="add_form.startMoney"
                style="margin: 0 10px"
                :min="0"
                :controls="false"
              ></el-input-number>
              <span>元，每消费</span>
              <el-input-number
                v-model="add_form.amount"
                style="margin: 0 10px"
                :min="0"
                :controls="false"
              ></el-input-number>
              <span>元，奖励</span>
              <el-input-number
                v-model="add_form.integral"
                style="margin: 0 10px"
                :min="0"
                :controls="false"
              ></el-input-number>
              <span>积分</span>
            </div>
          </el-form-item>
          <el-form-item label=" ">
            <div>
              <el-checkbox v-model="goods_checked">按商品奖励积分</el-checkbox>
            </div>
            <el-table v-if="goods_checked" :data="goods_list" size="mini">
              <el-table-column
                label="#"
                width="60"
                type="index"
              ></el-table-column>
              <el-table-column
                label="商品编码"
                width="140"
                prop="goodsCode"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                prop="goodsName"
                label="商品名称"
                min-width="180"
              >
                <template slot-scope="scope">
                  <ConditionSelGoods
                    v-model="scope.row.goodsName"
                    :is-reveal-sku="4"
                    :enable-status="5"
                    :spec-check="spec_check"
                    @selGoods="selGoods"
                    @specSelConfirm="specSelConfirm"
                    @goodsVisibleChange="
                      goodsVisibleChange($event, scope.$index)
                    "
                  />
                </template>
              </el-table-column>

              <el-table-column prop="specGropName" label="规格" min-width="160">
                <template slot-scope="scope">
                  <span v-if="scope.row.unitName">
                    {{ scope.row.unitName }};
                  </span>
                  <span>{{ scope.row.specGroupName }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="integral" label="积分" min-width="160">
                <template slot="header" slot-scope="scope">
                  <span v-if="false">{{ scope.$index }}</span>
                  <span style="color: #f40">*</span>
                  <span style="margin: 0 5px">积分</span>
                  <el-input
                    v-model="integral"
                    style="width: calc(100% - 100px)"
                    size="mini"
                    type="number"
                    placeholder="批量填充积分"
                  >
                    <el-button slot="append" @click="batchInput">
                      批量填充
                    </el-button>
                  </el-input>
                </template>
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.integral"
                    style="width: 100%"
                    size="mini"
                    :min="0"
                    placeholder="积分"
                    :controls="false"
                  />
                </template>
              </el-table-column>

              <el-table-column label="管理" fixed="right" width="140">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="mini"
                    :disabled="goods_list.length === 1"
                    @click="delData(scope.$index, scope.row)"
                  >
                    删除
                  </el-button>
                  <el-button type="text" size="mini" @click="addListGoods">
                    新增
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </ContainerTit>
</template>

<script>
  import ConditionSelGoods from "@/component/common/ConditionSelGoods";
  import {
    addIntegralRule,
    updateIntegralRule,
    getIntegralRuleInfo,
  } from "@/api/Integral";
  const goods = {
    id: "",
    goodsCode: "",
    goodsName: "",
    skuId: "",
    unitName: "",
    specGroupName: "",
    integral: "",
  };
  export default {
    name: "PointRuleAdd",
    components: {
      ConditionSelGoods,
    },
    data() {
      return {
        sub_load: false,
        goods_index: 0,
        spec_check: [],
        form_rules: {
          title: [
            { required: true, message: "请输入规则名称", trigger: "blur" },
          ],
        },
        integral: "",
        goods_list: [
          {
            id: "",
            goodsCode: "",
            integral: "",
            unitName: "",
            skuId: "",
            specGroupName: "",
            goodsName: "",
          },
        ],
        order_checked: true,
        goods_checked: false,
        add_form: {
          title: "",
          amount: "",
          startMoney: "",
          integral: "",
          goods: {},
        },
        rule_id: "",
      };
    },
    created() {
      if (this.$route.query.id) {
        this.rule_id = this.$route.query.id;
        this.getIntegralRuleInfo();
      }
    },
    activated() {
      if (this.$_isInit()) return;
      if (this.$route.query.id) {
        this.rule_id = this.$route.query.id;
        this.getIntegralRuleInfo();
      }
    },
    methods: {
      // 获取详情
      async getIntegralRuleInfo() {
        const { data } = await getIntegralRuleInfo(this.rule_id);
        this.add_form = {
          title: data.title,
          amount: data.amount,
          startMoney: data.startMoney,
          integral: data.integral,
          goods: data.goods,
        };
        this.order_checked = !!Number(data.amount);
        if (Array.isArray(data.goods)) {
          this.goods_list = [
            {
              id: "",
              goodsCode: "",
              integral: "",
              unitName: "",
              skuId: "",
              specGroupName: "",
              goodsName: "",
            },
          ];
        } else {
          this.goods_list = Object.values(data.goods);
        }

        this.goods_checked = !Array.isArray(data.goods);
      },
      // 选择商品
      selGoods(list) {
        let target = this.$_common.deepClone(this.goods_list);
        const goodsD = list.map((item) => {
          let specGroupName = item.specGroup
            .map((itemS) => {
              return itemS.specValueName;
            })
            .join("_");
          return {
            id: item.id,
            goodsCode: item.code,
            goodsName: item.title,
            skuId: item.skuId,
            specGroupName: specGroupName,
            unitName: item.unitName,
            integral: 0,
          };
        });
        target = this.$_common.unique(target.concat(goodsD), ["id", "skuId"]);
        this.goods_list = target.filter((item) => item.goodsName);
        this.addListGoods();
      },
      goodsVisibleChange(visible, index) {
        if (visible) {
          this.goods_index = index;
        }
      },
      // 批量填充
      batchInput() {
        if (this.integral <= 0) {
          this.$message.warning("请输入大于0的值");
          return;
        }
        this.goods_list.forEach((item) => {
          item.integral = this.integral;
        });
      },
      specSelConfirm(params) {
        if (!params.goodsD[0].skuId) {
          this.$message.warning("至少选择一项");
          return;
        }
        let target = this.$_common.deepClone(this.goods_list);
        const goodsD = params.goodsD.map((item) => {
          return {
            id: params.now_goods_data.id,
            goodsCode: params.now_goods_data.code,
            goodsName: params.now_goods_data.title,
            skuId: item.skuId,
            specGropName: item.spec.specGropName,
            unitName: item.spec.unitName,
            integral: "",
          };
        });
        target = this.$_common.unique(target.concat(goodsD), ["id", "skuId"]);
        this.goods_list = target.filter((item) => item.goodsName);
        this.addListGoods();
      },
      addListGoods() {
        this.goods_list.push(this.$_common.deepClone(goods));
      },
      delData(index) {
        this.goods_list.splice(index, 1);
      },
      async submit() {
        this.$refs["add_form"].validate(async (valid) => {
          if (valid) {
            if (!this.order_checked && !this.goods_checked) {
              this.$message.warning("至少设置一种积分奖励规则类型");
              return;
            }
            if (this.order_checked) {
              if (!this.add_form.amount) {
                this.$message.warning("请输入订单金额");
                return;
              }
              if (!this.add_form.integral) {
                this.$message.warning("订单奖励积分需大于0");
                return;
              }
            }
            const goodsList = this.goods_list.filter((item) => !!item.skuId);
            if (this.goods_checked) {
              if (!goodsList.length) {
                this.$message.warning("请选择商品");
                return;
              }
            }
            const isIntergral = goodsList.every((item) => item.integral > 0);
            if (!isIntergral) {
              this.$message.warning("按商品奖励积分规则，积分需大于0");
              return;
            }
            let goods = {};
            goodsList.forEach((item) => {
              goods[item.skuId] = item;
            });
            const params = {
              ...this.add_form,
              goods: goods,
            };
            this.sub_load = true;
            try {
              if (this.rule_id) {
                const data = await updateIntegralRule(this.rule_id, params);
              } else {
                const data = await addIntegralRule(params);
              }
              this.sub_load = false;
              this.$message.success("提交成功");
              this.$closeCurrentGoEdit("/PointsMall/PointRule");
            } finally {
              this.sub_load = false;
            }
          }
        });
      },
    },
  };
</script>

<style scoped></style>
