<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">
            <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>
            <h5 style="margin: 8px;">1、安管人员：</h5>
            <h5 style="margin-left: 16px;">①企业主要负责人（A证）：年龄18周岁以上，分管安全的技术负责人、安全总监到60岁，法定代表人没有年龄限制。</h5>
            <h5 style="margin-left: 16px;">②项目负责人（B证）：年龄18周岁以上，65周岁以下。</h5>
            <h5 style="margin-left: 16px;">③安全生产管理人员（C证）：年龄18周岁以上，60周岁以下。</h5>
            <h4 style="margin: 8px;">2、特种作业人员：年龄18周岁以上，男性55周岁以下，女性50周岁以下。</h4>
            <h4 style="margin: 8px;">3、八大员：年龄20周岁以上，60周岁以下。</h4>

            <h2 style="margin:8px 0 16px 0px;">二、执业注册人员：</h2>
            <h4 style="margin: 8px;">1、注册建造师（一级、二级）、注册监理工程师：年龄65周岁以下；</h4>
            <h4 style="margin: 8px;">2、其他执业资格注册证件无年龄要求。</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="4" :xs="12" v-for="item in typeList"  :key="item.id" v-if="item.isOpen && item.isNew==1">
          <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>

      <div class="mt10" v-if="type=='施工现场专业人员'">
        <p style="color: red;font-size: 16px;">
          报名对象为：2020年度及以后由培训单位核发的和2021年度换发的“电子培训合格证”且每年度需参加继续教育人员
        </p>
        <p style="color: red;font-size: 16px;">
          注意：继续教育学员请先下载
          <a style="color: blue;cursor: hand;" href="https://sm.hqedust.com/cdn/%E7%BB%A7%E7%BB%AD%E6%95%99%E8%82%B2%E5%A7%94%E6%89%98%E5%9F%B9%E8%AE%AD%E3%80%81%E6%89%BF%E8%AF%BA%E5%87%BD.doc">
            《继续教育委托培训、承诺函》
          </a>
            ，填写并加盖单位公章后，在申请开通课程界面上传扫描件、并缴费
        </p>
      </div>

      <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 ng-binding">
                <span v-if="item.is_pay==0 && item.buyImg =='' && item.payNo == ''">
                  还未购买
                </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">进入学习</el-button>

                <el-button @click="goPay(item)" v-else-if="item.is_pay==2 || !!item.buyImg" class="ui-btn btn-o">补充材料</el-button>
                <el-button @click="goPay(item)" v-else class="ui-btn btn-o">购买课程</el-button>
              </div>
            </div>

            <div class="tit"><a>{{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>

      <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 class="fc tc" :visible.sync="loginDialog" :close-on-click-modal="false" width="500px" @close="loginDialog=false">
      <div class="login-dialog m-login">
        <un-login @login="login"></un-login>
      </div>
    </el-dialog>


    <el-dialog title="申请开通课程"  :visible.sync="buyCourseDialog"
    width="800px" top="20px" align="center">
      <el-form label-width="80px" label-position="right" :inline="true" :model="buyForm" status-icon :rules="rules" ref="elForm">
        <el-row align="left">
          <el-col :lg="12" class="pl20 pr20">
            <el-form-item lable="报考岗位" prop="courseName">
              <label slot="label">报考岗位</label>
              <el-input v-model="buyForm.courseName" type="text" placeholder="报考岗位" style="width: 220px;"></el-input>
            </el-form-item>

          </el-col>

          <el-col :lg="12" class="pl20 pr20">
            <el-form-item lable="证书编号" prop="rzCode">
              <label slot="label">证书编号</label>
              <el-input v-model="buyForm.rzCode" type="text" placeholder="证书编号" style="width: 220px;"></el-input>
            </el-form-item>
          </el-col>

<!--          <el-row>
            <span style="color: red;padding:10px"> 请认真核实报考岗位与证书编号，本课程不支持退款</span>
          </el-row> -->

          <el-col :lg="12" class="pl20 pr20">
            <el-form-item lable="邮箱地址" prop="email">
              <label slot="label">邮箱地址</label>
              <el-input v-model="buyForm.email" type="textarea" placeholder="邮箱地址" style="width: 220px;"></el-input>
            </el-form-item>
          </el-col>


          <el-col :span="12" class="pl20 pr20">
            <el-form-item lable="订单号" prop="payNo">
              <label slot="label">订单编号</label>
              <el-input v-model="buyForm.payNo" placeholder="输入订单编号后6位" style="width: 220px;" :minlength="6" :maxlength="6" show-word-limit ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
         <el-row>
           <el-col :span="12" class="pl20 pr20">
             <el-form-item lable="工作单位" prop="company">
               <label slot="label">工作单位</label>
               <el-input v-model="buyForm.company" type="textarea" placeholder="工作单位" style="width: 220px;"></el-input>
             </el-form-item>
           </el-col>
          <el-col :span="12" class="pl20 pr20">
            <el-form-item lable="备注信息" prop="marks">
              <label slot="label">备注信息</label>
              <el-input v-model="buyForm.marks" type="textarea" placeholder="姓名+工种名称，例：张三+土建施工员" style="width: 220px;"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="type=='施工现场专业人员'">
            <div style="width: 700px;margin: 0 auto;text-align: left;color: red;">
              提示：八大员继续教育承诺函企业名称应与个人报名系统企业名称一致，如已变更单位的，
            请先在个人系统帐号设置进入额外信息栏进行修改工作单位与报名承诺函工作单位相符后方可上传承诺函确认
            </div>
           <img :src="buyForm.buyImg" :onerror="errorImg" style="width: 160px;text-align: center;">
           <do-upload @onFinish="(url)=>{buyForm.buyImg=url}" placeholder="上传承诺书" width="160px"> </do-upload>
        </el-row>


        <el-row>
          <h2 class="tc"> 本课程费用: <strong style="color: red;"> {{buyForm.fee/100}} 元 </strong> </h2>
          <div style="width: 300px; margin: 0px auto;">
            <img src="/static/images/wxpay.jpg"   width="300px" @click="showImg(buyForm.buyImg)">
          </div>
        </el-row>

         <el-row class="tc fc">
          <el-form-item >
            <el-button @click="cancelBuyCourse">取 消</el-button>
            <el-button @click="buyCourse" type="primary">确 定</el-button>
          </el-form-item>
        </el-row>

      </el-form>

    </el-dialog>



    <el-dialog :title="promiseType[promise.showType]" class="fc tc" :visible.sync="commitmentDialog">
        <div>
          <div>
            <div class="commitment-header"> {{promise.title}} </div>
            <div class="tl commitment">
                {{promise.content}}
            </div>
            <div class="commitment-footer">
              {{promise.footer}}
            </div>
          </div>

          <div class="tl commitment-content mt20" v-if="promise.showType==2">
            <el-radio-group v-model="isCommitment">
              <el-row class="mt10">
                <el-radio :label="true">本人作出上述承诺</el-radio>
              </el-row>
              <el-row class="mt10">
                <el-radio :label="false">本人不作出上述承诺</el-radio>
              </el-row>
            </el-radio-group>
          </div>

          <span slot="footer" class="dialog-footer" v-if="promise.showType==2">
            <el-button @click="commitmentDialog = false">取 消</el-button>
            <el-button type="primary" :disabled="isCommitment?false:true" @click="buyCourseDialog=true">确 定</el-button>
          </span>

          <div slot="footer" class="dialog-footer mt20" v-else>
            <el-button @click="commitmentDialog = false">取 消</el-button>
            <el-button type="primary"  @click="buyCourseDialog=true">继续购买</el-button>
          </div>
        </div>
    </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>
  </div>
</template>

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

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


  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: '',
        list: [],
        promiseType:{1:'温馨提示', 2:'承诺书',  3:'委 托 书'},
        nd: new Date().getFullYear()+'',
        filterName: '',
        ndList:[],
        allList:[],
        typeInfo:{},
        isCommitment: "",
        buyCourseDialog: false,
        showExample: false,
        showImgDialog: false,
        buyForm: {
          marks: '',
          rzCode: '',
          payNo:'',
          email:'',
          company:'',
          buyImg:'',
          name:'',
          courseName: ''
        },
        promise,
        imgUrl: '',
        qrcodeUrl: "",
        outTradeNo: "",
        courseFee: 0,
        title: '',
        timer: null,
        tickCount: 0,
        listLoading: false,
        loginDialog: false,
        isLoginOk: false,
        media: {},
        commitmentDialog: false,
        exampleImg: exampleImg,
        rules: {
          rzCode: [{
            required: true,
            message: '请输入证书编号'
          }],
          payNo:[
            {
              required: true,
              message: '请输入订单编号后六位'
            }
          ],
          marks:[
            {
              required: true,
              message: '请输入备注信息'
            }
          ],
          email: [{
              required: true,
              message: '请输入有效邮箱'
            },
            {
              type: 'string',
              message: '邮箱格式不正确',
              trigger: 'blur',
              transform(value) {
                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: '请输入所在企业'
          }],
          courseName: [{
            required: true,
            message: '请输入报考岗位'
          }]
        },
        errorImg: 'this.src="' + require('../../../assets/images/no-data_hash5abcd2ef62.png') + '"'
      };
    },
    computed: {
      ...mapGetters("user", ["typeList", "userInfo", "promiseList"])
    },
    components: {
      unLogin,
      DoUpload
    },
    filters: {
      dateFilter(val) {
        return parseTime(val, '{y}-{m}-{d}')
      }
    },
    watch: {
      type(val) {
        this.page = 1
        this.nd = new Date().getFullYear()+''
        this.filterData()
      },
      nd(){
        this.filterData()
      },
      filterName(){
        this.page = 1
        this.filterData()
      },
      isCommitment(val) {
        console.log(val)
      }
    },
    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";
      },
      getData() {
        let param = {
          size: 1000,
          trainType: 1,
          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(){
        this.$refs["elForm"].resetFields();
        this.buyCourseDialog=false
      },
      buyCourse() {
        this.$refs["elForm"].validate((valid) => {
          if (!valid) return;
          let { marks, company, payNo, course_id, courseName, rzCode, name,  email, buyImg} = this.buyForm;
          if (courseName != name) {
            this.$message.errorMsg("报考岗位有误", 1)
            return;
          }
          let param = { marks, payNo, company,courseId: course_id, courseName,rzCode,email,buyImg }
          httpServer("course.buyCourse", param).then((res) => {
            if (res.code == 200) {
              this.$message.successMsg("申请购买成功", 1);
              this.buyForm.temp.marks = this.buyForm.marks
              Object.assign( this.buyForm.temp, param);
              this.$refs["elForm"].resetFields();
              this.buyForm.temp.is_pay = 0
              this.buyCourseDialog = false
            }
          });
        })
      },
      gotoDetail(courseId) {
        this.$router.push(`/main/course/${courseId}`);
      },
      uploadBuyImg(url) {
        this.buyForm.buyImg = url;
      },
      matchPromise( row ){
        let {name,type} = row;
        let isMatch = false
        for( let i in this.promiseList){
          let item = this.promiseList[i];
          if( name == item.type || item.type == type ){
            this.promise = Object.assign( this.promise, item);
            console.log("promise", this.promise);
            isMatch = true
          } else if( !isMatch && item.type == '默认类型'){
            this.promise = Object.assign( this.promise, item);
          }
        }
      },
      matchType(type) {
        for (let i in this.typeList) {
          let item = this.typeList[i];
          if(item.name == type) {
            this.typeInfo = Object.assign(this.typeInfo, item);
            return;
          }
        }
      },
      goPay( item ) {
        this.buyForm = Object.assign(this.buyForm, item)
        this.buyForm.company = this.userInfo.company;
        this.buyForm.temp = item;
        this.buyForm.courseName = item.name;
        let isEdu = this.type == '施工现场专业人员';
        this.matchPromise(item);
        this.matchType(item.type)
        // 绕开检查
        // this.stage = 2;
        // this.isCompanyPay = 1;
        // this.isCommitment=''
        // this.buyForm.rzCode = item.rzCode;
        // this.buyForm.company = 'ssss';
        // this.buyForm.courseName = item.courseName;
        // this.buyCourseDialog = true;
        // 检查
        httpServer("weixin.docheckpay", {
          courseId: item.course_id
        }).then((res) => {
          if (res.code == 200) {
            this.stage = 2;
            this.isCompanyPay = 0;
            this.isCommitment=''
            Object.assign( this.buyForm, res.data);
            if( isEdu){
              this.buyCourseDialog = true;
            }else{
              this.commitmentDialog = true;
            }
          }
        });
      },
      gotoPlay(courseId) {
        this.$router.push(`/center/class/train`);
      },
      handleCurrentChange(page) {
        this.page = page;
        this.filterData()
      },
      login(param) {
        httpServer("Auth.LoginStudy", param).then(res => {
          if (res.code == 200) {
            let {
              nickname,
              token,
              uid
            } = res.data;
            localStorage.nickname = nickname;
            localStorage.token = token;
            localStorage.uid = uid
            this.user = {
              nickname,
              token,
              uid
            };
            this.loginOk = true
            this.loginDialog = false
          }
        })
      }
    },
  };
</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>
