<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">规则说明</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="奖励对象" prop="staff">
            <el-button type="primary" size="mini" @click="staff_show = true">
              选择
            </el-button>
            <div style="display: inline-block; margin-left: 10px">
              <el-tag
                v-for="(item, index) in staff_list"
                :key="index"
                closable
                @close="closeTag(index)"
              >
                {{ item.staffName }}
              </el-tag>
            </div>
          </el-form-item>
          <el-form-item label="计算方式">
            <el-radio-group v-model="add_form.computed">
              <el-radio :label="5">重复计算</el-radio>
              <el-radio :label="4">单独计算</el-radio>
            </el-radio-group>
            <div class="form-tip">
              重复计算，即例如A商品
              100元，B商品100元，客户下单A商品和B商品各10个。
              <br />
              提成是订单金额的3%，B商品是卖一个奖励10元
              <br />
              重复计算的结果是（100*10+100*10）*0.03+10*10=160元
              <br />
              单独计算的结果是 100*10*0.03+10*10=130元
            </div>
          </el-form-item>
          <el-form-item label="规则设置">
            <el-checkbox v-model="order_checked">按订单</el-checkbox>

            <br />
            <div v-if="order_checked">
              <span>按订单的消费金额</span>
              <el-input-number
                v-model="add_form.percentage"
                :min="0"
                :controls="false"
                style="width: 100px; margin: 0 10px"
              ></el-input-number>
              <span>%奖励</span>
            </div>
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="goods_checked">按商品</el-checkbox>
            <br />
            <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="商品编码"
                min-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="goodRule" label="商品规格" min-width="130">
                <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
                label="金额"
                fixed="right"
                min-width="130"
                prop="money"
              >
                <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="money"
                    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.money"
                    style="width: 100%"
                    size="mini"
                    :min="0"
                    type="text"
                    placeholder="金额"
                    :controls="false"
                    @blur="editNumChange(scope.$index, 'buyerNum')"
                  />
                </template>
              </el-table-column>
              <el-table-column label="管理" fixed="right" width="160">
                <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>
    <!--    业务员-->
    <staffListModal
      v-if="staff_show"
      :is-check="true"
      :is-show="staff_show"
      @cancel="staff_show = false"
      @confirm="selStaff"
    />
  </ContainerTit>
</template>

<script>
  import {
    updateRewardRule,
    addRewardRule,
    getRewardRuleInfo,
  } from "@/api/Reward";

  import staffListModal from "@/component/common/staffListModal.vue";
  import ConditionSelGoods from "@/component/common/ConditionSelGoods";
  const goods = {
    id: "",
    goodsCode: "",
    goodsName: "",
    skuId: "",
    unitName: "",
    money: "",
  };
  export default {
    name: "RuleCommission",
    components: {
      ConditionSelGoods,
      staffListModal,
    },
    data() {
      const staffValidate = (rule, value, callback) => {
        if (!this.staff_list.length) {
          callback(new Error("至少选择一个奖励对象"));
        } else {
          callback();
        }
      };
      return {
        staff_list: [],
        staff_show: false,
        goods_checked: false,
        order_checked: true,
        sub_load: false,
        money: "",
        goods_index: 0,
        spec_check: [],
        form_rules: {
          title: [
            { required: true, message: "请输入规则名称", trigger: "blur" },
          ],
          staff: [
            {
              type: "array",
              required: true,
              validator: staffValidate,
              trigger: "change",
            },
          ],
        },
        goods_list: [
          {
            id: "",
            goodsCode: "",
            goodsName: "",
            skuId: "",
            unitName: "",
            money: "",
          },
        ],
        add_form: {
          staff: [],
          title: "",
          computed: 5,
          percentage: "",
          goods: {},
        },
      };
    },
    created() {
      if (this.$route.query.id) {
        this.rule_id = this.$route.query.id;
        this.getRewardRuleInfo();
      }
    },
    activated() {
      if (this.$_isInit()) return;
      if (this.$route.query.id) {
        this.rule_id = this.$route.query.id;
        this.getRewardRuleInfo();
      }
    },
    methods: {
      // 获取详情
      async getRewardRuleInfo() {
        const { data } = await getRewardRuleInfo(this.rule_id);
        this.add_form = {
          title: data.title,
          staff: [],
          percentage: data.percentage,
          goods: data.goods,
          computed: data.computed || 5,
        };
        this.order_checked = !!Number(data.percentage);

        if (Array.isArray(data.goods)) {
          this.goods_list = [
            {
              id: "",
              goodsCode: "",
              goodsName: "",
              skuId: "",
              unitName: "",
              money: "",
            },
          ];
        } else {
          this.goods_list = Object.values(data.goods);
        }
        this.goods_checked = !Array.isArray(data.goods);

        this.staff_list = data.staff;
      },
      delData(index) {
        this.goods_list.splice(index, 1);
      },
      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,
            money: "",
          };
        });
        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;
        }
      },
      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,
            money: "",
          };
        });
        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));
      },
      // 选择员工
      selStaff(list) {
        const arr = list.map((item) => {
          return {
            id: item.id,
            staffName: item.staffName,
          };
        });
        if (!this.staff_list.length) {
          this.staff_list = arr;
        } else {
          this.staff_list = this.$_common.unique(this.staff_list.concat(arr), [
            "id",
          ]);
        }
      },
      closeTag(index) {
        this.staff_list.splice(index, 1);
      },
      // 批量填充
      batchInput() {
        if (this.money <= 0) {
          this.$message.warning("请输入大于0的值");
          return;
        }
        this.goods_list.forEach((item) => {
          item.money = this.money;
        });
      },
      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.percentage) {
                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 isMoney = goodsList.every((item) => item.money > 0);
            if (!isMoney) {
              this.$message.warning("按商品奖励规则，金额需大于0");
              return;
            }
            let goods = {};
            goodsList.forEach((item) => {
              goods[item.skuId] = item;
            });
            const staff = this.staff_list.map((item) => item.id);
            const params = {
              ...this.add_form,
              goods: goods,
              staff: staff,
            };
            this.sub_load = true;
            try {
              if (this.rule_id) {
                const data = await updateRewardRule(this.rule_id, params);
              } else {
                const data = await addRewardRule(params);
              }
              this.sub_load = false;
              this.$message.success("提交成功");
              this.$closeCurrentGoEdit("/saleCommission/CommissionRule");
            } finally {
              this.sub_load = false;
            }
          }
        });
      },
    },
  };
</script>

<style scoped></style>
