<template>
  <div class="container">
    <div class="query-form">
      <div class="query-form-left-panel">
        <el-button icon="el-icon-s-promotion" type="primary" size="mini" @click="handleIssue">建立优惠券</el-button>
        <!-- <el-button icon="el-icon-full-screen" type="warning" size="mini" @click="handleVerification">核销</el-button> -->
      </div>
      <div class="query-form-right-panel">
        <el-form :inline="true" class="docTime" :model="queryForm" @submit.native.prevent>
          <el-form-item>
            <el-input v-model="queryForm.name" placeholder="优惠券名称" clearable size="small" style="width: 150px"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" size="mini" @click="queryData">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-table style="width: 100%;margin-top:5px" max-height="650" :header-cell-style="{background: 'linear-gradient(#6cb3ff, #1873d4)' ,color:'#eeeeee'}" ref="list" class="custom-table" highlight-current-row border v-loading="listLoading" :data="list" :element-loading-text="elementLoadingText">
      <el-table-column align="center" width="50" type="index" label="序号"></el-table-column>
      <el-table-column show-overflow-tooltip align="center" min-width="100" prop="state" label="状态">
        <template #default="{row}">
          <el-tag effect="dark" v-if="row.state===0">新增</el-tag>
          <el-tag effect="dark" type="info" v-if="row.state===1">送审</el-tag>
          <el-tag effect="dark" type="danger" v-if="row.state===2">回收</el-tag>
          <el-tag effect="dark" type="success" v-if="row.state===3">审核</el-tag>
          <el-tag effect="dark" type="warning" v-if="row.state===4">反审核</el-tag>
          <el-tag effect="dark" type="danger" v-if="row.state===11">审核失败</el-tag>
          <el-tag effect="dark" type="danger" v-if="row.state===12">退款中</el-tag>
          <el-tag effect="dark" type="success" v-if="row.state===5">打款待审</el-tag>
          <el-tag effect="dark" type="success" v-if="row.state===6">通过</el-tag>
          <el-tag effect="dark" type="danger" v-if="row.state===11">不通过</el-tag>
          <el-tag type="danger" v-if="row.state===7">反审核</el-tag>
          <el-tag effect="dark" type="success" v-if="row.state===8">已发布</el-tag>
          <el-tag effect="dark" type="warning" v-if="row.state===9">已回收</el-tag>
          <el-tag effect="dark" type="success" v-if="row.state===10">已关闭</el-tag>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip align="center" min-width="130" prop="couponName" label="优惠券名称"></el-table-column>
      <el-table-column show-overflow-tooltip align="center" min-width="100" prop="couponNumber" label="优惠券数量"></el-table-column>
      <el-table-column show-overflow-tooltip align="center" min-width="100" prop="couponType" label="优惠方式">
        <template #default="{row}">
          {{row.couponType===0?'代金券':row.couponType===1?'折扣券':row.couponType===2?'代扣券':''}}
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip align="center" min-width="100" prop="fullKimsMoney" label="抵扣金额"></el-table-column>
      <el-table-column show-overflow-tooltip align="center" min-width="100" prop="fullDiscountMoney" label="折扣(%)"></el-table-column>
      <el-table-column show-overflow-tooltip align="center" min-width="100" prop="serviceConditions" label="优惠限制">
        <template #default="{row}">
          {{row.serviceConditions===0?'满减':row.serviceConditions===1?'没有限制':''}}
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip align="center" min-width="100" prop="fullReductionMoney" label="满减金额"></el-table-column>
      <el-table-column show-overflow-tooltip align="center" min-width="100" prop="suitableStore" label="适用门店">
        <template #default="{row}">
          <div v-if="row.suitableStore===0">所有门店</div>
          <el-button v-if="row.suitableStore===1" size="mini">查看门店</el-button>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip align="center" min-width="100" prop="suitableProject" label="适用项目">
        <template #default="{row}">
          <div v-if="row.suitableProject===0">所有项目</div>
          <el-button v-if="row.suitableProject===1" size="mini">查看项目</el-button>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip align="center" min-width="100" prop="indateType" label="有效方式">
        <template #default="{row}">
          {{row.indateType===0?'领取后多少天':row.indateType===1?'固定日期':''}}
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip align="center" min-width="130" prop="startDay" label="领取后多少天生效"></el-table-column>
      <el-table-column show-overflow-tooltip align="center" min-width="130" prop="endDay" label="生效后多少天内有效"></el-table-column>
      <el-table-column show-overflow-tooltip align="center" min-width="180" label="有效日期">
        <template #default="{row}">
          {{row.indateType===1?`${row.startDate.split(' ')[0]} ~ ${row.endDate.split(' ')[0]}`:''}}
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip align="center" min-width="130" prop="shareCommissionRules" label="分享提成规则">
        <template #default="{row}">
          {{row.shareCommissionRules===0?'固定提成(元)':row.shareCommissionRules===1?'单据金额抽成(%)':''}}
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip align="center" min-width="100" prop="fixedAmount" label="固定提成(元)"></el-table-column>
      <el-table-column show-overflow-tooltip align="center" min-width="120" prop="orderCommission" label="单据金额抽成(%)"></el-table-column>
      <el-table-column show-overflow-tooltip align="center" min-width="120" prop="guaranteeMoney" label="保证金" sortable></el-table-column>
      <el-table-column show-overflow-tooltip align="center" min-width="80" prop="imageUrl" label="活动图片">
        <template #default="{row}">
          <el-image style="width: 30px; height: 30px" :src="imgPath+row.fileLists[0].filePath+'/'+row.fileLists[0].fileName" :preview-src-list="[imgPath+row.fileLists[0].filePath+'/'+row.fileLists[0].fileName]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="520" label="操作">
        <template #default="{ row, $index }">
          <el-button type="primary" size="mini" :disabled="row.state!==0&&row.state!=2&&row.state!=4" @click="handleEdit(row)">编辑</el-button>
          <el-button type="info" size="mini" :disabled="row.state!==0&&row.state!=2&&row.state!=4" @click="handleAudit(row,1)">送审</el-button>
          <el-button type="danger" size="mini" :disabled="row.state!=1" @click="handleAudit(row,2)">回收</el-button>
          <el-button type="success" size="mini" :disabled="row.state!=1" @click="handleAudit(row,3)">审核</el-button>
          <el-button type="warning" size="mini" :disabled="row.state!=3" @click="handleAudit(row,4)">反审核</el-button>
          <el-button type="primary" size="mini" :disabled="row.state!=3" @click="handleRemit(row,true)">打款</el-button>
          <el-button type="danger" size="mini" :disabled="row.state!=5" @click="handleAudit(row,12)">退款</el-button>
          <!-- <el-button type="primary" size="mini">增量</el-button>
          <el-button type="warning" size="mini">作废</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background :current-page="queryForm.pageNum" :page-size="queryForm.pageSize" :layout="layout" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
    <verification ref="verification" @fetch-data="fetchData"></verification>
    <Pay ref="Pay" @fetch-data="fetchData"></Pay>
  </div>
