<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" placeholder="请输入优惠券标题" />
      <!-- <el-input v-model="listQuery.couponNo" clearable class="filter-item" style="width: 200px;" placeholder="请输入优惠券号" /> -->
      <el-select v-model="listQuery.type" clearable style="width: 200px" class="filter-item" placeholder="请选择优惠券类型">
        <el-option v-for="type in typeOptions" :key="type.value" :label="type.label" :value="type.value" />
      </el-select>

      <el-select v-model="listQuery.voucherType" clearable style="width: 200px" class="filter-item" placeholder="请选择抵用类型">
        <el-option v-for="type in voucherTypeData" :key="type.value" :label="type.label" :value="type.value" />
      </el-select>

      <el-select v-model="listQuery.status" clearable style="width: 200px" class="filter-item" placeholder="请选择优惠券状态">
        <el-option v-for="type in statusOptions" :key="type.value" :label="type.label" :value="type.value" />
      </el-select>
      <el-select v-model="listQuery.channelId" filterable clearable style="width: 200px" class="filter-item" placeholder="择优惠券使用渠道">
        <el-option v-for="type in channels" :key="type.id" :label="type.name" :value="type.id" />
      </el-select>
      <el-select v-model="listQuery.isFraUsable" clearable style="width: 200px" class="filter-item" placeholder="请选择加盟商可用状态">
        <el-option  key="0" label="加盟商-不可用" value="0" />
        <el-option  key="1" label="加盟商-可用" value="1" />
      </el-select>

      <el-button v-permission="['GET /admin/coupon/list']" class="filter-item" type="primary" icon="el-icon-search"
        @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/coupon/create']" class="filter-item" type="primary" icon="el-icon-edit"
        @click="handleCreate">添加</el-button>
      <!-- <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button> -->
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <el-table-column align="center" label="优惠券ID" prop="id" sortable />

      <el-table-column align="center" label="优惠券名称" prop="name" />

      <el-table-column align="center" label="说明介绍" prop="desc" />

      <el-table-column align="center" label="标签" prop="tag" />

      <el-table-column align="center" label="最低消费" prop="min">
        <template slot-scope="scope">满{{ scope.row.min }}元可用</template>
      </el-table-column>

      <el-table-column align="center" label="满减金额" prop="discount">
        <template slot-scope="scope">
          <span v-if="scope.row.voucherType == 1">减免{{ scope.row.discount }}元</span>
          <span v-if="scope.row.voucherType == 2">折扣率{{ scope.row.discount }}%</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="每人限领" prop="limit">
        <template slot-scope="scope">{{ scope.row.limit != 0 ? scope.row.limit : "不限" }}</template>
      </el-table-column>

      <el-table-column align="center" label="商品使用范围" prop="goodsType">
        <template slot-scope="scope">{{ scope.row.goodsType | formatGoodsType }}</template>
      </el-table-column>

      <el-table-column align="center" label="优惠券类型" prop="type">
        <template slot-scope="scope">{{ scope.row.type | formatType }}</template>
      </el-table-column>
      <el-table-column align="center" label="使用渠道" prop="channelId">
        <template slot-scope="scope">{{ formateChannel(scope.row.channelId)   }}</template>
      </el-table-column>

      <el-table-column align="center" label="优惠券数量" prop="total">
        <template slot-scope="scope">{{ scope.row.total != 0 ? scope.row.total : "不限" }}</template>
      </el-table-column>

      <el-table-column align="center" label="加盟商可用" prop="isFraUsable">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isFraUsable" @change="fraUsableChange(scope.row)" />
        </template>
      </el-table-column>

      <el-table-column align="center" label="状态" prop="status">
        <template slot-scope="scope">{{ scope.row.status | formatStatus }}</template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['GET /admin/coupon/read']" type="primary" size="mini"
            @click="handleDetail(scope.row)">详情</el-button>
          <!-- <el-button v-permission="['POST /admin/coupon/update']" type="info" size="mini" @click="handleUpdate(scope.row)">编辑</el-button> -->
          <el-button v-permission="['POST /admin/coupon/delete']" type="danger" size="mini"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width='800px'>
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px"
        style="margin-left:20px;">
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="dataForm.name" />
        </el-form-item>
        <el-form-item label="说明介绍" prop="desc">
          <el-input v-model="dataForm.desc" placeholder="使用说明及介绍" />
        </el-form-item>
        <el-form-item label="海报图片" prop="posterImg">
          <el-upload :action="uploadPath" :show-file-list="false" :headers="headers" :on-success="uploadShareWxPicUrl"
            class="avatar-uploader" accept=".jpg,.jpeg,.png,.gif">
            <img v-if="dataForm.posterImg" :src="dataForm.posterImg" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
          <span class="info">二维码尺寸：160*160,位置：350*280</span>
        </el-form-item>
        <el-form-item label="标签" prop="tag">
          <el-input v-model="dataForm.tag" />
        </el-form-item>
        <el-form-item label="最低消费" prop="min">
          <el-input v-model="dataForm.min">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="每人限领" prop="limit">
              <el-input v-model="dataForm.limit">
                <template slot="append">张</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用渠道" prop="channelId">
              <el-select v-model="dataForm.channelId" style="width:100%">
                <el-option v-for="type in channels" :key="type.id" :label="type.name" :value="type.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="分发类型" prop="type">
              <el-select v-model="dataForm.type" style="width:100%">
                <el-option v-for="type in typeOptions" :key="type.value" :label="type.label" :value="type.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="抵用类型" prop="type">
              <el-select v-model="dataForm.voucherType" style="width:100%">
                <el-option v-for="type in voucherTypeData" :key="type.value" :label="type.label" :value="type.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item :label="dataForm.voucherType == 1 ? '满减金额' : '折扣率'" prop="discount">
          <el-input v-model="dataForm.discount">
            <template slot="append">元（或折扣率1-100%）</template>
          </el-input>
        </el-form-item>

        <el-form-item label="优惠券数量" prop="total">
          <el-input v-model="dataForm.total">
            <template slot="append">张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="有效期">
          <el-radio-group v-model="dataForm.timeType">
            <!-- <el-radio-button :label="0">领券相对天数</el-radio-button>
            <el-radio-button :label="1">指定绝对时间</el-radio-button> -->
            <el-radio-button :label="0">领券后有效时长</el-radio-button>
            <el-radio-button :label="1">券有效起止时间</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="dataForm.timeType === 0">
          <el-input v-model="dataForm.days">
            <template slot="append">天</template>
          </el-input>
        </el-form-item>
        <el-form-item v-show="dataForm.timeType === 1">
          <el-col :span="11">
            <el-date-picker v-model="dataForm.startTime" type="datetime" placeholder="选择日期"
              value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;" />
          </el-col>
          <el-col :span="2" class="line">至</el-col>
          <el-col :span="11">
            <el-date-picker v-model="dataForm.endTime" type="datetime" placeholder="选择日期"
              value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;" />
          </el-col>
        </el-form-item>
        <el-form-item label="商品限制范围">
          <el-radio-group v-model="dataForm.goodsType">
            <el-radio-button :label="0">全场通用</el-radio-button>
            <el-radio-button :label="1">指定分类</el-radio-button>
            <el-radio-button :label="2">指定商品</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="dataForm.goodsType === 1">
          <el-cascader :options="categoryList" expand-trigger="hover" style="width:100%" clearable
            @change="handleTypeChange" />
        </el-form-item>
        <el-form-item v-show="dataForm.goodsType === 2">
          <el-cascader v-model="dataForm.goodsId" :options="goodsList" expand-trigger="hover"
            :props="{ expandTrigger: 'hover', value: 'value', label: 'label', multiple: true }" style="width:100%" clearable
            @change="handleTypeChange" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus == 'create'" type="primary" @click="createData">确定</el-button>
        <!--<el-button v-else type="primary" @click="updateData">修改</el-button>-->
      </div>
    </el-dialog>

  </div>
