<template>
  <div class="app-containers">
    <div class="card-box" style="margin-bottom: 20px">
      <div class="top-hang">
        <div class="d-s">

          <el-input
            placeholder="请输入内容"
            v-model="queryParams.activeName"
            clearable
            width="150px"
          >
          </el-input>

          <el-select v-model="queryParams.status" clearable style="margin-left: 10px" placeholder="请选择状态">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </div>
        <div class="d-s">
          <el-button type="primary" icon="el-icon-search" @click="getlist">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          <el-button type="primary" icon="el-icon-search" @click="downloadTemplate()">下载模板</el-button>
          <el-button type="primary" @click="centerDialogVisible =! centerDialogVisible">新增礼品卡活动</el-button>

        </div>
      </div>
      <el-table
        border
        :data="tableData"
        style="width: 100%">
        <el-table-column
          label="序号"
          type="index"
        >
        </el-table-column>
        <el-table-column
          prop="activeNum"
          label="活动编号"
        >
        </el-table-column>
        <el-table-column
          prop="activeName"
          label="活动名称"
        >
        </el-table-column>
        <el-table-column
          prop="cardAmount"
          label="礼品卡面值"
        >
        </el-table-column>
        <el-table-column
          prop="sumNum"
          label="制卡数量"
        >
        </el-table-column>
        <el-table-column
          prop="sailNum"
          label="售出数量"
        >
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="有效期"
        >
          <template slot-scope="scope">
            {{ scope.row.effectiveTimeStart + '~' + scope.row.effectiveTimeEnd }}
          </template>
        </el-table-column>
        <el-table-column
          prop="pwdType"
          label="密码"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.pwdType  == 0">免密</span>
            <span v-if="scope.row.pwdType  == 1">加密</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.status  == 0">待上传</span>
            <span v-if="scope.row.status  == 1">待加密</span>
            <span v-if="scope.row.status  == 2">生效中</span>
          </template>
        </el-table-column>