</template>

<script>
import Verification from "./components/verification";
import Pay from "./components/pay";
import {
  getList,
  doDelete,
  doAudit,
  doPay
} from "@/api/discount-coupon/management.js";
import { partten } from "@/utils/partten/index.js";
import Bus from "../../bus";

export default {
  name: "management",
  components: { Verification, Pay },
  data() {
    return {
      // 列表
      list: [
        // {
        //   name: "德财五周年庆",
        //   type: "代金券",
        //   couponNumber: 10000,
        //   deductionAmount: 588,
        //   shareAmount: 10,
        //   desc1: 219,
        //   desc2: 2,
        //   desc3: "2022-07-01 -- 2022-07-31",
        //   status: 1,
        // },
      ],
      listLoading: false,
      elementLoadingText: "正在加载...",
      // 分页
      queryForm: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      layout: "total, sizes, prev, pager, next, jumper",
      // 数据
      imgPath: "",
    };
  },
  created() {
    this.imgPath = partten.imagePath;
    this.fetchData();
    // 发布、编辑完成
    Bus.$on("issueComplete", () => {
      this.fetchData();
    });
  },
  methods: {
    // ========================== 查询 ========================== //
    queryData() {
      this.queryForm.pageNum = 1;
      this.fetchData();
    },
    // 获取优惠券活动数据
    async fetchData() {
      this.listLoading = true;
      let { code, pageInfo } = await getList(this.queryForm);
      this.listLoading = false;
      if (code == "000000") {
        this.list = Array.from(pageInfo.list);
        this.total = pageInfo.total;
        this.queryForm.pageNum = pageInfo.pageNum;
        this.queryForm.pageSize = pageInfo.pageSize;
      }
    },
    // 分页-一页多少条
    handleSizeChange(val) {
      this.queryForm.pageSize = val;
      this.fetchData();
    },
    // 分页-第几页
    handleCurrentChange(val) {
      this.queryForm.pageNum = val;
      this.fetchData();
    },
    // ========================== 其它 ========================== //
    // 编辑
    handleEdit(row) {
      // Bus.$emit("/couponIssue", row)
      this.$router.push({ name: "CouponIssue", params: row });
    },
    // 查询所有领取人
    handleGoter(row) {
      this.$router.push({ name: "AllGot", params: row });
    },
    // 发布
    handleIssue() {
      this.$router.push("/couponIssue");
    },
    // 核销
    handleVerification() {
      this.$refs.verification.open();
    },
    // 审核
    async handleAudit(row, state) {
      // 三元表达式判断当前是什么操作，1=送审,2=回收,3=审核,4=反审核,12=退款
      this.$confirm(`确定要${state === 1 ? '送审' : state === 2 ? '回收' : state === 3 ? '审核' : state === 4 ? '反审核' : '退款'}当前项吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success",
        cancelButtonClass: "cancelbtnFalses",
        confirmButtonClass: "confirmbtnFalses",
      })
        .then(async () => {
          let { code, message } = await doAudit({ id: row.id, state: state });
          if (code == "000000") {
            this.$message.success(
              state === 1
                ? "送审成功"
                : state === 2
                  ? "回收成功"
                  : state === 3
                    ? "审核成功"
                    : state === 4 ? "反审核成功" : state === 12 ? "退款申请提交成功" : message
            );
            this.fetchData();
          }
          if (code == "010000") {
            this.$message.error(message);
          }
        })
        .catch(() => { });

    },
    // 打款
    handleRemit(row) {
      // shareCommissionRules:0=固定提成，1=单据金额抽成
      // 固定提成需要打款保证金，单据金额抽成无需打款保证金
      if (row.shareCommissionRules === 0) {
        this.$refs.Pay.show(row)
      }
      if (row.shareCommissionRules === 1) {
        this.$confirm("当前分享提成规则：单据金额抽成，无法打款保证金，是否提交申请？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "success",
          cancelButtonClass: "cancelbtnFalses",
          confirmButtonClass: "confirmbtnFalses",
        })
          .then(async () => {
            let form = Object.assign({}, row);
            form.state = 5
            for (let key in form) {
              // format写法会将null类型强行转化成字符串的‘null’，传到后台，后台会报错，所以需要删掉值为null的字段
              if (form[key] !== 0 && !form[key]) {
                delete form[key]
              }
              // 这三个数组无法用format传值，会自动被编译成字符串，例：[object object]，后台无法识别，所以需要删掉
              if (key == 'useStores' || key == 'useProjects' || key == 'fileLists') {
                delete form[key]
              }
            }
            let format = new FormData()
            Object.keys(form).map(key => {
              format.append(key, form[key])
            })
            let { code, message } = await doPay(format)
            if (code == '000000') {
              this.$message({
                message: message,
                type: 'success'
              });
              // 成功后刷新页面的数据
              this.fetchData()
            }
            if (code == '010000') {
              this.$message({
                message: message,
                type: 'error'
              });
            }
          })
          .catch(() => { });
      }
    },
    // 删除
    async handleDelete(row) {
      let { code, message } = await doDelete(row.id);
      if (code == "000000") {
        this.$message.success("删除成功");
      }
      if (code == "010000") {
        this.$message.error(message);
      }
    },
  },
};
</script>

<style scoped>
@import "./styles/index.css";
</style>
