<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>
      </div>

      <el-row class="pt-line mt20">
        <el-col :span="6" v-for="item in typeList" style="width: 25%;float: left;" :key="item.id" v-if="item.isOpen">
           <span :class="{active:item.name==type }" class="nav-btn w220" @click="type=item.name">{{item.name}} </span>
        </el-col>

        <el-col :span="24" v-if="type=='继续教育' || type=='施工现场专业人员'" class="mt10" >
          <p class="tc" style="color: red;font-size: 18px;">
            报名对象为：2020年度及以后由培训单位核发的和2021年度换发的“电子培训合格证”且每年度需参加继续教育人员
          </p>
        </el-col>
      </el-row>

      <ul class="m-course-list clear mt10 classlist" v-if="total>0">
        <li v-for="(item,index) in list" :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(index)" v-else-if="item.is_pay==2 || !!item.buyImg" class="ui-btn btn-o">补充材料</el-button>
                <el-button @click="goPay(index)" 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="handleCurrentChange" :current-page="page" :page-size="size"
        layout="total, prev, pager, next" :total="total">
      </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" :append-to-body="true" width="750px" 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 :span="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 :span="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>
         <el-row>
          <el-col :span="24" class="pl20 pr20">
            <el-form-item lable="备注信息" prop="marks">
              <label slot="label">备注信息</label>
              <el-input v-model="buyForm.marks" type="textarea" placeholder="姓名+工种名称，例：张三+土建施工员" style="width: 573px;"></el-input>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <h2 class="tc"> 本课程费用:
            <strong style="color: red;"> {{buyForm.fee/100}} 元 </strong>
          </h2>
          <vue-viewer class="preview" width="150" height="150"
           :thumb="exampleImg" :full="exampleImg">
          </vue-viewer>
        </el-row>
        <el-row>
          <el-form-item>
            <img :src="buyForm.buyImg" :onerror="errorImg" class="setting-img" @click="showImg(buyForm.buyImg)">
            <do-upload @onFinish="uploadBuyImg" placeholder="上传支付凭证"> </do-upload>
          </el-form-item>
        </el-row>
        
        <el-row class="tc fc mt20">
          <el-form-item >
            <el-button @click="buyCourseDialog=false">取 消</el-button>
            <el-button @click="buyCourse" type="primary">确 定</el-button>
          </el-form-item>
        </el-row>

      </el-form>

    </el-dialog>



    <el-dialog title="承诺书" class="fc tc" :visible.sync="commitmentDialog" >

        <div>
          <div v-if="type=='继续教育'">
            <div class="commitment-header"> 致：{{settings.study.username}} </div>
            <div class="tl commitment">
                {{settings.study.promise}}
            </div>
            <div class="commitment-footer">
              特此诺书！
            </div>
          </div>

          <div v-else-if="type=='新培'">
            <div class="commitment-header"> 致：{{settings.exam.username}} </div>
            <div class="tl commitment">
              {{settings.exam.promise}}
            </div>
          </div>

          <div class="tl commitment-content mt20 p10">
            <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">
            <el-button @click="commitmentDialog = false">取 消</el-button>
            <el-button type="primary" :disabled="isCommitment?false:true" @click="buyCourseDialog=true">确 定</el-button>
          </span>
        </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 settings from '@/settings.js'
  import exampleImg from '@/assets/template.png'

  import {mapGetters, mapActions } from "vuex";

  export default {
    name: "Index",
    data() {
      return {
        page: 1,
        size: 9,
        total: 0,
        stage: 0,
        isCompanyPay: 0,
        width: "",
        type: this.$route.query.type || '',
        list: [],
        showData: [],
        isCommitment: "",
        buyCourseDialog: false,
        showExample: false,
        showImgDialog: false,
        exampleImg,
        buyForm: {
          marks: '',
          rzCode: '',
          payNo:'',
          courseName: ''
        },
        settings,
        promise,
        imgUrl: '',
        qrcodeUrl: "",
        outTradeNo: "",
        courseFee: 0,
        title: '',
        timer: null,
        tickCount: 0,
        listLoading: false,
        loginDialog: false,
        isLoginOk: false,
        media: {},
        commitmentDialog: false,
        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 {}
              }
            }
          ],
          courseName: [{
            required: true,
            message: '请输入报考岗位'
          }]
        },
        errorImg: 'this.src="' + require('../../../assets/images/no-data_hash5abcd2ef62.png') + '"'
      };
    },
    computed: {
      ...mapGetters("user", ["typeList", "userInfo"])
    },
    components: {
      unLogin,
      DoUpload
    },
    filters: {
      dateFilter(val) {
        return parseTime(val, '{y}-{m}-{d}')
      }
    },
    watch: {
      type(val) {
        this.page = 1
        this.getData()
      },
      isCommitment(val) {
        console.log(val)
      }
    },
    beforeMount() {
      if (!this.type && this.typeList.length > 0) {
        this.type = this.typeList[0].name
        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() {
        if (!this.type) return;
        let param = {
          size: this.size,
          type: this.type,
          from: (this.page - 1) * this.size
        }
        httpServer("course.getcoursemarket", param).then((res) => {
          if (res.code == 200) {
            this.list = res.data.list;
            this.total = res.data.total;
          }
        });
      },
      buyCourse() {
        this.$refs["elForm"].validate((valid) => {
          if (!valid) return;
          let {
            marks,
            payNo,
            course_id,
            courseName,
            rzCode,
            name,
            email
          } = this.buyForm;
          if (courseName != name) {
            this.$message.errorMsg("报考岗位有误", 1)
            return;
          }
          let param = {
            marks,
            payNo,
            courseId: course_id,
            courseName,
            rzCode,
            email
          }
          httpServer("course.buyCourse", param).then((res) => {
            if (res.code == 200) {
              this.$message.successMsg("申请购买成功", 1);
              this.buyForm.temp.buyImg = this.buyForm.buyImg
              this.buyForm.temp.marks = this.buyForm.marks
              this.buyForm.temp.is_pay = 0
              this.buyForm.temp.courseName = this.buyForm.courseName;
              this.buyForm.temp.rzCode = this.buyForm.rzCode
              this.buyCourseDialog = false
            }
          });
        })
      },
      gotoDetail(courseId) {
        this.$router.push(`/main/course/${courseId}`);
      },
      uploadBuyImg(url) {
        this.buyForm.buyImg = url;
      },
      goPay(index) {
        let item = this.list[index];
        this.buyForm = Object.assign({}, item)
        this.buyForm.temp = item;

        // 绕开检查
        this.stage = 2;
        this.isCompanyPay = 0;
        this.isCommitment=''
        this.buyForm.rzCode = item.rzCode;
        this.buyForm.courseName = item.courseName;
        this.commitmentDialog = true;
        // 检查
        // httpServer("weixin.docheckpay", {
        //   courseId: item.course_id
        // }).then((res) => {
        //   if (res.code == 200) {
        //     this.stage = 2;
        //     this.isCompanyPay = 0;
        //     this.isCommitment=''
        //     this.buyForm.rzCode = res.data.certificateNum;
        //     this.buyForm.courseName = res.data.positionName;
        //     this.commitmentDialog = true;
        //   }
        // });
      },
      gotoPlay(courseId) {
        this.$router.push(`/center/class/train`);
      },
      handleCurrentChange(page) {
        this.page = page;
        this.getData()
      },
      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;
  }
</style>
