<template>
   <div class="cpr_step_page">

      <div class="center_container">
         <CprHeader :title="headerText" :backPath="'/'" @onBack="cancelCpr"></CprHeader>
      </div>

      <div class="cpr_step_label" v-if="currentStep <= 4">
         <AppStep :data="mySteps" :currentStep="currentStep"></AppStep>
      </div>

      <div class="center_container">
         <StepFirstPage v-if="currentStep == 1"></StepFirstPage>
         <StepSecondtPage v-if="currentStep == 2"></StepSecondtPage>
         <StepThirdPage v-if="currentStep == 3"></StepThirdPage>
         <StepFourthPage v-if="currentStep == 4"></StepFourthPage>
      </div>
      <StepFifthPage v-if="currentStep == 5"></StepFifthPage>

      <div class="apply_ing" v-if="applyStatus == eApplyStatus.APPLYING">
         <img class="loading_img" src="@/assets/img/loading.png" alt="">
         <div class="loading_text">LODING</div>
         <div class="loading_tip">你的版权申请正在提交中!</div>
      </div>

      <div class="apply_success" v-if="applyStatus == eApplyStatus.APPLYSUCCESS && currentStep == 6">
         <img class="apply_res_img" src="@/assets/img/apply_success.png" alt="">
         <div class="apply_success_tip">提交成功！</div>
         <!-- <div class="apply_account">流水号：11111111111111</div> -->
         <div class="apply_text">请耐心等待湖北版权局审核受理，受理成功后将在15个工作日内完成登记。</div>
         <div class="apply_after_btn" @click="gotoCheck">查看登记</div>
      </div>
      <div class="apply_fail" v-if="applyStatus == eApplyStatus.APPLYFAIL && currentStep == 6">
         <img class="apply_res_img" src="@/assets/img/apply_fail.png" alt="">
         <div class="apply_fail_tip">抱歉！网络出错了！</div>
         <!-- <div class="apply_account">流水号：11111111111111</div> -->
         <!-- <div class="apply_text">这里是失败的原因，这里是失败的原因，这里是失败的原因！</div> -->
         <div class="apply_after_btn" @click="reApplyFun">重新提交</div>
      </div>

      <div class="step_change_box" v-if=" currentStep <= 5 && !isCheck && !afterApply">
          <div v-if="currentStep == 1" class="left" @click="cancelCpr">取消</div>
          <div v-else-if="currentStep == 5" class="left" @click="preStep()">修改</div>
          <div v-else class="left" @click="preStep()">上一步</div>
          <div v-if="currentStep == 5" class="right" :class="{'right_disabled': nextBtnDisabled}" @click="nextStep()">确认提交</div>
          <div v-else class="right" :class="{'right_disabled': nextBtnDisabled}" @click="nextStep()">下一步</div>
      </div>

   </div>
</template>

<script lang='ts'>
import Vue from 'vue'
import { mapDraft, mapFilterDraft } from "./mapState"

