<template>
  <div class="app-container coupon-add">
    <el-row  :gutter="10">
      <el-col  :xs="{span: 22, offset: 0}" :sm=" {span: 18, offset: 0}" :lg="{span: 10, offset: 0}">
        <el-form ref="addItem" :model="addData" :rules="rules" label-width="100px">
          <el-form-item label="券包名称:" prop="title">
            <el-input v-model="addData.title" :readonly="readonly" placeholder="请输入券包名称" :maxlength="32" show-word-limit />
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <br>
    <el-button v-if="!readonly" type="primary" size="small" plain @click="couponTableVisible = true">添加优惠券</el-button>
    <br>
    <br>
    <span style="font-size: 14px; line-height: 40px">面值总额：￥{{ $numberFormat(totalPrice) }}</span>
    <span style="margin-left: 80px;font-size: 14px; line-height: 40px">优惠券数量：{{ totalCouponNum }}</span>
    <el-table :data="couponPkgItemList">
      <el-table-column label="券编号" prop="couponId" align="center" />
      <el-table-column label="券名称" prop="title" />
       <el-table-column label="券金额" min-width="85">
          <template slot-scope="{ row }">
            <div>￥{{ $numberFormat(row.discount) }}</div>
          </template>
        </el-table-column>
      <el-table-column label="门店承担比例" prop="channelSharedRate">
        <template slot-scope="{row}">
          {{row.channelSharedRate}}%
        </template>
      </el-table-column>
      <el-table-column label="使用场景" prop="type">
        <template slot-scope="{ row }">
          <div>{{ row.type.desc }}</div>
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center">
        <template slot-scope="{ row }">
          <div>
            <el-input-number
              :disabled="readonly"
              v-model="row.couponNum"
              controls-position="right"
              :min="1"
              size="small"
              @change="changeCouponNum"
            ></el-input-number>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="有效期限" min-width="85" align="center">
          <template slot-scope="{ row }">
            <div>领取后{{ row.dueDays }}天有效</div>
          </template>
        </el-table-column>
      <el-table-column v-if="!readonly" prop="date" label="操作" align="center">
        <template slot-scope="{ $index }">
          <el-button type="text" class="del" @click="couponPkgItemList.splice($index, 1);getIds();getPrice();getCouponNum()">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <br>
    <el-row v-if="!readonly">
      <el-col :span="23" style="text-align: right">
        <el-button type="info" @click="$router.go(-1)">取消</el-button>
        <el-button :loading="addIng" type="primary" @click="update()">保存</el-button>
      </el-col>
    </el-row>

    <!-- 添加券 -->
    <coupon-add :dialog-visible="couponTableVisible" :ids="ids" @close="couponTableVisible = false" @confirmCoupon="confirmCoupon" v-if="couponTableVisible" />
  </div>
</template>
<script>
import { couponPkgCreate, couponPkgDetail, couponPkgUpdate } from "@/api/business/couponPkg";
import CouponAdd from "./components/CouponAdd"
import { accMul } from '@/utils/util'
export default {
  name: 'CouponPkgAdd',
  components: {
    CouponAdd
  },
  data() {
    return {
      id: this.$route.query.id,
      readonly: this.$route.name === 'CouponPkgQuery',
      addData: {},
      couponTableVisible: false,
      couponPkgItemList: [],
      totalPrice: 0,
      totalCouponNum: 0,
      ids: [],
      addIng: false,
      rules: {
        title: [{ required: true, message: '请输入券包名称', trigger: 'blur' }]
      }
    };
  },
  created() {
    if(this.id) {
      couponPkgDetail(this.id).then(res => {
        const { couponPkgItemVOList, facePrice, title, couponNum } = res.data
        this.addData = { title }
        this.totalPrice = facePrice
        this.totalCouponNum = couponNum
        this.ids = couponPkgItemVOList.map(item => item.couponId)
        this.couponPkgItemList = couponPkgItemVOList.map(item => {
          return {
            ... item,
            type: item.type && JSON.parse(item.type)
          }
        })
      })
    }
  },
  methods: {
    confirmCoupon(arr) {
      this.couponPkgItemList = this.couponPkgItemList.concat(arr)
      this.getIds()
      this.getPrice()
      this.getCouponNum()
    },

    changeCouponNum(e) {
      let rule = /^([1-9]\d*)$/;
      if(!rule.test(e)) {
        this.$message.error('优惠券数量格式错误');
        return
      }
      this.getPrice()
      this.getCouponNum()
    },

    getPrice() {
      let num = 0
      this.couponPkgItemList.forEach(item => {
        num = (accMul(item.discount, item.couponNum)) + num
      })
      this.totalPrice = num
    },

    getIds() {
      this.ids = this.couponPkgItemList.map(item => item.couponId)
    },

    getCouponNum() {
      let num = 0
      this.couponPkgItemList.forEach(item => {
        num = item.couponNum + num
      })
      this.totalCouponNum = num
    },

    update() {
      const subForm = this.$refs["addItem"];
      subForm.validate((valid) => {
        if (valid) {
          if(!this.couponPkgItemList.length) {
            this.$message.error('请添加优惠券');
            return
          }
          let couponIndex = this.couponPkgItemList.findIndex((item) => {
            let rule = /^([1-9]\d*)$/;
            return !rule.test(item.couponNum);
          });
          // 判断优惠券数量格式
          if (couponIndex != -1) {
            this.$message.error(
              `券${this.couponPkgItemList[couponIndex].title}的数量格式错误！`
            );
            return;
          }
          this.addIng = true
          let data = {
            title: this.addData.title,
            couponPkgItemList: this.couponPkgItemList,
            facePrice: this.totalPrice,
            couponNum: this.totalCouponNum
          }
          if(this.id){
            data.id = this.id
          }
          let request = this.id ? couponPkgUpdate : couponPkgCreate
          request(data).then(res => {
            this.addIng = false
            if (res.code === 0) {
              this.$message({
                message: this.id ? '修改成功!' : '添加成功!',
                type: 'success'
              })
              this.$store.dispatch('tagsView/delView', this.$route)
              this.$router.go(-1)
            }
          }).catch(() => {
            this.addIng = false
          })
          }
      });
    }
  },
};
</script>
<style>
</style>
