<template>
  <view v-if="!refreshPage && !$isEmpty(detailData)" 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
      :scroll-y="true"
      class="main-container scroll-view-hook">
      <view class="header-top">
        <view class="bg linear-gradient" />
        <view class="card">
          <view class="title-cell">
            <image :src="$static('images/crm/gray_receivables.png')" class="type-icon" />
            <view class="title-text">
              {{ detailData.number || '' }}
            </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="main-info">
            <view class="info-item">
              <text class="label">
                回款金额：
              </text>
              <text class="value">
                {{ detailData.money ? splitNumber(detailData.money) : '&#45;&#45;' }}
              </text>
            </view>
            <view class="info-item">
              <text class="label">
                回款方式：
              </text>
              <text class="value">
                {{ detailData.returnType || '&#45;&#45;' }}
              </text>
            </view>
            <view class="info-item">
              <text class="label">
                回款时间：
              </text>
              <text class="value">
                {{ detailData.returnTime || '&#45;&#45;' }}
              </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>

      <detail-base-info
        v-if="id"
        :detail-id="id"
        :detail-data="detailData"
        :type="comType"
        class="detail-container" />
    </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 } from 'API/crm/received'
  import { QueryExamineRecordList, AuditExamine } from 'API/examine'

  import DetailBaseInfo from '../components/detailSection/baseInfo'
	import FlowProgress from '../components/customFlow/flowProgress'

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

  export default {
    name: 'ReceivedDetail',
    components: {
      DetailBaseInfo,
			FlowProgress
    },
    mixins: [detailMixins],
    data() {
      return {
        id: null,
        routerQuery: {},

        comType: 'crm_receivables',
        detailData: {},
        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({receivablesId: 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: 'update', auth: 'crm.receivables.update', value: 'update'},
          {label: '删除', imgIcon: 'delete', auth: 'crm.receivables.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 (![4, 5, 8].includes(checkStatus)) {
          if (![4, 5, 8].includes(checkStatus) && this.detailData.examineRecordId) {
            this.commandList.splice(index, 1)
          }
        }
      },

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

      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 'update':
          this.handleEdit()
          break
        case 'delete':
          this.dialogMsg = '您确定要删除该回款吗？'
          this.$refs.popup.open()
          break
        }
      },

      handleDialogConfirm(next) {
        switch (this.commandValue) {
        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.refreshPrevPage = true
          this.$refreshAndToPrev(this)
        }).catch()
      },

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

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