// interface PageData {
//    [key: string]: any
// }
// interface FileData {
//    fileName: string;
//    fileHash: string;
//    file: File;
// }
enum eApplyStatus {
   BEFOREAPPLY,
   APPLYING,
   AFTERAPPLY,
   APPLYSUCCESS,
   APPLYFAIL
}
export default Vue.extend({
   name:'',
   data(){
      return {
         eApplyStatus,
         applyStatus: eApplyStatus.BEFOREAPPLY,
         draftId: this.$route.query.draftId || undefined,//草稿的记录id
         editId: this.$route.query.editId || undefined,//非草稿的记录id
         isCheck: this.$route.query.check || undefined,//申请完查看详情
         afterApply: false,//当前记录申请后,
         reApply: this.$route.query.reApply || undefined,//如果是，则是登记失败或待补正的情况，不删除原纪录
      }
   },
   computed:{
      needGetDraft(){
         return this.$store.state.copyright.needGetDraft
      },
      headerText(): string{
         if(this.$store.state.copyright.currentStep == 5) {
            return '信息确认'
         }else {
            return '版权登记'
         }
      },
      currentStep():number{
         return this.$store.state.copyright.currentStep
      },
      mySteps():Array<any>{
        return [
          {
            text: "作品文件",
          },
          {
            text: "作品信息",
          },
          {
            text: "作品权属",
          },
          {
            text: "著作权人与作者",
          },
        ]
      },
      /**判断每一步的下一步按钮是否可用 */
      nextBtnDisabled(): boolean{
         let disabled = false
         if(this.currentStep == 1) {
            const pageData = this.$store.state.copyright.eachPageData[0]
            if(!pageData.trace || pageData.fileList.length <= 0 || pageData.commissionFileList.length <= 0) {
               disabled = true
            }
            for(let item of pageData.fileList) {
               if(!item.fileUrl) return true
            }
            for(let item of pageData.commissionFileList) {
               if(!item.fileUrl) return true
            }
         }else if(this.currentStep == 2) {
            const pageData = this.$store.state.copyright.eachPageData[1]
            if(!pageData.proofName || !pageData.proofType || !pageData.proofFeature || !pageData.proofDesc || !pageData.proofCreateProgress || !pageData.proofFinishDate || pageData.proofFinishPlace.length <= 0) {
               disabled = true
            }
            if(pageData.proofPublishStatus == 1 && (!pageData.proofPublishDate || pageData.proofPublishPlace.length <= 0)) {
               disabled = true
            }
         }else if(this.currentStep == 3) {
            const pageData = this.$store.state.copyright.eachPageData[2]
            if(!pageData.authGetWay || pageData.uploadAuthCer.length <= 0 || !pageData.authBelongWay || pageData.authGuaranteeCer.length <= 0) {
               disabled = true
            }
            if([1,2,3,4].indexOf(pageData.authBelongWay.value) != -1 && pageData.authBelongCer.length <= 0) {
               disabled = true
            }
            for(let item of pageData.uploadAuthCer) {
               if(!item.fileUrl) return true
            }
            for(let item of pageData.authGuaranteeCer) {
               if(!item.fileUrl) return true
            }
            for(let item of pageData.authBelongCer) {
               if(!item.fileUrl) return true
            }
         }else if(this.currentStep == 4) {
            const pageData = this.$store.state.copyright.eachPageData[3]
            if(pageData.copyrightOwnerList.length <= 0 || pageData.authorList.length <= 0 || pageData.rightList.length <= 0 ) {
               disabled = true
            }
            if(pageData.authorList.length >= 1) {
               for(let item of pageData.authorList) {
                  if(!item.name || !item.aliasType.name || !item.alias) {
                     disabled = true
                  }
               }
            }
         }
         return disabled
      }
   },
   async mounted(){
      if((this.draftId && !this.needGetDraft) || (this.editId && !this.needGetDraft)) {
         await this.getDraft()
      }
   },
   components:{
      CprHeader: ()=>import('../component/CprHeader.vue'),
      AppStep: ()=>import('../component/CprStep.vue'),
      StepFirstPage: ()=>import('@/view/NFT/Copyright/CopyrightStep/component/StepFirstPage.vue'),
      StepSecondtPage: ()=>import('@/view/NFT/Copyright/CopyrightStep/component/StepSecondPage.vue'),
      StepThirdPage: ()=>import('@/view/NFT/Copyright/CopyrightStep/component/StepThirdPage.vue'),
      StepFourthPage: ()=>import('@/view/NFT/Copyright/CopyrightStep/component/StepFourthPage.vue'),
      StepFifthPage: ()=>import('@/view/NFT/Copyright/CopyrightStep/component/StepFifthPage.vue'),
   },
   methods:{

      /**获取草稿或重新编辑时 */
      async getDraft(){
         if(this.draftId) {
            const draftRes = await this.$service.copyrightService.getDraft(this.draftId)
            if(draftRes) {
               this.$store.commit('copyright/initEachPageData', draftRes)
            }
         }else if(this.editId) {
            const draftRes = await this.$service.copyrightService.getContentJson(this.editId)
            if(draftRes) {
               this.$store.commit('copyright/initEachPageData', draftRes)
            }
         }
      },

      /**退出的时候，如果已经提交则直接退出，否则还要经过比对操作*/
      async cancelCpr(){
         /**如果是提交之后退出的，那就不用保存草稿,之前再提交申请时已经分类操作过了*/
         if(this.afterApply) {
            this.leaveAndReset()
            return 
         }

         /**如果未提交，那就是修改部分然后退出，如果数据发送改变需要保存草稿 */
         const draftJson = this.$store.state.copyright.draft//草稿
         const rawRawJson = JSON.stringify(this.$store.state.copyright.rawPageData)//初始的空数据
         const rawJson = JSON.stringify(this.$store.state.copyright.eachPageData)//改变后的数据
         /**如果数据发生更改才要保存草稿 */
         /**如果有草稿，则拿草稿和改变后的数据对比,改变则提示是否保存 */
         if(draftJson){
            if(draftJson != rawJson){
               this.$dialog.confirm({
                  title: '温馨提示',
                  message:  '您将退出版权申请，退出后记录将保存在草稿中。'
               }).then(async ()=>{
                  const mapJson = JSON.stringify(mapDraft(this.$store.state.copyright.eachPageData))
                  // const mapJson = JSON.stringify(mapFilterDraft(this.$store.state.copyright.eachPageData, JSON.parse(draftJson)))
                  const step = this.$store.state.copyright.currentStep
                  let currentStep = step >= 6? 4 : step
                  let saveDraftRes = null
                  /**保存了新的草稿，那就删除之前保存的草稿或撤回的认证,如果是通过草稿修改的那删除原草稿;如果是没有申请完的记录修改的，那新建草稿时要再传一个copyrightId，后端根据这个id删除原记录*/
                  if(this.draftId) {
                     saveDraftRes = await this.$service.copyrightService.saveDraft(rawJson, mapJson, currentStep)//保存草稿
                     await this.$service.copyrightService.deleteDraft(this.draftId as any)//删除草稿
                  }else if(this.editId) {
                     /**如果是已撤回，则要删除原纪录(撤回状态) */
                     if(!this.reApply) {
                        saveDraftRes = await this.$service.copyrightService.saveDraft(rawJson, mapJson, currentStep, this.editId as string)//保存草稿加删除原纪录
                     /**如果是登记失败或待补正，则不删除原纪录 */
                     }else {
                        saveDraftRes = await this.$service.copyrightService.saveDraft(rawJson, mapJson, currentStep)//保存草稿
                     }
                  }
                  if(saveDraftRes){
                     this.$toast('保存草稿成功~')
                  }
                  this.leaveAndReset()
               }).catch(()=>{
                  // this.leaveAndReset()
               })
            }else {
               this.leaveAndReset()
            }
         /**如果没有草稿，则拿最原始的空数据和改变后的数据对比 */
         }else {
            if(rawRawJson != rawJson){
               this.$dialog.confirm({
                  title: '温馨提示',
                  message: '您将退出版权申请，退出后记录将保存在草稿中。'
               }).then(async ()=>{
                  const mapJson = JSON.stringify(mapDraft(this.$store.state.copyright.eachPageData))
                  const step = this.$store.state.copyright.currentStep
                  let currentStep = step >= 6? 4 : step
                  const saveDraftRes = await this.$service.copyrightService.saveDraft(rawJson, mapJson, currentStep)
                  if(saveDraftRes){
                     this.$toast('保存草稿成功~')
                  }
                  this.leaveAndReset()
               }).catch(()=>{
                  // this.leaveAndReset()
               })
            }else {
               this.leaveAndReset()
            }
         }
      },

      /**退出并重置数据 */
      leaveAndReset(){
         /**退出 */
         this.$router.push('/Copyright/List')
         /**重置数据 */
         this.$store.commit('copyright/resetAllData')
      },

      /**上一步 */
      preStep(){
         if(this.currentStep > 1)
         this.$store.commit('copyright/changeStep', -1)
      },

      /**下一步 */
      async nextStep(){
          /**如果步骤小于6, 且按钮可用则下一步 */
          if(this.currentStep < 6 && !this.nextBtnDisabled) {
             this.$store.commit('copyright/changeStep', 1)
          }
          /**如果当前步骤为5，那下一步就是发布 */
          if(this.currentStep == 6) {
             this.copyrightApply()
          }
      },

      /**版权申请,比较复杂，需要组织成后端的结构，如果有草稿还要和草稿比对，没有修改则传[] */
      async copyrightApply(){
         this.applyStatus = eApplyStatus.APPLYING
         const draftJson = this.$store.state.copyright.draft//草稿
         /**如果没有草稿,说明之前没保存过，那就直接映射成后端的数据 */
         if(!draftJson) {
            const rawJSON = JSON.stringify(this.$store.state.copyright.eachPageData)
            const mapData = mapDraft(this.$store.state.copyright.eachPageData) as any
            mapData.content = rawJSON
            const applyRes = await this.$service.copyrightService.copyrightApply(mapData)//提交申请
            if(applyRes) {
               this.applyStatus = eApplyStatus.APPLYSUCCESS
               this.afterApply = true
            }else {
               this.applyStatus = eApplyStatus.APPLYFAIL
            }
         /**如果有草稿，需要和草稿对比，还要判断是否是重新申请的,是重新申请的有些数组如果没变过，则传[] */
         }else {
            const rawJSON = JSON.stringify(this.$store.state.copyright.eachPageData)

            let applyRes = null
            if(this.reApply) {/**重新申请的情况下 */
               const mapData = mapFilterDraft(this.$store.state.copyright.eachPageData, JSON.parse(draftJson))
               mapData.content = rawJSON
               mapData.id = this.editId
               applyRes = await this.$service.copyrightService.editCprApply(mapData)//编辑版权申请
            } else {/**提交草稿或撤回的情况下 */
               const mapData = mapDraft(this.$store.state.copyright.eachPageData)
               mapData.content = rawJSON
               applyRes = await this.$service.copyrightService.copyrightApply(mapData)//提交申请
            }
            if(applyRes) {
               this.applyStatus = eApplyStatus.APPLYSUCCESS
               this.afterApply = true
               /**提交成功之后，删除之前的草稿或编辑的申请记录，如果原纪录已经申请过那就不删除 */
               if(this.draftId) {//删除草稿
                  await this.$service.copyrightService.deleteDraft(this.draftId as any)
               }else if(this.editId && !this.reApply) {//如果是通过未提交到最后的记录修改的,则删除原记录
                  await this.$service.copyrightService.deleteCopyrightApply(this.editId as any)
               }
            }else {
               this.applyStatus = eApplyStatus.APPLYFAIL
            }  
         }
      },

      /**版权申请提交完之后，查看登记 */
      gotoCheck(){
         this.$store.commit('copyright/changeCurrentStep', 5)
      },
      /**如果提交失败，重新提交 */
      reApplyFun(){
         this.applyStatus = eApplyStatus.APPLYING
         this.copyrightApply()
      }
   }

})
</script>

