<template>
  <view v-if="!refreshPage" class="uni-app">
    <view class="status-bar" />
    <wk-nav-bar
      :command-list="commandList"
      :refresh-prev="refreshPrevPage"
      title="合同详情"
      theme="white"
      class="nav-bar"
      @command="handleCommand" />

    <scroll-view
      v-if="!$isEmpty(detailData)"
      :scroll-y="true"
      class="main-container scroll-view-hook"
      @scrolltolower="handleScrollTolower">
      <view class="header-top">
        <view class="bg linear-gradient" />
        <view class="card">
          <view class="title-cell">
            <image :src="$static('images/crm/gray_contract.png')" class="type-icon" />
            <view class="title-text">
              {{ detailData.name || '' }}
            </view>
            <view
              v-if="showCheckStatus"
              :style="{
                backgroundColor: statusObj.bg,
                color: statusObj.color
              }"
              class="title-status">
              <text
                :class="statusObj.icon"
                class="wk" />
              <text>{{ statusObj.label }}</text>
            </view>
          </view>

          <view class="info-cell">
            <view class="info-cell-item">
              <text class="name">
                回款进度({{ detailData.receivedProgress }}%)
              </text>
              <view class="progress">
                <view :style="{width: detailData.receivedProgress + '%'}" class="now" />
              </view>
            </view>
            <view class="info-cell-item">
              <text class="name">
                合同金额
              </text>
              <text class="money">
                ￥{{ splitNumber(detailData.money) || '--' }}
              </text>
            </view>
            <view class="info-cell-item">
              <text class="text first">
                已回款：￥{{ splitNumber(detailData.receivablesMoney) || '0.0' }}
              </text>
              <text class="text">
                待回款：￥{{ splitNumber(detailData.unreceivedMoney) || '0.0' }}
              </text>
            </view>
            <view class="info-cell-item">
              <text class="text first">
                签约时间：{{ detailData.orderDate | formatTime }}
              </text>
            </view>
          </view>
					
          <view class="main-info">
            <flow-progress
              v-if="detailData"
              :type="comType"
              :detail-id="id"
              :detail-data="detailData" />	
          </view>
					
          <view
            class="relevance-cell"
            @click="handleToCustomer">
            <image :src="$static('images/application/customer.png')" class="cell-icon" />
            <text class="cell-body">
              {{ detailData.customerName }}
            </text>
            <text class="cell-link wk wk-arrow-right" />
          </view>

          <view
            v-if="auditInfo && auditInfo.isCheck === 1"
            class="check-box">
            <view class="btn success" @click="handleAuditAction('pass')">
              <text class="wk wk-check-fill icon" />
              <text>通过</text>
            </view>
            <view class="btn error" @click="handleAuditAction('refuse')">
              <text class="wk wk-close-fill icon" />
              <text>拒绝</text>
            </view>
          </view>
        </view>
      </view>

      <view class="wk-tabs">
        <view
          v-for="(tab, index) in tabs"
          :key="index"
          :class="{active: activeTab === tab.value}"
          class="wk-tab-item"
          @click="handleToggleTabs(tab.value)">
          {{ tab.label }}
        </view>
      </view>

      <wk-keep-alive v-if="id" v-model="activeTab">
        <wk-keep-alive-item>
          <detail-activity-list 
            ref="activity" 
            :detail-id="id" 
            :type="comType" 
            activity-title="合同" />
        </wk-keep-alive-item>

        <wk-keep-alive-item>
          <detail-base-info :detail-id="id" :type="comType" class="detail-container" />
        </wk-keep-alive-item>

        <wk-keep-alive-item>
          <detail-about
            :detail-id="id"
            :detail-data="detailData"
            :batch-id="detailData.batchId"
            class="detail-about-container" />
        </wk-keep-alive-item>
      </wk-keep-alive>
    </scroll-view>

    <uni-popup ref="popup" type="dialog">
      <uni-popup-dialog
        :content="dialogMsg"
        type="warning"
        @confirm="handleDialogConfirm" />
    </uni-popup>
  </view>
</template>