<!--        <el-table-column-->
<!--          prop="createBy"-->
<!--          label="创建人"-->
<!--        >-->
<!--        </el-table-column>-->
        <el-table-column
          prop="address"
          label="操作">
          <template slot-scope="scope">
            <div style="display: flex;flex-wrap: wrap">
              <el-button
                type="text"
                v-if="scope.row.status == 0"
                @click="updateId(scope.row)"
              >修改
              </el-button>
              <el-button
                type="text"
                v-if="scope.row.status == 0"
                @click="uploadShow(scope.row)"
              >上传礼品卡数据
              </el-button>
              <el-button
                type="text"
                v-if="scope.row.status == 1"
                @click="jmData(scope.row.id)"
              >一键加密
              </el-button>
              <el-button
                type="text"
                v-if="scope.row.status == 2"
                @click="downData(scope.row.id)"
              >下载
              </el-button>
              <el-button
                type="text"
                v-if="scope.row.status ==2"
                @click="orderShow =! orderShow"
              >查看订单信息
              </el-button>
            </div>
          </template>
        </el-table-column>

      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="pageNo"
        :limit.sync="pageSize"
        @pagination="getlist"
      />
    </div>
    <el-drawer
      title="订单记录"
      :visible.sync="orderShow"
      size="55%"
      :before-close="handleClose"
      center>
      <div class="box-der">
        <div class="d-b">
          <div class="d-s">
            <el-input v-model="input" style="width: 200px;margin-right: 10px" placeholder="请输入订单号"></el-input>
            <el-select v-model="value" placeholder="请选择" style="width: 200px;margin-right: 10px">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-date-picker
              v-model="value1"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </div>
          <el-button type="primary" icon="el-icon-search">搜索</el-button>
        </div>
        <el-table
          :data="orderData"
          border
          style="width: 100%">
          <el-table-column
            label="序号"
            type="index"
          >
          </el-table-column>
          <el-table-column
            prop="date"
            label="订单号"
          >
          </el-table-column>
          <el-table-column
            prop="date"
            label="会员手机号"
          >
          </el-table-column>
          <el-table-column
            prop="date"
            label="礼品卡面值（元）">
          </el-table-column>
          <el-table-column
            prop="date"
            label="数量">
          </el-table-column>
          <el-table-column
            prop="date"
            label="礼品卡金额">
          </el-table-column>
          <el-table-column
            prop="date"
            label="实收金额">
          </el-table-column>
          <el-table-column
            prop="date"
            label="订单状态">
          </el-table-column>
          <el-table-column
            prop="date"
            label="订单完成时间">
          </el-table-column>
        </el-table>
      </div>
    </el-drawer>
    <el-dialog
      title="上传礼品卡数据"
      :visible.sync="uploadingShow"
      width="40%"
      @close="handleClose2"
    >
      <el-form :model="ruleForm2" :rules="rules2" ref="ruleForm2" label-width="100px" class="demo-ruleForm">

        <el-form-item label="活动编号" prop="activeNum">
          <el-input v-model="ruleForm2.activeNum"></el-input>
        </el-form-item>


        <el-form-item label="上传数据形式">
          <div class="d-s">
            <div class="icon-type" v-for="(item,index) in modalitylsit2" :key="index"
                 :class="{ 'acvtive' : index === tindex2 }" @click="Typeindex2(index)">
              <img src="../../../assets/images/wx.png" style="width: 20px;height: 20px" v-if="index != tindex2">
              <img src="../../../assets/images/xz.png" style="width: 20px;height: 20px" v-if="index == tindex2">
              {{ item }}
            </div>
          </div>
        </el-form-item>


        <el-form-item label="文件" prop="activeNum">
          <el-upload
            :action=uploadUrl
            ref="upload2"
            class="upload-demo"
            drag
            :auto-upload="false"
            :before-upload="beforeUpload"
            :on-success="handleSuccess"
            :on-error="handleError"
            :on-exceed="handleExceed"
            :file-list="fileList2"
            :limit="1"
            :on-change="handleChange"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">
      <span>上传文件必须符合模板格式，请下载
        <a @click="downloadTemplate" style="color:blue">导入模板</a>
      </span>
            </div>
          </el-upload>
          <el-button @click="uploadingShow = false">取消</el-button>
          <el-button type="primary" @click="submitUpload">导入</el-button>

        </el-form-item>


      </el-form>

    </el-dialog>
    <el-dialog
      title="新增/修改礼品卡活动"
      :visible.sync="centerDialogVisible"
      width="40%"
      @close="handleClose1"
    >
      <el-form ref="formName" :model="ruleForm" :rules="rules" :label-position="labelPosition" label-width="100px"
               class="demo-ruleForm">
        <el-form-item label="活动编号" prop="activeNum">
          <el-input v-model="ruleForm.activeNum"></el-input>
        </el-form-item>
        <el-form-item label="活动名称" prop="activeName">
          <el-input v-model="ruleForm.activeName"></el-input>
        </el-form-item>
        <el-form-item label="礼品卡面值" prop="cardAmount">
          <el-input placeholder="请输入内容" v-model="ruleForm.cardAmount">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="有效期" prop="value1">
          <el-date-picker
            v-model="ruleForm.value1"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="卡类型" prop="cardType">
          <el-select v-model="ruleForm.cardType" placeholder="请选择投放类型" style="width: 100%">
            <el-option v-for="dict in dict.type.card_gift_type" :key="dict.value" :label="dict.label"
                       :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="密码形式" prop="name">
          <div class="d-s">


            <el-radio-group v-model="ruleForm.pwdType">
              <el-radio :label="0">免密</el-radio>
              <el-radio :label="1">加密</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item label="礼品卡说明" prop="remark">
          <el-input type="textarea" v-model="ruleForm.remark"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
            <el-button @click="centerDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addBlock('formName')">创建</el-button>
          </span>
    </el-dialog>
    <el-dialog
      title="密码加密"
      :visible.sync="Encryption"
      width="30%"
    >
      <div class="d-b">
        <div class="d-s">
          <span style="margin-right: 15px">活动编号</span>
          <el-input v-model="ruleForm.number" style="width: 200px;margin-right: 10px" placeholder="请输入活动编号"></el-input>
        </div>
        <el-button type="primary">一键加密</el-button>
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        border=""
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          label="活动编号"
          width="120">
          <template slot-scope="scope">{{ scope.row.date }}</template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="卡号"
          width="120">
        </el-table-column>
        <el-table-column
          prop="address"
          label="密码"
          show-overflow-tooltip>
        </el-table-column>
        <el-table-column
          prop="address"
          label="加密后的密码"
          show-overflow-tooltip>
        </el-table-column>
      </el-table>

    </el-dialog>

  </div>
</template>

<script>
import {
  add,
  updateId,
  getList,
  getListtj,
  uploadFile,
  eitList,
  encryptData, exportCardInfo
} from "@/api/EventMarketing/giftBlock";
import {getToken} from "@/utils/auth";
import saveAs from 'file-saver';
import {exportExcelTankApi} from "@/api/oilConfig/oilTank";
import {exportExcelApi} from "@/api/convenienceStore/damage";