<style lang='less'>
.cpr_step_page {
   height: 100vh;
   padding-bottom:150px;
   background-color: #fff;
   overflow-y: scroll;
   .center_container {
      padding: 0 16px;
   }
   .cpr_step_label {
      margin-top: 27px;
      padding-bottom: 10px;
      border-bottom: 5px solid #F5F5F5;
   }
   .apply_ing {
      .loading_img {
         position: fixed;
         top: 40%;
         left: 50%;
         width: 40%;
         margin-top: -20%;
         margin-left: -20%;
         animation: circle 2s infinite linear;
      }
      @keyframes circle {
        from {
          transform: rotate(0) ;
        }
        to {
          transform: rotate(360deg) ;
        }
      }
      .loading_text {
         position: fixed;
         top: 40%;
         left: 50%;
         transform: translate(-50%, -50%);
         color: #2B446C;
         font-size: 14px;
         letter-spacing: 8px;
      }
      .loading_tip {
         position: fixed;
         top: 60%;
         left: 50%;
         transform: translate(-50%, -50%);
         text-align: center;
         font-size: 14px;
         color: #2B446C;
      }
   }
   .apply_success, .apply_fail {
      position: fixed;
      top: 45%;
      left: 50%;
      width: 80%;
      transform: translate(-50%, -50%);
      text-align: center;
      .apply_res_img {
         width: 70%;
         margin: 0 auto;
      }
      .apply_success_tip {
         margin-top: 15px;
         color: #2B446C;
         font-size: 14px;
      }
      .apply_fail_tip {
         color: #F68585;
      }
      .apply_text {
         margin-top: 15px;
         color: #7388AB;
         font-size: 14px;
      }
      .apply_after_btn {
         margin-top: 15px;
         color: #ffffff;
         background-color: #6377FF;
         width: 100%;
         height: 40px;
         line-height: 40px;
         box-shadow: 0px 2px 6px 0px rgba(99, 119, 255, 0.35);
      }
   }
   .step_change_box {
       position: fixed;
       bottom: 16px;
       left: 16px;
       right: 16px;
       display: flex;
       justify-content: space-between;
       align-items: center;
       text-align: center;
       .left {
           width: 48%;
           background-color: #6377FF;
           line-height: 40px;
           color: #fff;
           box-shadow: 0px 2px 6px 0px rgba(99, 119, 255, 0.4);
       }
       .right {
           width: 48%;
           background-color: #6377FF;
           line-height: 40px;
           color: #fff;
           box-shadow: 0px 2px 6px 0px rgba(99, 119, 255, 0.4);
       }
       .right_disabled {
          background: rgba(99, 119, 255, 0.2);
          color: #fff;
          box-shadow: 0px 2px 6px 0px rgba(99, 119, 255, 0.1);
       }
   }
}
.van-dialog {
   background-color: #fff;
   color: #2B446C;
   .van-dialog__message {
      background-color: #fff;
      color: #2B446C;
      text-align: left;
   }
   .van-dialog__cancel {
      background-color: #fff;
      color: #2B446C;
   }
   .van-dialog__confirm {
      background-color: #fff;
      color: #2B446C;
   }
}
</style>
