<template>
   <div class="proof-detail">
    <div style="position:relative;" class="caozuo" v-if="baseProof && id">
      <common-svg name="cunzhengliebiao-gengduo" class="tubiao" @click.native="showMoreAction = !showMoreAction;"></common-svg>
      <ul class="moreAction" v-show="showMoreAction" style="position:absolute;right:0;top:40px;z-index:1000;width:112px;padding: 20px;
          background:rgba(255,255,255,1);
          box-shadow:0px 2px 10px 0px rgba(0,0,0,0.12);">
        <li @click="delIncrementProof">删除</li>
        <li @click="reSendBlockChain(id)">重新上链</li>
      </ul>
    </div>
    <van-field v-model="name" label="填写存证名称" placeholder="请输入" />
    <template-detail :detailInformation="detail" class="detail"></template-detail>
    <div class="btn-group" v-if="!baseProof">
      <div style="overflow:hidden;color:#B6B5BA;font-size:14px;white-space:nowrap;margin-right: 10px;flex:auto;text-align:left;">已选模板:<span style="color:#3F79FE;margin-left:10px;">{{proofType}}</span></div>
      <div class="right" v-show="showBtn"
       style="width:119px;color:#FFFFFF;line-height:40px;
              height:40px;
              background:linear-gradient(360deg,rgba(93,123,246,1) 0%,rgba(108,122,254,1) 100%);
              box-shadow:0px 2px 10px 0px rgba(63,121,254,0.4);
              border-radius:4px;"
        @click="showBanner = true">
        下一步
      </div>
    </div>
    <div class="btn-group" v-else>
       <div
        v-show="showBtn"
        @click="save([])"
        class="left"
        >保存</div>
      <van-button
        v-show="showBtn"
        @click="saveAndChain([])"
        class="right"
        block
        color="#3F79FE"  
        type="primary" 
        >保存并上链</van-button>
    </div>
    <add-banner v-if="showBanner" :banners="banners" @save="save" @save-and-chain="saveAndChain"></add-banner>
   </div>
</template>
<script lang="ts">
import { Component, Prop, Watch, Vue } from 'vue-property-decorator';
import { Button, Field } from 'vant';
import { Getter, State } from 'vuex-class';
import { TemplateDataItem } from '@/const/interface';
import { Route } from 'vue-router';
import AddBanner from './components/AddBanner.vue';
@Component({
  components: {
    [Button.name]: Button,
    [Field.name]: Field,
    AddBanner,
  },
})
export default class Detail extends Vue {
  @State('userInfo') private userInfo!: any;

  private showBanner: boolean = false;
  private id: number = 0;
  private name: string = '';
  private detail: any[]  = [] ;
  private showBtn: boolean = false;
  private detail2: string  = '' ;
  private name2: string = '';
  private proofType: string = '';
  private checkEdited: boolean = true;
  private banners: string[] = [];
  private showMoreAction: boolean = false;
  @Prop({
  })
  private templateId!: number;
  @Prop({
  })
  private proofId!: number;
  @Prop({})
  private preProof!: any;
  @Prop({})
  private baseProof!: any;

