<template>
  <div class="m-right-block fr mh576">
    <div class="right-block-bd ng-scope" ui-view="myStudyContent" style="position: relative;">
      <div class="panel-tit clear">
        <p class="fl">推荐课程</p>
        <ul class="fr tips-intro" style="color:royalblue" @mouseover="showTip=true" @mouseleave="showTip=false">
          <li class="fs15 tit" style="margin-right: 20px;">
            <i class="p-ico questiong-ico" style="margin-right: 0px;" />  温馨提醒
          </li>
        </ul>

        <div class="fr tip-card" v-show="showTip">
          <div class="p20">
            <h3>温馨提醒：</h3>
            <h2 style="margin: 8px; 0 16px 0px;">一、福建省内可报</h2>
            <h4 style="margin: 8px;">1.施工现场专业人员</h4>
            <h4 style="margin: 8px;">2.20周岁以上，且男性小于60周岁，女性小于55周岁。</h4>

            <h2 style="margin:8px 0 16px 0px;">二、宁德内可报：</h2>
            <h4 style="margin: 8px;">1.安全生产管理人员</h4>
            <h4 style="margin: 8px;">2.建筑施工特种作业人员</h4>
            <h4 style="margin: 8px;">3.企业安全生产培训</h4>
          </div>
        </div>
      </div>

      <el-row class="pt-line mt20">
        <el-col :span="4" :xs="12">
          <el-button :class="{type_active : type==''}" class="type_item" type="text" @click="type=''">所有</el-button>
        </el-col>

        <el-col :span="item.span" :xs="12" v-for="item in typeList" :key="item.id" v-if="item.isOpen && !item.link">
          <el-button :class="{type_active:item.name==type }" class="type_item" type="text"
            @click="type=item.name">{{item.name}}</el-button>
        </el-col>


      </el-row>


      <ul class="pt-line mt20" v-if="ndList.length>1">
        <li style="float: left;font-size: 16px;margin: 4px;padding: 4px;">
          <span>课程年度:</span>
        </li>
        <li style="float: left;">
          <span :class="{type_active:nd==''}" class="nav-btn-years" @click="nd=''">所有</span>
        </li>
        <li v-for="item in ndList" style="float: left;">
          <span :class="{type_active:item==nd }" class="nav-btn-years" @click="nd=item">{{item}} </span>
        </li>
        <li style="float: left;">
          <input type="text" style="line-height: 1;padding: 10px" v-model="filterName"
            class="ui-ipt ng-pristine ng-valid filterName" placeholder="输入名字查找">
        </li>
      </ul>

      <ul class="m-course-list clear mt10 classlist">
        <li v-for="(item,index) in list.slice(page*size-size, page*size)" :key="item.course_id"
          class="pt-sola mt20 pb10">
          <div>
            <span v-if="item.isFinish==1" class="p-ico2 ico-passed"></span>
            <div class="img">
              <img :src="item.tb">
              <div class="year-label">
                <span v-if="item.is_pay==0 && item.buyImg =='' && item.payNo == ''">
                  还未购买
                </span>
                <span v-else-if="item.is_pay == 2 && item.is_import ==9">
                  预购买中
                </span>
                <span v-else-if="item.is_pay==0" style="background-color: orange;">
                  等待审核
                </span>
                <span v-else-if="item.is_pay==2" style="background-color: #78335F;">申请驳回</span>
                <span v-else-if="!item.is_pass"
                  style="background-color: blue;padding: 2px;border-radius: 2px;">在学习中</span>
                <span v-else style="background-color: green;padding: 2px;border-radius: 2px;">已经完成</span>
              </div>

              <div class="hover-block">
                <div class="mask-bg"></div>
                <el-button @click="gotoPlay(item.course_id)" v-if="item.is_pay==1"
                  class="ui-btn btn-blue">进入学习</el-button>
                <el-button @click="goPay(item)" v-else-if="item.is_pay==2 || !!item.buyImg"
                  class="ui-btn btn-w">补充材料</el-button>
                <el-button @click="goPay(item)" v-else-if="item.payErr" class="ui-btn btn-gr">申请购买</el-button>
                <el-button @click="goPay(item)" v-else class="ui-btn btn-o">购买课程</el-button>

              </div>
            </div>

            <div class="tit"><a>{{item.displayName || item.name}}</a>
            </div>

            <div class="info">
              <p class="w1"><span class="p-ico c1"></span> {{item.type}} </p>
              <p class="w2"><span class="p-ico c2"></span>{{item.nd||'2020'}}</p>
              <p class="w1">
                <span class="p-ico c5"></span> ￥{{item.fee/100}}元
              </p>
              <p class="w2">
                <span class="p-ico c3"></span> {{item.xs/10}}学时
              </p>
            </div>
          </div>
        </li>
      </ul>
      <div v-if="list.length==0" class="tc mt20 red">
        <span style="color: red;padding:40px;font-size: 26px;">已经最后一页了</span>
      </div>

      <el-pagination class="m-pages" @current-change="(page)=>{this.page=page}" :current-page="page" :page-size="size"
        layout="total, prev, pager, next" :total="list.length">
      </el-pagination>

    </div>

    <el-dialog title="申请开通课程" :visible.sync="buyCourseDialog" width="550px" top="100px" align="left">
      <template v-if="!showPay">
        <el-form label-width="100px" :inline="false" :model="buyForm" :rules="rules"
          ref="elForm">
          <el-form-item label="账户余额" prop="balance" >
            <p style="margin-left: 20px;font-size: 16px;">
              <span v-if="userInfo.balance>=buyForm.fee" style="color: green;"> ￥{{userInfo.balance/100}}元</span>
              <span v-else style="color: red;"> ￥{{userInfo.balance/100}}元</span>
            </p>
          </el-form-item>

          <el-form-item label="报考岗位" prop="courseName">
            <el-input type="text" placeholder="报考岗位" v-model="buyForm.courseName+'-'+buyForm.nd"
            style="width: 360px;" />
          </el-form-item>


          <el-form-item label="证书编号" prop="rzCode">
            <el-input v-model="buyForm.rzCode" type="text" style="width: 360px;">
              <template #suffix>
                <el-button @click="openShowAllRzcodeDialog" type="text" style="margin-right: 10px;">修改</el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-divider></el-divider>
          <h3 class="tc" style="margin-bottom: 16px;">发票信息</h3>
          <el-form-item label="是否需要开票">
            <el-radio-group v-model="buyForm.needInvoice">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="buyForm.needInvoice">
            <el-form-item label="开票类型">
              <el-radio-group v-model="buyForm.invoiceType">
                <el-radio label="personal">个人</el-radio>
                <el-radio label="enterprise">企业</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="发票抬头" prop="title">
              <el-input v-model="buyForm.title" :placeholder="buyForm.invoiceType === 'enterprise'?'请输入单位名称':'请输入真实名字'" style="width: 360px;"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="buyForm.phone" placeholder="请输入手机号码" style="width: 360px;"></el-input>
            </el-form-item>
            <el-form-item label="邮箱地址" prop="email">
              <el-input v-model="buyForm.email" placeholder="请输入邮箱地址" style="width: 360px;"></el-input>
            </el-form-item>
          </template>

          <el-divider></el-divider>
          <h2 class="tc"> 本课程费用: <strong style="color: red;"> {{buyForm.fee/100}} 元 </strong> </h2>

          <el-form-item label-width="0" style="margin: 30px auto;text-align: center;">
            <el-button @click="cancelBuyCourse">取 消</el-button>
            <el-button @click="generatePayQrcode" type="primary">提交订单</el-button>
            <el-button v-if="userInfo.balance >= buyForm.fee" @click="doAccountPay" type="success">余额付款</el-button>
          </el-form-item>

        </el-form>
      </template>

      <template v-if="showPay">
        <h2 class="tc"> 本课程费用: <strong style="color: red;"> {{buyForm.fee/100}} 元 </strong> </h2>
        <div style="width: 300px; margin: 20px auto;">
          <img :src="wxPayUrl" width="300px" @click="showImg(wxPayUrl)">
        </div>
        <p class="tc">请使用微信扫码支付</p>
        <el-row class="tc fc">
          <el-button @click="cancelBuyCourse">关 闭</el-button>
        </el-row>
      </template>


    </el-dialog>


    <el-dialog append-to-body close-on-click-modal :visible.sync="showImgDialog" style="margin-top: 0px;"
      :width="width">
      <img :src="imgUrl" @load="onLoad" alt="" />
    </el-dialog>

    <el-dialog append-to-body close-on-click-modal :visible.sync="showAllRzcodeDialog" width="1024">
      <el-table v-if="buyForm.list.length>0" :data="buyForm.list" border>
        <el-table-column label="证书编号" prop="certificateNum" align="center" />
        <el-table-column label="岗位名称" prop="positionName" align="center" />
        <el-table-column label="证书状态" prop="certificateStatus" align="center" />
        <el-table-column label="发证机关" prop="certificateOrgan" align="center" />
        <el-table-column label="发证时间" prop="startTime" align="center" />
        <el-table-column label="选择" prop="reviewTime" align="center">
          <template slot-scope="{row}">
            <el-button @click="selectRzcode(row)" type="primary">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
  import {
    httpServer
  } from "@/components/httpServer/httpServer.js";

  import {
    MessageBox
  } from "element-ui";
  import {
    parseTime
  } from "@/utils";
  import DoUpload from '@/components/upload/index.vue'
  import exampleImg from '@/assets/template.png'
  import {curDatetime} from '@/utils/date.js'

  import {
    mapGetters,
    mapActions
  } from "vuex";

  export default {
    name: "Index",
    data() {
      return {
        page: 1,
        size: 6,
        total: 0,
        stage: 0,
        isCompanyPay: 0,
        showTip: false,
        width: "",
        type: '',
        filterName: '',
        list: [],
        nd: new Date().getFullYear() + '',
        ndList: [],
        allList: [],
        isCommitment: "",
        buyCourseDialog: false,
        showExample: false,
        showImgDialog: false,
        showAllRzcodeDialog: false,
        showPay: false,
        buyForm: {
          payType:'wx',
          rzCode: '',
          email: '',
          title: '',
          phone: '',
          courseName: '',
          list: [],
          fee: 0,
          courseId: '',
          needInvoice: 0,
          invoiceType: 'personal'
        },
        imgUrl: '',
        qrcodeUrl: "",
        wxPayUrl:"",
        aliPayUrl:"",
        outTradeNo: "",
        courseFee: 0,
        title: '',
        timer: null,
        tickCount: 0,
        listLoading: false,
        media: {},
        commitmentDialog: false,
        exampleImg: exampleImg,
        rules: {
          rzCode: [{
            required: true,
            message: '请输入证书编号'
          }],
          payNo: [{
            required: true,
            message: '请输入订单编号后六位'
          }],
          title: [{
            required: true,
            message: '抬头必须填写'
          }],
          email: [{
              required: true,
              message: '请输入有效邮箱'
            },
            {
              type: 'string',
              message: '邮箱格式不正确',
              trigger: 'blur',
              transform(value) {
                value = value.trim();
                if (!/^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(value)) {
                  return true
                } else {}
              }
            }
          ],
          company: [{
            required: true,
            message: '请输入单位名称'
          }],
          phone: [{
            required: true,
            message: '请输入手机号码'
          }, {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号码格式不正确',
            trigger: 'blur'
          }],
          courseName: [{
            required: true,
            message: '请输入报考岗位'
          }]
        },
        errorImg: 'this.src="' + require('../../../assets/images/no-data_hash5abcd2ef62.png') + '"'
      };
    },
    computed: {
      ...mapGetters("user", ["typeList", "userInfo"])
    },
    components: {
      DoUpload
    },
    filters: {
      dateFilter(val) {
        return parseTime(val, '{y}-{m}-{d}')
      }
    },
    watch: {
      type(val) {
        this.page = 1
        this.nd = new Date().getFullYear() + ''
        this.filterData()
      },
      nd(val) {
        this.filterData()
      },
      filterName() {
        this.page = 1
        this.filterData()
      }
    },
    beforeMount() {
      this.type = this.$route.query.type || ''
      this.getData();
    },

    beforeDestroy() {
      if (this.timer) window.clearInterval(this.timer);
    },
    methods: {
      showImg(url) {
        if (!url) return;
        this.imgUrl = url;
        this.showImgDialog = true;
      },
      closeDialog() {
        if (this.timer) window.clearInterval(this.timer);
      },
      onLoad(e) {
        const img = e.target;
        let width = 0;
        if (img.fileSize > 0 || (img.width > 1 && img.height > 1)) {
          width = img.width + 40;
        }
        this.width = width + "px";
      },
      initTimer() {
        if (this.timer) window.clearInterval(this.timer);
        this.tickCount = 0;
        this.timer = window.setInterval(() => {
          this.tickCount++;
          this.tickTimer();
        }, 3000);
      },
      tickTimer() {
        if (this.tickCount > 100) {
          if (this.timer) window.clearInterval(this.timer);
          this.$message.warning("支付超时，请重新支付");
          this.buyCourseDialog = false;
          return;
        }
        let outTradeNo = this.outTradeNo;
        httpServer("weixin.isPayOk", { outTradeNo }).then((res) => {
          if (res.code == 200 && !!res.data) {
            if (this.timer) window.clearInterval(this.timer);
            this.$message.successMsg("支付成功", 2);
            this.buyCourseDialog = false;
            this.getData();
          }
        });
      },
      doAccountPay(){
        let param = Object.assign({}, this.buyForm);
        httpServer("weixin.doAccountPay", {courseId}).then((res) => {
          if (res.code != 200) return;
          this.$message.successMsg("支付成功", 2);
          this.buyCourseDialog = false;
          this.getData();
        });
      },
      generatePayQrcode() {
        console.log('generatePayQrcode')
        let payType = this.buyForm.payType;
        let apiName = payType === 'wx' ? "weixin.DoWxpay" : "weixin.DoaliPay";
        let {
          courseId,
          courseName,
          title,
          email,
          phone,
          needInvoice,
          invoiceType
        } = this.buyForm;
        let param = {
          courseId,
          title,
          phone,
          email,
          needInvoice,
          invoiceType
        };
        httpServer(apiName, param).then((res) => {
          if (res.code != 200) return;
          let { outTradeNo, showUrl } = res.data;
          this.outTradeNo = outTradeNo;
          if (payType === 'wx') {
            this.wxPayUrl = showUrl;
          } else {
            this.aliPayUrl = showUrl;
          }
          this.showPay = true
          this.initTimer();

        });
      },
      getData() {
        let param = {
          size: 1000,
          trainType: 2,
          from: 0
        }
        httpServer("course.getcoursemarket", param).then((res) => {
          if (res.code == 200) {
            this.allList = res.data.list;
            this.filterData()
          }
        });
      },
      filterData() {
        let nd = this.nd || '';
        let filterName = this.filterName || '';
        let type = this.type || ''
        this.ndList = [];
        this.list = [];
        for (let i in this.allList) {
          let item = this.allList[i];
          if (type != '' && item.type != type) continue;
          if (this.ndList.indexOf(item.nd) == -1) {
            this.ndList.push(item.nd);
          }
          if (filterName!='' && item.name.indexOf(filterName) == -1) continue;
          if (nd != '' && item.nd != nd) continue;
          this.list.push(item)
        }
      },
      cancelBuyCourse() {
        if (this.timer) window.clearInterval(this.timer);
        this.$refs["elForm"] && this.$refs["elForm"].resetFields();
        this.buyCourseDialog = false
        this.showPay = false;
      },
      openShowAllRzcodeDialog() {
        this.showAllRzcodeDialog = true;
      },
      selectRzcode(row) {
        this.buyForm.rzCode = row.certificateNum;
        this.showAllRzcodeDialog = false;
      },
      gotoDetail(courseId) {
        this.$router.push(`/main/course/${courseId}`);
      },
      goPay(item) {
        this.showPay = false;
        this.buyForm = Object.assign(this.buyForm, item)
        this.buyForm.phone = this.userInfo.phone;
        this.buyForm.temp = item;
        this.buyForm.courseName = item.name;
        this.buyForm.courseId = item.course_id;
        this.buyForm.fee = item.fee;
        // 检查
        httpServer("weixin.docheckpay", {
          courseId: item.course_id
        }).then((res) => {
          if (res.code != 200) return;
          Object.assign(this.buyForm, res.data);
          this.buyCourseDialog = true;
        });
      },
      gotoPlay(item) {
        let courseId = item.courseId;
        if( curDatetime() < item.startDate){
          this.$message.warning("还未到学习时间");
          return
        }
        this.$router.push({name:'play', params:{courseId}})
      },
      handleCurrentChange(page) {
        this.page = page;
        this.filterData()
      }
    },
  };
</script>
<style>
  @import "../../../assets/css/content.css";
  @import "../../../assets/css/course.css";
  @import url("./index.css");

  .buyForm-title {
    width: 90px;
    padding: 2px;
    text-align: center;
  }

  .commitment-header {
    font-size: 16px;
    text-align: left;
  }

  .commitment {
    text-indent: 30px;
    margin-top: 20px;
    font-size: 16px;
    line-height: 200%;
  }

  .commitment-footer {
    margin-top: 30px;
    text-indent: 50px;
    font-size: 16px;
    text-align: left;
  }

  .commitment-content {
    font-size: 16px;
  }

  .tip-card {
    border-radius: 20px;
    font-size: 14px;
    float: right;
    width: 420px;
    right: 20px;
    position: absolute;
    top: 50px;
    color: white;
    background-color: #7fbae4;
    z-index: 1000;
  }

  .tips-intro {
    color: #468cf2;
    cursor: pointer;
    position: relative;
  }
</style>