</template>


<script>
import { listCoupon, createCoupon, updateCoupon, deleteCoupon, changeFraUsable } from "@/api/coupon";
import { allChannel } from "@/api/channel";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import { listGoods3 } from "@/api/goods";
import { createStorage, uploadPath } from "@/api/storage";
import { defaultCouponTypeOptions, ArrayToObject } from "@/api/enumUtils"
import { getToken } from "@/utils/auth";

 
const voucherTypeData = [
  {
    label: "立减券",
    value: 1,
  },
  {
    label: "折扣券",
    value: 2,
  },
];


const defaultStatusOptions = [
  {
    label: "正常",
    value: 0,
  },
  {
    label: "已过期",
    value: 1,
  },
  {
    label: "已下架",
    value: 2,
  },
];

export default {
  name: "Coupon",
  components: { Pagination },
  filters: {
    formatType(type) {
      for (let i = 0; i < defaultCouponTypeOptions.length; i++) {
        if (type === defaultCouponTypeOptions[i].value) {
          return defaultCouponTypeOptions[i].label
        }
      }
      return ''
    }, 
    formatGoodsType(goodsType) {
      if (goodsType === 0) {
        return "全场通用";
      } else if (goodsType === 1) {
        return "指定分类";
      } else if (goodsType === 2) {
        return "指定商品";
      }
    },
    formatStatus(status) {
      if (status === 0) {
        return "正常";
      } else if (status === 1) {
        return "已过期";
      } else {
        return "已下架";
      }
    },
  },
  data() {
    return {
      uploadPath: uploadPath,
      voucherTypeData: voucherTypeData,
      typeOptions: defaultCouponTypeOptions,
      statusOptions: Object.assign({}, defaultStatusOptions),
      defaultTypeOptions: ArrayToObject(defaultCouponTypeOptions),
      list: [],
      channels: [], //渠道
      goodsList: [], // 三级商品
      categoryList: [], // 商品分类
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
        type: undefined,
        status: undefined,
        voucherType: undefined,
        sort: "add_time",
        order: "desc",
      },
      dataForm: {
        id: undefined,
        name: undefined,
        desc: undefined,
        tag: undefined,
        total: 0,
        discount: 0,
        min: 0,
        limit: 1,
        type: 0,
        status: 0,
        goodsType: 0,
        goodsValue: [],
        timeType: 0,
        days: 0,
        startTime: null,
        endTime: null,
        goodsId: null, // 指定商品控件 绑定值
        goodsCate: null, // 指定分类
        voucherType: 1, //默认1立减券
        priceType: 0//结算类型
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "创建",
      },
      rules: {
        name: [
          { required: true, message: "优惠券标题不能为空", trigger: "blur" },
        ],
        min: [{ required: true, message: "最低消费不能为空", trigger: "blur" }],
        limit: [
          { required: true, message: "每人限领不能为空", trigger: "blur" },
        ],
        discount: [
          { required: true, message: "折扣或立减不能为空", trigger: "blur" },
        ],
      },
      downloadLoading: false,
    };
  },
  created() {
    allChannel().then((res) => {
      this.channels = res.data.data;
    });
    this.getList();
    console.info(this.typeOptions)
  },
  computed: {
    headers() {
      return {
        "X-Jz-Admin-Token": getToken(),
      };
    },
  },
  methods: {
    getList() {
      this.listLoading = true;
      listCoupon(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
      this.handleListGoods();
    }, // 三级商品分类
    handleListGoods() {
      listGoods3()
        .then((res) => {
          this.goodsList = res.data.data.goodsList;
          this.categoryList = res.data.data.categoryList;
        })
        .catch(() => { });
    },
    fraUsableChange(row) {
      changeFraUsable({ id: row.id, usable: row.isFraUsable }).then(res => {
        this.$notify.success({
          title: "成功",
          message: "状态设置成功",
        });
      })

    },
    handleTypeChange(value) {
      this.dataForm.goodsValue = []; //只允许一个
      if (value.length > 0) {
        if (this.dataForm.goodsType == "1") {
          this.dataForm.goodsId = [];
          this.dataForm.goodsValue.push(value[value.length - 1]);
        }
        else {
          this.dataForm.goodsId.forEach((item) => {
            this.dataForm.goodsValue.push(item[2]);
          });
        }
      }

      console.log(this.dataForm.goodsValue);
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        name: undefined,
        desc: undefined,
        tag: undefined,
        total: 0,
        discount: 0,
        min: 0,
        limit: 1,
        type: 0,
        status: 0,
        goodsType: 0,
        goodsValue: [],
        timeType: 0,
        days: 0,
        startTime: null,
        endTime: null,
        voucherType: 1,
      };
    },
    handleCreate() {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      if (this.dataForm.type == 2 && this.dataForm.total == 0) {
        //兑换券 必须设置优惠券生成数量
        this.$notify.error({
          title: "失败",
          message: "兑换券，优惠券数量必须大于0",
        });
        return;
      }

      if (this.dataForm.voucherType == 2) {
        //折扣券
        if (this.dataForm.discount > 100 || this.dataForm.discount < 1) {
          this.$notify.error({
            title: "失败",
            message: "折扣券，折扣率仅能在1到100之间",
          });
          return;
        }
      }

      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          createCoupon(this.dataForm)
            .then((response) => {
              this.list.unshift(response.data.data);
              this.dialogFormVisible = false;
              this.$notify.success({
                title: "成功",
                message: "创建优惠券成功",
              });
            })
            .catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response.data.errmsg,
              });
            });
        }
      });
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        if (this.dataForm.days === 0) {
          this.dataForm.daysType = 1;
        } else {
          this.dataForm.daysType = 0;
        }
        this.$refs["dataForm"].clearValidate();
      });
      // 指定商品控件赋值
      if (this.dataForm.goodsType === 2) {
        this.dataForm.goodsId =
          this.dataForm.goodsValue.length > 0
            ? this.dataForm.goodsValue[0]
            : null;
      } else if (this.dataForm.goodsType === 1) {
        this.dataForm.goodsCate =
          this.dataForm.goodsValue.length > 0
            ? this.dataForm.goodsValue[0]
            : null;
      }
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          updateCoupon(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v);
                  this.list.splice(index, 1, this.dataForm);
                  break;
                }
              }
              this.dialogFormVisible = false;
              this.$notify.success({
                title: "成功",
                message: "更新优惠券成功",
              });
            })
            .catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response.data.errmsg,
              });
            });
        }
      });
    },
    handleDelete(row) {
      deleteCoupon(row)
        .then((response) => {
          this.$notify.success({
            title: "成功",
            message: "删除优惠券成功",
          });
          const index = this.list.indexOf(row);
          this.list.splice(index, 1);
        })
        .catch((response) => {
          this.$notify.error({
            title: "失败",
            message: response.data.errmsg,
          });
        });
    },
    handleDetail(row) {
      this.$router.push({
        path: "/promotion/couponDetail",
        query: { id: row.id },
      });
    },

    uploadShareWxPicUrl: function (response) {
      this.dataForm.posterImg = response.data.url;
      this.$refs["dataForm"].validateField("posterImg");
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = [
          "优惠券ID",
          "名称",
          "内容",
          "标签",
          "最低消费",
          "减免金额",
          "每人限领",
          "优惠券数量",
        ];
        const filterVal = [
          "id",
          "name",
          "desc",
          "tag",
          "min",
          "discount",
          "limit",
          "total",
        ];
        excel.export_json_to_excel2(
          tHeader,
          this.list,
          filterVal,
          "优惠券信息"
        );
        this.downloadLoading = false;
      });
    },
    formateChannel(channelId){
      if(channelId==null||channelId==''){
        return;
      }
      let nm='';
      this.channels.forEach(f=>{
        if(f.id==channelId){
          nm=f.name;
        }
      })
      return nm;
    },
  },
};
</script>



<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}

.avatar {
  width: 80px;
  height: 80px;
  display: block;
}

.el-form--label-left .el-form-item__label {
  text-align: center;
}</style>