<template>
  <div style="background-color:#f7f7f7;padding:10px 10px;">
    <div class="couponPage" v-show="type == '1'">
      <div>
        <div style="height:58px;line-height:58px;">
          <div style="color:#0006"> <span>优惠券管理</span> <span style="padding:0 5px;">></span> <span
              style="color:#000000e6">资金池</span></div>
        </div>
        <!-- 搜索 -->
        <div class="formSearch">
          <!-- 搜索条件 -->
          <el-form :inline="true" :model="query" class="demo-form-inline">
            <el-form-item label="名称">
              <el-input v-model="query.poolName" placeholder="请输入名称" />
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="query.fundsStatus" placeholder="请选择状态">
                <el-option v-for="item in activityStatusSelect" :key="item.index" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-form>
          <div>
            <el-button style="background-color: #3F9B6A;color: #fff" @click="search">查询</el-button>
            <el-button class="buttonHover" style="color: #606266;border: 1px solid #dddfe5;background-color: #fff;"
              @click="clear">重置</el-button>
          </div>
        </div>
        <div style="margin: 0  0 20px 0;">
          <el-button icon="el-icon-circle-plus-outline" style="background-color: #3F9B6A;color: #fff;"
            @click="addActivity">新增</el-button>
        </div>
        <!-- 表格 -->
        <div class="tableBox">
          <el-table ref="multipleTable" :data="tableData"
            :header-cell-style="{fontSize: '14px',color:'#0009',fontWeight: 'normal',backgroundColor:'#f5f8f9'}"
            tooltip-effect="light">
            <!-- <el-table-column label="编号">
              <template slot-scope="scope">{{ scope.row.poolId }}</template>
            </el-table-column> -->
            <el-table-column label="资金池名称">
              <template slot-scope="scope">{{ scope.row.poolName }}</template>
            </el-table-column>
            <!-- <el-table-column label="出资方">
              <template slot-scope="scope">{{ scope.row.contributor }}</template>
            </el-table-column> -->
            <el-table-column label="总金额">
              <template slot-scope="scope">{{ scope.row.totalAmount }}</template>
            </el-table-column>
            <el-table-column
              label="出资方">
              <template slot-scope="scope">
                <el-popover trigger="hover" placement="top">
                  <p style="max-width: 300px;">{{ scope.row.contributor }}</p>
                  <div slot="reference" style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;width: 100%;" >
                    {{ scope.row.contributor }}
                  </div>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="状态">
              <template slot-scope="scope">
                <span v-if="scope.row.fundsStatus == '1'">启用中</span>
                <span v-else-if="scope.row.fundsStatus == '2'">已关闭</span>
                <span v-else>未启用</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right">
              <template slot-scope="scope">
                <div class="btnList">
                  <!-- <div class="tableBtn greens" @click="editActivity(scope.row)">编辑</div> -->
                  <div v-if="scope.row.fundsStatus == '1'" class="tableBtn greens" @click="xq(scope.row)">查看详情</div>
                  <div v-if="scope.row.fundsStatus == '1'" class="tableBtn greens" @click="addcoupon(scope.row)">创建优惠券
                  </div>
                  <div v-if="scope.row.fundsStatus == '1'" class="tableBtn greens"
                    @click="endActivityeditPool(scope.row,'2')">禁用</div>
                  <div v-else-if="scope.row.fundsStatus == '2'" class="tableBtn greens" @click="delActivity(scope.row)">
                    删除</div>
                  <div v-else class="tableBtn greens" @click="endActivityeditPool(scope.row,'1')">开启</div>
                  <!-- <div class="tableBtn greens" @click="delActivity(scope.row)">删除</div> -->
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div style="display: flex;justify-content: space-between;" class="bom">
            <div style="font-size: 14px;">共 <span style="color: #3F9B6A;">{{total}}</span> 项数据</div>
            <el-pagination :current-page="query.pageNumber" :page-sizes="[10, 20, 50, 100]" :page-size="10" background
              small layout="prev, pager, next" :total="total" @size-change="handleSizeChange"
              @current-change="handleCurrentChange">
            </el-pagination>
          </div>
        </div>

        <el-dialog :title="editForm ? '修改资金池' : '新增资金池'" :visible.sync="activityVisible" width="500px" center
          :close-on-click-modal="false" @close="activityVisible">
          <el-form ref="form" :model="form" label-width="100px" :rules="couponRules">
            <el-form-item label="资金池名称:" prop="poolName">
              <el-input v-model="form.poolName" placeholder="请输入资金池名称" />
            </el-form-item>
            <el-form-item label="总金额:" style="margin: 20px 0;" prop="totalAmount">
              <el-input v-model.number="form.totalAmount" placeholder="请输入总金额" />
            </el-form-item>
            <el-form-item label="出资方:" prop="contributor">
              <el-input maxlength="200" show-word-limit rows="4" type="textarea" v-model="form.contributor"
                placeholder="请输入出资方" />
            </el-form-item>
          </el-form>
          <div class="footer" style="margin-top: 25px;">
            <div class="btn_list">
              <span @click="cancel" class="buttonHover"
                style="color: #606266;border: 1px solid #dddfe5;background-color: #fff;">取消</span>
              <span @click="save" style="background-color: #3F9B6A;color: #fff">保存</span>
            </div>
          </div>
        </el-dialog>
      </div>
    </div>
    <div class="couponPage" v-show="type == '2'">
      <div style="height:58px;line-height:58px;">
        <div style="color:#0006"> <span>优惠券管理</span> <span style="padding:0 5px;">></span> <span
            style="color:#000000e6">创建优惠券</span></div>
      </div>
      <TitleWithCircle title="资金池" style="margin-bottom: 15px;"/>
      <div style="display: flex;margin-bottom: 20px;padding-left: 30px;">
        <div>资金池名称:{{ coupoobj.poolName }}</div>
        <div style="margin-left: 30px;">资金池可用金额:<span style="font-weight: bold;">{{ coupoobj.symon }}</span></div>
      </div>
      <coupon :couponfrom="couponfrom" :coupoobj="coupoobj" @changevalue="changevalue"/>
      <div class="footer">
        <div class="btn_list" style="margin-top: 30px;">
          <span @click="qxcoupon" class="buttonHover"
            style="color: #606266;border: 1px solid #dddfe5;background-color: #fff;">取消</span>
          <span @click="savecoupon" style="background-color: #3F9B6A;color: #fff">保存</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import {
    getcereFundsPoolData,
    addcereFundsPool,
    delPool,
    editPool,
    cereCouponMainTable,
    totalCapitalBalance,
    addcereCouponCategory
  } from '@/api/couponmanagement/capitalpool.js'
  import router from '@/router';
  import coupon from './coupon.vue';
  import TitleWithCircle from '@/components/top/index';
  export default {

    components: {
      coupon,TitleWithCircle
    },
    data() {
      return {
        couponRules: {
          poolName: [{
              required: true,
              message: '请输入资金池名称',
              trigger: 'blur'
            },
            {
              min: 0,
              max: 20,
              message: '长度不超过20个字符',
              trigger: 'blur'
            }
          ],
          totalAmount: [{
            required: true,
            message: '请输入总金额',
            trigger: 'blur'
          }, ],
          contributor: [{
            required: true,
            message: '请输入出资方',
            trigger: 'blur'
          }, ],
        },
        useCategorylist:'',
        usedMerchantslist:'',
        couponfrom: {
          usedMerchants: 1,
          couponName: '',
          remark: '',
          couponType: '1', // 默认值
          useCategory: 1,
          maxDiscountAmount: null,
          usageThreshold: null, //使用门槛不用
          discountContent: null,
          pointsRequired: 0,
          startTime: '',
          endTime: '',
          totalCoupons: null,
          totalFunds: null,
        },
        coupoobj: {},
        type: '1',
        query: {
          activityName: '', // 活动名称
          // 活动状态 0-报名未开始 1-报名进行中 2-活动待开始 3-活动进行中 4-活动已结束
          state: '',
          pageNumber: 1,
          pageSize: 10
        },
        total: 0,
        tableData: [],
        activityStatusSelect: [{
            index: 0,
            label: '未启用',
            value: 0
          },
          {
            index: 1,
            label: '启用中',
            value: 1
          },
          {
            index: 2,
            label: '已关闭',
            value: 2
          },
        ],
        activityVisible: false,
        editForm: false,
        activityDetailVisible: false,
        form: {
          poolName: '',
          contributor: '',
          totalAmount: null,
          fundsStatus: '0'
        }
      }
    },
    created() {
      this.getAll()
    },
    methods: {
      changevalue(e,list) {
        console.error(e,list )
        this[e] = list
      },
      xq(e) {
        console.log(e )
        // 跳转路由
        router.push({
          path: '/other/capitalpoolinfo',
          query: {
            id: e.poolId
          }
        })
      },
      savecoupon() {
        let that = this
        if(!this.couponfrom.couponName) {
          return
        }
        if(!this.couponfrom.startTime) {
          return
        }
        if(!this.couponfrom.totalCoupons) {
          return
        }
        if(!this.couponfrom.maxDiscountAmount) {
          return 
        }
        if(!this.couponfrom.discountContent) {
          return 
        }
        if(this.couponfrom.couponType == '1') {
          if(Number(this.couponfrom.discountContent) >= Number(this.couponfrom.maxDiscountAmount)) {
            return 
          }   
        } 
        let c1 = this.changecouponfrom()
        console.error(c1)
        console.error(this.useCategorylist)
        console.error(this.usedMerchantslist)
        console.error(this.coupoobj)
        let from = this.couponfrom
        from.fundPoolId = this.coupoobj.poolId
        from.totalFunds = c1
        if (c1 > this.coupoobj.symon) {
          that.$message({
            message: '金额不足',
            error: 'error'
          });
          return
        }
        from.maxDiscountAmount = Number(from.maxDiscountAmount)
        from.discountContent = Number(from.discountContent)
        from.pointsRequired = Number(from.pointsRequired)
        from.totalCoupons = Number(from.totalCoupons)
        console.error({
          ...from
        })
        // return
        cereCouponMainTable(from).then(res => {
          console.error(res)
          if (res.data) {
            if(res.data.useCategory == '2') {
              let info1 = {
                couponId:res.data.id,
                usedMerchants:1,
                categoryIds:that.useCategorylist
              }
              addcereCouponCategory(info1).then(res1 => {
                console.error(res1)
              })
            }
            if(res.data.usedMerchants == '3') {
              let info2 = {
                couponId:res.data.id,
                usedMerchants:3,
                categoryIds:that.usedMerchantslist
              }
              addcereCouponCategory(info2).then(res2 => {
                console.error(res2)
              })
            }
            that.$message({
              message: '提交成功',
              type: 'success'
            });
          } else {
            that.$message({
              message: '提交失败',
              error: 'success'
            });
          }
          setTimeout(() => {
            that.type = '1'
          }, 2000)
        })
      },
      changecouponfrom() {
        let num = 0
        if (this.couponfrom.couponType == '1') {
          num = (this.couponfrom.discountContent ? Number(this.couponfrom.discountContent) : 0) * (this.couponfrom
            .totalCoupons ? Number(this.couponfrom.totalCoupons) : 0)
        } else if (this.couponfrom.couponType == '2') {
          num = (this.couponfrom.maxDiscountAmount ? Number(this.couponfrom.maxDiscountAmount) : 0) * (this.couponfrom
            .totalCoupons ? Number(this.couponfrom.totalCoupons) : 0)
        }
        return num
      },
      qxcoupon() {
        this.type = '1'
      },
      async addcoupon(e) {
        let that = this

        let c1 = {
          symon: 0,
          ...e
        }
        await totalCapitalBalance({
          poolId: e.poolId
        }).then(res => {
          console.error(res)
          c1.symon = res.data
        })
        this.type = '2'
        this.coupoobj = c1
        console.error(this.coupoobj)
      },
      endActivityeditPool(item, type) {
        let that = this
        let form = item
        form.totalAmount = Number(form.totalAmount)
        form.fundsStatus = type
        editPool(form).then(res => {
          console.error(res)
          if (res.data) {
            that.$message({
              message: '修改成功',
              type: 'success'
            });
          } else {
            that.$message({
              message: '修改失败',
              error: 'success'
            });
          }
          that.search()
        })
      },
      save() {
        let that = this
        console.error(this.form)
        let form = this.form
        that.$refs.form.validate((valid) => {
          if (valid) {
            form.totalAmount = Number(form.totalAmount)
            if (that.editForm) {
              editPool(form).then(res => {
                // console.error(res)
                if (res.data) {
                  that.$message({
                    message: '修改成功',
                    type: 'success'
                  });
                } else {
                  that.$message({
                    message: '修改失败',
                    error: 'success'
                  });
                }
                that.search()
                that.activityVisible = false
                that.form = {
                  poolName: '',
                  contributor: '',
                  totalAmount: null,
                  fundsStatus: '0'
                }
              })
            } else {
              addcereFundsPool(form).then(res => {
                // console.error(res)
                if (res.data) {
                  that.$message({
                    message: '提交成功',
                    type: 'success'
                  });
                } else {
                  that.$message({
                    message: '提交失败',
                    error: 'success'
                  });
                }
                that.search()
                that.activityVisible = false
                that.form = {
                  poolName: '',
                  contributor: '',
                  totalAmount: null,
                  fundsStatus: '0'
                }
              })
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });


      },
      cancel() {
        this.activityVisible = false
        this.form = {
          poolName: '',
          contributor: '',
          totalAmount: null,
          fundsStatus: '0'
        }
      },
      async getAll() {
        const res = await getcereFundsPoolData(this.query)
        this.tableData = res.data.content
        this.total = res.data.numberOfElements
      },
      handleSizeChange(val) {
        this.query.pageSize = val
        this.getAll()
      },
      handleCurrentChange(val) {
        this.query.pageNumber = val
        this.getAll()
      },
      search() {
        this.total = 1
        this.query.pageNumber = 1
        this.getAll()
      },
      // 重置
      clear() {
        this.query = {
          activityName: '',
          state: '',
          pageNumber: 1,
          pageSize: 10
        }
        this.getAll()
      },
      // 活动详情
      details(row) {
        this.form = row
        this.activityDetailVisible = true
      },
      // 添加活动
      addActivity() {
        this.editForm = false
        this.activityVisible = true
      },
      // 编辑
      editActivity(row) {
        this.editForm = true
        this.form = row
        this.activityVisible = true
      },
      async endActivity(row) {
        const res = await endCoupon({
          activityId: row.activityId
        })
        if (res.code === '') {
          this.$message({
            message: '结束成功',
            type: 'success'
          })
        } else {
          this.$message({
            message: res.message,
            type: 'error'
          })
        }
        this.getAll()
      },
      async delActivity(row) {
        let that = this
        this.$confirm('此作将永久操删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delPool({
            poolId: row.poolId
          }).then(res => {
            console.error(res)
            if (res.data) {
              that.$message({
                message: '删除成功',
                type: 'success'
              });
            } else {
              that.$message({
                message: '删除失败',
                error: 'success'
              });
            }
            that.search()
          }).catch(error => {
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

    }
  }
</script>

<style scoped lang="scss">

  .el-table {
    height: calc(100vh - 330px);
  }

  .bom {
    margin-top: 40px;
  }

  .el-form-item {
    margin-bottom: 0;
  }

  ::v-deep .el-dialog__header {
    border-bottom: 2px solid #eee;
    background-color: #fff;
  }

  ::v-deep .el-dialog__title {
    color: #303133;
  }

  .footer {
    font-size: 24px;

    .btn_list {
      display: flex;
      flex-direction: row-reverse;

      span {
        padding: 0;
        margin: 0;
        width: 100px;
        height: 32px;
        line-height: 32px;
        text-align: center;
        display: inline-block;
        font-size: 16px;
        border-radius: 4px;
        box-sizing: border-box;

        &:hover {
          cursor: pointer;
        }

        &:nth-child(1) {
          background: rgba(255, 255, 255, 1);
          order: 1px solid rgba(224, 229, 235, 1);

          border: 1px solid rgba(224, 229, 235, 1);
        }

        &:nth-child(2) {
          background: #3f9b6a;
          color: #fff;
          margin-right: 20px;
        }
      }
    }
  }

  .couponPage {

    padding: 0 20px 20px 20px;
    min-height: calc(100vh - 50px - 20px);
    background-color: #Fff;


    .tableBox {
      text-align: center;

      .fenye {
        // margin: 20px;
      }
    }
  }

  .couponDialogBox {
    max-height: 600px;
    overflow-y: auto;
  }

  .formSearch {

    display: flex;
    width: 100%;
    font-size: 14px;
    justify-content: space-between;
    padding-bottom: 10px;
    align-items: center;

  }

  .tableBtn {
    display: inline-block;
    margin-right: 10px;
  }

  .greens {
    color: #3F9B6A;
  }

  ::v-deep .buttonHover:hover {
    color: #3f9b6a !important;
    border-color: #c5e1d2 !important;
    background-color: #ecf5f0 !important;
    outline: none;
  }

  ::v-deep .el-pagination__total {
    position: absolute;
    left: 10px;
  }

  ::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
    background-color: #3f9b6a;
  }
</style>