export default {
  name: 'index',
  dicts: ['card_gift_type'],
  data() {
    return {
      //http://localhost:81/dev-api/cardGiftActive
      uploadUrl: process.env.VUE_APP_BASE_API + ' /cardGiftActive/importCardInfo',
      Encryption: false,
      uploadingShow: false,
      oillist: [
        "不限",
        "自定义"
      ],
      modalitylsit: [
        "免密",
        "密码"
      ],
      modalitylsit2: [
        "新增",
        "覆盖新增"
      ],
      oilnumlist: [
        {
          value: '1',
          label: '#95'
        },
        {
          value: '2',
          label: '#92'
        },
      ],
      tindex: 0,
      tindex2: 0,
      jglist: [],
      onelist: [],
      twolist: [],
      threelist: [],
      orderShow: false,
      orderData: [{
        date: '2016-05-02',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1518 弄'
      },],
      headers: {
        'Access-Token': getToken(),
      },
      uploading: false,
      fileList: [],
      fileList2: [],
      labelPosition: 'left',
      queryParams: {
        //活动名称
        activeName: '',


        pageNo: 1,
        pageSize: 10
      },
      centerDialogVisible: false,
      input: '',
      total: 0,
      pageNo: 1,
      pageSize: 10,
      option: [
        {
          value: '0',
          label: '已激活'
        }, {
          value: '1',
          label: '未激活'
        },],
      options: [
        {
          value: '0',
          label: '待上传'
        }, {
          value: '1',
          label: '待加密'
        },
        {
          value: '2',
          label: '生效中'
        }

      ],
      value: '',
      tjdata: {},
      tableData: [
        {
          date: '2016-05-02',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄'
        }, {
          date: '2016-05-04',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1517 弄'
        }, {
          date: '2016-05-01',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1519 弄'
        }, {
          date: '2016-05-03',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1516 弄'
        }],
      ruleForm: {
        //活动编号
        activeNum: '',
        //活动名称
        activeName: '',
        //礼品卡面值
        cardAmount: '',
        //有效期
        value1: '',
        //卡类型
        cardType: '',
        //礼品卡说明
        remark: '',

      },
      ruleForm2: {},

      rules: {
        activeNum: [
          {required: true, message: '此为必填项', trigger: 'blur'},
        ],
        activeName: [
          {required: true, message: '此为必填项', trigger: 'blur'},
        ],
        cardAmount: [
          {required: true, message: '此为必填项', trigger: 'blur'},
        ],
        value1: [
          {required: true, message: '此为必填项', trigger: 'blur'},
        ],
        cardType: [
          {required: true, message: '此为必填项', trigger: 'change'},
        ],
        remark: [
          {required: true, message: '此为必填项', trigger: 'blur'},
        ],

      }

    }
  },
  mounted() {
    this.getlist()
    this.gettj()
  },

  methods: {
    downData(activeId){
      exportCardInfo(activeId).then(res=>{
        console.log("res",res)
        // this.downloadFile(res);
        const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

        this.$download.saveAs(blob,+'礼品卡数据.xLs')
      })
    },
    beforeUpload(file) {
      // 自定义上传前的逻辑
      return new Promise((resolve, reject) => {
        // 进行一些验证或其他操作
        console.log('Before Upload:', file);
        resolve(true); // 继续上传
      });
    },
    handleSuccess(response, file, fileList) {
      this.getlist()
      console.log('上传成功:', response);
      this.$message.success('上传成功！');
      this.uploadingShow = false;
    },
    handleError(error, file, fileList) {
      console.error('上传失败:', error);
      this.$message.error('上传失败！');
      this.uploadingShow = false;

    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择一个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    submitUpload() {
      if (this.fileList2.length > 0) {
        // 自定义上传
        this.customUpload(this.fileList2[0])

      } else {
        this.$message.warning('请选择一个文件上传！');
      }
    },

    customUpload(file) {
      const formData = new FormData();
      formData.append('file', file.raw); // 将文件添加到 FormData 对象

      uploadFile(formData, this.ruleForm2.activeNum, this.tindex2) // 调用封装好的上传方法
        .then(response => {
          this.handleSuccess(response.data, file, this.fileList2);
        })
        .catch(error => {
          this.handleError(error, file, this.fileList2);
        });


    },

    downloadTemplate() {
      const link = document.createElement('a');
      link.href = '/CardGiftActiveTemplate.xlsx'; // 相对于 public 目录下的路径
      link.download = 'CardGiftActiveTemplate.xlsx';
      link.click();
    },

    handleClose1() {
      // 重置表单验证状态
      this.$refs['formName'].resetFields();
      // 重置表单数据
      this.ruleForm = {};
    },

    handleClose2() {
       this.fileList2 = []
    },

    updateId(row) {

      this.centerDialogVisible = !this.centerDialogVisible
      this.ruleForm = row
      // 时间
      this.ruleForm.value1 = [row.effectiveTimeStart, row.effectiveTimeEnd]
      // 卡类型  确保下拉框选中
      this.ruleForm.cardType = row.cardType
    },
    jmData(activeId){
      encryptData(activeId).then(response => {
        this.$message.success('成功！');
        this.getlist()
      })
    },
    uploadShow(row) {
      this.uploadingShow = !this.uploadingShow
      //  将编号赋值
      this.ruleForm2.activeNum = row.activeName
    },
    Typeindex2(index) {
      this.tindex2 = index
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    handleChange(file, fileList) {
      // 文件变化时的处理逻辑
      console.log('文件变化:', file, fileList);
      this.fileList2 = fileList; // 更新 fileList
    },
    // 重置按钮操作
    resetQuery() {
      this.queryParams = {
        number: '',
        remark: '',
        activateStatus: null,
        status: '',
        pageNo: 1,
        pageSize: 10
      }
      this.getlist();
    },
    getlist() {

      this.queryParams.pageNo = this.pageNo
      this.queryParams.pageSize = this.pageSize
      getList(this.queryParams).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total;
      })
    },

    posteid(data) {
      eitList(data).then(res => {
        if (res.code == 200) {
          this.$message.success('操作成功！');
        } else {
          this.$message.error('修改失败请稍后再试');
        }
      })
    },
    gettj() {
      getListtj().then(res => {
        this.tjdata = res.data
      })
    },
    daking() {
      this.centerDialogVisible = true
      this.ruleForm = {
        activateStatus: '0',
        quantity: '1',
        cardAmount: '1',
        remark: ''
      }
    },
    addBlock(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {

          //密码形式 字段单独添加 因为涉及到图片样式
          this.ruleForm.pwdType = this.tindex
          //开始时间 结束时间分割
          this.ruleForm.effectiveTimeStart = this.ruleForm.value1[0]
          this.ruleForm.effectiveTimeEnd = this.ruleForm.value1[1]


          //通过判断 表单数据是否包含id 区分新增修改
          if (this.ruleForm.id) {

            updateId(this.ruleForm).then(
              (res) => {
                if (res.code == 200) {
                  this.$message.success('修改成功');
                } else {
                  this.$message.error('修改失败');
                }
              }
            )

          } else {

            add(this.ruleForm).then(res => {
              if (res.code == 200) {
                this.$message.success('添加成功');
              } else {
                this.$message.error('添加失败');
              }
            })

          }


          //关闭弹窗
          this.centerDialogVisible = false
          //清除表单数据
          this.$refs[formName].resetFields();
          //初始化查询
          this.getlist()
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    }
  }
}
</script>

<style scoped lang="scss">
.tj {
  width: 100%;
  display: flex;
  justify-content: space-between;

}

.box-der {
  box-sizing: border-box;
  padding: 15px;
}

.kar {
  width: 100%;
  background: #FFFFFF;
  margin-bottom: 10px;

}

.d-b {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 10px;
}

.one-size {
  font-size: 20px;
  font-weight: bold;
  color: #000;
}

.two-size {
  font-size: 20px;
  font-weight: bold;
  color: #78b0fb;
}

.three-size {
  font-size: 20px;
  font-weight: bold;
  color: #f73f3f;
}

.ds {
  width: 100%;
  display: flex;
  align-items: center;
  background: #f4f4f4;
  border-radius: 6px;
  margin-bottom: 15px;
  box-sizing: border-box;
  padding: 15px 5px;
}

.tj-text {
  font-size: 18px;
  font-weight: bold;
}

.tj-num {
  margin: 5px auto;
  //font-size: 28px;
  color: #666;
  text-align: center;
}

.tj-siez {
  margin: 5px auto;
  color: #909399;
  font-size: 14px;
  text-align: center;
}

.top-hang {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
}

.d-s {
  display: flex;
  align-items: center;
}

.butoon {
  box-sizing: border-box;
  padding: 6px 10px;
  border: 1px solid #fe8c4a;
  border-radius: 6px;
  font-size: 16px;
  margin-left: 15px;
}

.sshi {
  width: 33%;
  background: #FFFFFF;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  box-sizing: border-box;
  padding: 15px;
  border-radius: 6px;
  //background: #f9f9f9;
}

.tjaocuo {
  width: 100%;
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
}

.title_ {
  width: 100%;
  display: flex;
  align-items: center;
  font-size: 20px;
  font-weight: bold;
  justify-content: center;
  margin-bottom: 20px;
}

.card-box {
  width: 100%;
  background: #fff;
  box-sizing: border-box;
  padding: 15px;
  border-radius: 10px;
}

.icon-type {
  display: flex;
  align-items: center;
  font-weight: 400;
  font-size: 14px;
  color: #999999;
  margin-right: 20px;
  cursor: pointer;
}

.acvtive {
  color: #FF770F !important;
}
</style>