<script>
  import {
    QueryById,
    ChangeOwnerUser,
    DeleteByIds,
    DiscardById
  } from 'API/crm/contract'
  import { QueryExamineRecordList, AuditExamine } from 'API/examine'

  import DetailBaseInfo from '../components/detailSection/baseInfo'
  import DetailActivityList from '../components/detailSection/activityList'
  import DetailAbout from './components/tabsAbout'
	import FlowProgress from '../components/customFlow/flowProgress'

  import detailMixins from '../mixins/detail.js'
  import { mapGetters } from 'vuex'
  import { splitNumber } from '@/utils/lib.js'
  import moment from 'moment'

  export default {
    name: 'ContractDetail',
    filters: {
      formatTime(val) {
        if (!val) return '--'
        return moment(val).format('YYYY-MM-DD')
      }
    },
    components: {
      DetailBaseInfo,
      DetailActivityList,
      DetailAbout,
			FlowProgress
    },
    mixins: [detailMixins],
    data() {
      return {
        comType: 'crm_contract',
        commandList: [],

        auditInfo: null
      }
    },
    computed: {
      ...mapGetters({
        calcStatus: 'base/calcStatus',
        userInfo: 'user/userInfo'
      }),
      showCheckStatus() {
        return this.detailData.hasOwnProperty('checkStatus') && this.detailData.examineRecordId
      },
      statusObj() {
        if (!this.showCheckStatus) return {}
        return this.calcStatus(this.detailData.checkStatus) || {}
      }
    },
    methods: {
      splitNumber(num) {
        return splitNumber(num)
      },
      /**
       * 获取详情
       */
      getDetail() {
        QueryById({contractId: this.id}).then(response => {
          this.detailData = response
          this.getAuditInfo()
        }).catch(() => {
          this.goBack()
        })
      },

      /**
       * 获取审批流
       */
      getAuditInfo() {
        if (!this.detailData.examineRecordId) {
          this.auditInfo = null
          this.renderCommands()
          return
        }
        QueryExamineRecordList({
          recordId: this.detailData.examineRecordId,
          ownerUserId: this.detailData.ownerUserId
        }).then(res => {
          this.auditInfo = res || null
          this.renderCommands()
        }).catch()
      },

      /**
       * 渲染更多操作选项
       */
      renderCommands() {
        this.commandList = [
          {label: '查看审批流', imgIcon: 'read', noCheck: true, value: 'read'},
          {label: '转移', imgIcon: 'transfer', auth: 'crm.contract.transfer', value: 'transfer'},
          {label: '编辑', imgIcon: 'update', auth: 'crm.contract.update', value: 'update'},
          {label: '合同作废', imgIcon: 'discard', auth: 'crm.contract.discard', value: 'discard'},
          {label: '删除', imgIcon: 'delete', auth: 'crm.contract.delete', value: 'delete'}
        ]
        // 判断是否能够撤回审批
        let index = this.commandList.findIndex(item => item.label === '撤回审批')
        if (this.auditInfo && this.auditInfo.isRecheck === 1 && index === -1) {
          this.commandList.splice(1, 0, {
            label: '撤回审批',
            imgIcon: 'reset',
            noCheck: true,
            value: 'reset'
          })
        } else if (this.auditInfo && this.auditInfo.isRecheck !== 1 && index !== -1) {
          this.commandList.splice(index, 1)
        }
        index = null

        // 如果没有审批流则删除查看审批流
        index = this.commandList.findIndex(item => item.value === 'read')
        if (index !== -1 && !this.detailData.examineRecordId) {
          this.commandList.splice(index, 1)
        }
        index = null

        const checkStatus = this.detailData.checkStatus

        // 判断是否能编辑
        index = this.commandList.findIndex(item => item.value === 'update')
        if (index !== -1) {
          // 审核拒绝  审核撤回 未提交才能编辑
          // if (
          //   this.userInfo.userId !== this.detailData.createUserId ||
          //   (![2, 4, 5].includes(checkStatus) && this.detailData.examineRecordId)) {
          //   this.commandList.splice(index, 1)
          // }
          if (![2, 4, 5].includes(checkStatus) && this.detailData.examineRecordId) {
            this.commandList.splice(index, 1)
          }
        }
        index = null

        // 判断是否能删除
        index = this.commandList.findIndex(item => item.value === 'delete')
        if (index !== -1) {
          // 已撤回 未提交 作废 并且是超管才能删除
          if (!this.detailData.isAdmin === 1 ||
            (![4, 5, 8].includes(checkStatus) && this.detailData.examineRecordId)) {
            this.commandList.splice(index, 1)
          }
        }

        // 判断是否能作废
        index = this.commandList.findIndex(item => item.value === 'discard')
        if (index !== -1) {
          // 审核通过，有作废权限才能作废合同
          if (checkStatus !== 1) {
            this.commandList.splice(index, 1)
          }
        }

        // 如果合同已作废
        if (checkStatus === 8) {
          this.commandList = this.commandList.filter(item => ['read', 'delete'].includes(item.value))
        }
      },

      handleCommand(command) {
        this.commandValue = command.value
        switch (command.value) {
        case 'read':
          this.$Router.navigateTo({
            url: '/pages_crm/auditList',
            query: {
              id: this.detailData.examineRecordId,
              u_id: this.detailData.ownerUserId
            }
          })
          break
        case 'reset':
          this.handleAuditAction('cancel')
          break
        case 'transfer':
          this.handleToChangeOwnerUser()
          break
        case 'discard':
          this.dialogMsg = '您确定要作废该合同吗'
          this.$refs.popup.open()
          break
        case 'update':
          this.handleEdit()
          break
        case 'delete':
          this.dialogMsg = '您确定要删除该合同吗？'
          this.$refs.popup.open()
          break
        }
      },

      handleDialogConfirm(next) {
        switch (this.commandValue) {
        case 'discard':
          this.handleDiscard()
          break
        case 'delete':
          this.handleDelete()
          break
        }
        next()
      },

      /**
       * 审核操作
       * @param action 审核动作
       */
      handleAuditAction(action) {
        getApp().globalData.auditInfo = this.auditInfo
        uni.$once('save-audit', this.handleAudit)
        this.$Router.navigateTo({
          url: '/pages_common/audit/index',
          query: {
            type: action
          }
        })
      },

      /**
       * 审核
       * @param form 审核信息
       */
      handleAudit(form) {
        let params = {
          typeId: this.id,
          recordId: this.detailData.examineRecordId,
        ...form
        }
        // console.log('audit', params)
        AuditExamine(params).then(() => {
          this.$toast(params.status === 4 ? '撤回成功' : '审核成功')
          this.getDetail()
          this.refreshPrevPage = true
        }).catch(() => {})
      },

      /**
       * 跳转到客户
       */
      handleToCustomer() {
        this.$Router.navigateTo({
          url: '/pages_crm/customer/detail',
          query: {
            id: this.detailData.customerId
          }
        })
      },

      /**
       * 转移
       */
      handleTransfer(user) {
        let params = {
          ids: [Number(this.id)],
          ownerUserId: user.userId,
          transferType: 1
        }
        ChangeOwnerUser(params).then(() => {
          this.$toast('转移成功')
          this.getDetail()
          this.$refreshAndToPrev(this)
        }).catch(() => {})
      },

      /**
       * 合同作废
       */
      handleDiscard() {
        DiscardById({contractId: this.id}).then(() => {
          this.$toast('作废成功')
          this.$refreshAndToPrev(this)
        }).catch(() => {})
      },

      /**
       * 删除
       */
      handleDelete() {
        DeleteByIds([this.id]).then(() => {
          this.$toast('删除成功')
          this.$refreshAndToPrev(this)
        }).catch(() => {})
      }
    }
  }
</script>

<style scoped lang="scss">
@import "../style/detail.scss";

.info-cell {
  padding: 0 32rpx;
  margin-top: 20rpx;
  .info-cell-item {
    margin-bottom: 15rpx;
    @include left;
    .icon {
      width: 36rpx;
      height: 36rpx;
      vertical-align: middle;
      margin-right: 15rpx;
    }
    .name {
      font-size: $wk-font-sm;
      font-weight: 500;
      color: $dark;
      margin-right: 15rpx;
    }

    .progress {
      width: 160rpx;
      height: 12rpx;
      border-radius: 6rpx;
      background-color: #e1e1e1;
      margin-left: 10rpx;
      overflow: hidden;
      .now {
        height: 12rpx;
        background-color: $theme-color;
      }
    }

    .money {
      font-size: $wk-font-sm;
      font-weight: bold;
      color: $warning;
    }
    .text {
      font-size: $wk-font-mini;
      color: $gray;
      &.first {
        margin-right: 15rpx;
      }
    }
  }
}
</style>
