<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.invoiceApplyNumber || '' }}
            </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="text">
                开票金额：
              </text>
              <text class="money">
                ￥{{ splitNumber(detailData.invoiceMoney) || '--' }}
              </text>
            </view>
            <view class="info-cell-item">
              <text class="text">
                发票号码：{{ detailData.invoiceNumber || '--' }}
              </text>
            </view>
            <view class="info-cell-item">
              <text class="text">
                实际开票日期：{{ detailData.realInvoiceDate | 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-base-info
            :detail-id="id"
            :type="comType"
            :insert-fields="insertFields"
            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,
    DeleteByIds,
    ChangeOwnerUser
  } from 'API/crm/invoice'
  import { QueryExamineRecordList, AuditExamine } from 'API/examine'

  import DetailBaseInfo from '../components/detailSection/baseInfo'
  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: 'InvoiceDetail',
    filters: {
      formatTime(val) {
        if (!val) return '--'
        return moment(val).format('YYYY-MM-DD')
      }
    },
    components: {
      DetailBaseInfo,
      DetailAbout,
			FlowProgress
    },
    mixins: [detailMixins],
    data() {
      return {
        comType: 'crm_invoice',
        commandList: [],
        insertFields: [],

        tabs: [
          { label: '基本信息', value: 0 },
          { label: '相关信息', value: 1 }
        ],

        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({invoiceId: this.id}).then(response => {
          this.detailData = response
          this.getAuditInfo()
          this.setInsertFields()
        }).catch(() => {
          this.goBack()
        })
      },

      setInsertFields() {
        const data = this.detailData
        const titleType = { 1: '单位', 2: '个人', }[data.titleType]
        this.insertFields = [
          {
            name: '发票信息',
            list: [
              { fieldId: 1, name: '抬头类型', formType: 'text', value: titleType },
              { fieldId: 2, name: '开票抬头', formType: 'text', value: data.invoiceTitle },
              { fieldId: 3, name: '纳税人识别号', formType: 'text', value: data.taxNumber },
              { fieldId: 4, name: '开户行', formType: 'text', value: data.depositBank },
              { fieldId: 5, name: '开户账号', formType: 'text', value: data.depositAccount },
              { fieldId: 6, name: '开票地址', formType: 'text', value: data.depositAddress },
              { fieldId: 7, name: '电话', formType: 'text', value: data.telephone }
            ]
          },
          {
            name: '邮寄信息',
            list: [
              { fieldId: 1, name: '联系人', formType: 'text', value: data.contactsName },
              { fieldId: 2, name: '联系方式', formType: 'text', value: data.contactsMobile },
              { fieldId: 3, name: '邮寄地址', formType: 'text', value: data.contactsAddress }
            ]
          }
        ]
      },

      /**
       * 获取审批流
       */
      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.invoice.transfer', value: 'transfer'},
          {label: '编辑', imgIcon: 'update', auth: 'crm.invoice.update', value: 'update'},
          {label: '开票', imgIcon: 'dealStatus', auth: 'crm.invoice.updateInvoiceStatus', value: 'updateInvoiceStatus'},
          {label: '删除', imgIcon: 'delete', auth: 'crm.invoice.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)
          }
        }
      },

      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 'update':
          this.handleEdit()
          break
        case 'updateInvoiceStatus':
          this.$Router.navigateTo({
            url: '/pages_crm/invoice/updateStatus',
            query: {
              id: this.id,
              status: this.detailData.invoiceStatus
            }
          })
          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
          }
        })
      },

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

      /**
       * 转移
       */
      handleTransfer(user) {
        let params = {
          ids: [this.id],
          ownerUserId: user.userId,
          transferType: 1
        }
        ChangeOwnerUser(params).then(() => {
          this.$toast('转移成功')
          this.getDetail()
          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;
    .money {
      font-size: $wk-font-sm;
      font-weight: bold;
      color: $warning;
    }
    .text {
      font-size: $wk-font-mini;
      color: $gray;
    }
  }
}
</style>