  @Watch('templateId', { immediate: true, deep: true })
  private async onRouteChange(newTemplateId: number, oldTemplateId: number) {
    if (newTemplateId) {
      const templateDetail = await this.$api.template.get(newTemplateId);
      this.detail = JSON.parse(templateDetail.detail);
      this.detail2 = JSON.stringify(this.detail);
      this.proofType = templateDetail.name;
      this.name = templateDetail.name;
      this.name2 = this.name;
      this.showBtn = true;
    }
  }
  @Watch('proofId', { immediate: true, deep: true })
  private async onProofIdChange(newProofId: number, oldProofId: number) {
    if (newProofId) {
      let proofDetail: any;
      if (this.baseProof) {
        proofDetail = await this.$api.proof.incrementGet(newProofId);
      } else {
        proofDetail = await this.$api.proof.get(newProofId);
      }
      this.detail = (JSON.parse(proofDetail.detail) as any).slice(0, -1);
      this.detail2 = Object.freeze(JSON.stringify(this.detail));
      this.id = proofDetail.id;
      this.name = proofDetail.name;
      this.name2 = this.name;
      this.proofType = (JSON.parse(proofDetail.detail) as any)[(JSON.parse(proofDetail.detail) as any).length - 1]
                        .data.find((item: any) => item.key === '存证类型').data.value;
      this.showBtn = true;
      this.banners = JSON.parse(proofDetail.note).banners;
    }
  }
  get baseProofId() {
    if (this.baseProof) {
      return (JSON.parse(this.baseProof) as any).id;
    }
    return -1;
  }
  get baseProofHash() {
    if (this.baseProof) {
      return (JSON.parse(this.baseProof) as any).hash;
    }
    return 'null';
  }
  get preProofHash() {
    if (this.preProof) {
      return (JSON.parse(this.preProof) as any).hash;
    }
    return 'null';
  }
  get note() {
    const {user , icon } = this.userInfo;
    let obj: any = {};
    if (this.baseProof) {
      const baseProof = JSON.parse(this.baseProof);
      obj = {
        evidenceName: baseProof.name,
        stepName: this.name,
      };
    }
    const note = {
      userName: user, // String 账号名
      userIcon: icon, // String 用户图标图片地址
      evidenceName: this.name, // String 存证名称，ps：溯源时为父级商品名
      stepName: '', // String 溯源时的存证名称，非溯源时为空
      version: 1 , // Number 数据结构版本号，目前写死为 1
      banners: this.banners, // Array banner图数组，hash——图片哈希，target——跳转目标（暂未用到，可置空，某版溯源出现过这需求，作预留）
    };
    return JSON.stringify({...note, ...obj});
  }
  get extData() {
    const baseData: TemplateDataItem = {
        label: 'ext',
        key: 'ext',
        type: 3,
        data: [
            {
              data: {
                      type: 'text',
                      format: 'string',
                      value: this.name,
                    },
              type: 0,
              key: '存证名称',
              label: '存证名称',
            },
            {
              data: {
                      type: 'text',
                      format: 'string',
                      value: this.baseProofHash,
                    },
              type: 0,
              key: 'basehash',
              label: 'basehash',
            },
            {
              data: {
                      type: 'text',
                      format: 'string',
                      value: this.preProofHash,
                    },
              type: 0,
              key: 'prehash',
              label: 'prehash'},
            {
              data: {
                    type: 'text',
                    format: 'string',
                    value: this.proofType,
                  },
              type: 0,
              key: '存证类型',
              label: '存证类型'},
        ],
    };
    return baseData;
  }
  private beforeRouteLeave(to: Route, from: Route, next: (params?: any) => void) {
    if (!this.checkEdited) { return next(); }
    if ( this.name !== this.name2 || JSON.stringify(this.detail) !== this.detail2 ) {
      this.$dialog.confirm({
        title: '提示',
        message: '返回后，信息不做保存，确定要返回吗？',
        confirmButtonText: '离开',
        cancelButtonText: '继续填写',
      }).then(() => {
        next();
      }).catch(() => {
        next(false);
      });
    } else {
      next();
    }
  }
  private async addProof() {
    const detail = [...this.detail, this.extData];
    const result = await this.$api.proof.add(this.name, detail, this.note);
    return result.id;
  }
  private async addIncrementProof() {
    const detail = [...this.detail, this.extData];
    const { baseProofId, baseProofHash, preProofHash , name , note } = this;
    const result = await this.$api.proof.incrementAdd(baseProofId, baseProofHash, preProofHash, name, detail, note);
    return result.id;
  }
  private async editProof() {
    const detail = [...this.detail, this.extData];
    await this.$api.proof.update(this.id, this.name, detail, this.note);
  }
  private async editIncrementProof() {
    const detail = [...this.detail, this.extData];
    return await this.$api.proof.incrementEdit(this.id, this.name, detail, this.note);
  }
  private async incrementSendBlockChain(id: number) {
    return await this.$api.proof.incrementSendBlockChain(id);
  }
  private async sendBlockChain(id: number) {
    await this.$api.proof.sendBlockChian(id);
  }
  private async submit(flag: boolean) { // flase 仅保存 true: 保存并上链
    const detail = [...this.detail, this.extData];
    let id: number = -1;
    if (this.baseProof) {
      if (this.id) {
        id = this.id;
        await this.editIncrementProof();
      } else {
        if (!this.preProofHash) {
          this.$toast('请先上链上一条增量存证');
          return Promise.reject('请先上链上一条增量存证');
        }
        id = await this.addIncrementProof();
      }
      if (flag) {
        await this.incrementSendBlockChain(id);
      }
    } else {
      if (this.id) {
        id = this.id;
        await this.editProof();
      } else {
        id = await this.addProof();
      }
      if (flag) {
        await this.sendBlockChain(id);
      }
    }
    this.checkEdited = false;
    // this.$router.push({name: 'ProofList'});
  }
  private save(hashs: string[]) {
    this.banners = hashs;
    this.showBanner = false;
    this.submit(false);
    this.$router.push({name: 'ProofList'});
  }
  private async saveAndChain(hashs: string[]) {
    this.banners = hashs;
    this.showBanner = false;
    await this.submit(true);
    this.$router.push({name: 'ProofList'});
  }
  private async delIncrementProof() {
    await this.$api.proof.incrementDelete(this.id);
    this.$router.push({name: 'ProofList'});
  }
  private async reSendBlockChain(id: number) {
    await this.incrementSendBlockChain(id);
    this.$router.push({name: 'ProofList'});
  }
}
</script>
<style scoped lang="scss">
  .proof-detail{
    padding: 9px 18px;
    background: #FFFFFF;
    min-height: 100vh;
    ::v-deep .van-field{
      flex-direction: column;
      input{
        font-size: 16px;
      }
      &__label{
        text-align: left;
        font-size: 14px;
        color: $labelColor;
       
      }
      &__value{
        margin-top: 8px;
        color: $valueColor;
      }
    }
    ::v-deep .van-cell{
      padding: 12px 0;
    }
    .caozuo{
      .tubiao{
        position:absolute;
        right: 17px;
        top: 10px;
        z-index: 1000;
      }
      .moreAction{
        li{
          line-height: 2em;
        }
      }
    }
    .detail{
      margin-bottom: 66px;
    }
    .btn-group{
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      display: flex;
      align-items: center;
      padding: 11px 17px;
      background: #FFFFFF;
      box-shadow:0px 2px 4px 0px rgba(241,243,251,1);
      .right{
        flex: auto;
      }
      .left{
        width: 160px;
        height: 43.98px;
        line-height: 43.98px;
        margin-right: 10px;
        background: #FFFFFF;
        color: #000000;
        border-radius:4px;
        border:1px solid rgba(238,238,238,1);
      }
    }
   
  }
</style>