<template>
  <view class="uni-app">
    <view class="status-bar" />
    <view class="main-container">
      <wk-nav-bar
        :command-list="commandList"
        :refresh-prev="refreshPrevPage"
        :title="title"
        @command="handleCommand" />

      <view v-if="!$isEmpty(detailData)" class="container">
        <view class="user-info section">
          <wk-avatar
            :name="detailData.createUser.realname"
            :avatar="detailData.createUser.img"
            :size="14"
            class="avatar" />
          <view class="info">
            <view class="info-name">
              {{ detailData.createUser.realname }}
            </view>
            <view class="info-time">
              {{ detailData.createTime }}
            </view>
          </view>
          <view class="status">
            <view
              :style="{
                backgroundColor: statusObj.color
              }"
              class="dot" />
            <view class="text">
              {{ statusObj.label }}
            </view>
          </view>
        </view>

        <view class="fields-info section">
          <template v-for="(item, index) in fieldList">
            <view
              v-if="item.formType !== 'desc_text'"
              :key="index"
              class="fields-info-item">
              <view v-if="item.formType === 'file'" class="item-box">
                <text class="item-box-label">
                  {{ item.name }}：
                </text>
                <view class="item-box-value">
                  <text
                    v-for="(file, childIndex) in item.value"
                    :key="childIndex"
                    class="file"
                    @click="downloadFile(file)">
                    {{ file.name }}
                  </text>
                </view>
              </view>

              <view
                v-else-if="isWebSite(item)"
                class="item-box">
                <text class="item-box-label">
                  {{ item.name }}：
                </text>
                <view
                  style="color: #3C80F7"
                  class="item-box-value"
                  @click="handlerWebsite(item)">
                  {{ getFieldValue(item) || '' }}
                </view>
              </view>

              <view
                v-else-if="isTel(item)"
                class="item-box">
                <text class="item-box-label">
                  {{ item.name }}：
                </text>
                <view
                  style="color: #3C80F7"
                  class="item-box-value"
                  @click="handlerCall(item)">
                  {{ getFieldValue(item) || '' }}
                </view>
              </view>

              <view
                v-else-if="item.formType === 'handwriting_sign'"
                class="handwriting-sign">
                <view class="handwriting-sign-label">
                  {{ item.name }}：
                </view>
                <view class="handwriting-sign-value">
                  <wk-signature-view :batch-id="item.value" />
                </view>
              </view>

              <view
                v-else-if="item.fieldName !== 'cause'"
                class="item-box">
                <text class="item-box-label">
                  {{ item.name }}：
                </text>
                <view class="item-box-value">
                  {{ getFieldValue(item) }}
                </view>
              </view>
            </view>
            <template v-else-if="item.formType === 'desc_text' && item.value">
              <view :key="index" class="desc_text">
                <rich-text :nodes="item.value" />
              </view>
            </template>
          </template>
        </view>

        <template v-if="detailTableList.length > 0">
          <detail-table-item
            v-for="(item, index) in detailTableList"
            :key="index"
            :field="item" />
        </template>

        <travel-item
          v-if="!$isEmpty(causeData)"
          :item="causeData"
          class="section" />

        <view class="attachment-conent section">
          <wk-image-content
            v-if="detailData.img && detailData.img.length > 0"
            :list="detailData.img"
            class="image-content" />
          <template v-if="detailData.file && detailData.file.length > 0">
            <view class="base-file-title">
              附件
            </view>
            <wk-file-content :list="detailData.file" />
          </template>
          <relevance-section v-if="showRelevance" :relevance-data="relevanceData" />
        </view>

        <view class="empty" />

        <!--审核流程-->
        <view
          v-if="auditInfo.examineFlowList"
          class="examine-flow-container section">
          <view
            v-for="(item, index) in auditInfo.examineFlowList"
            :key="index"
            class="flow-item">
            <wk-audit-flow-item
              :item-data="item"
              :audit-info="auditInfo" />
          </view>
        </view>
      </view>

      <view
        v-if="auditInfo.isCheck === 1 || auditInfo.isRecheck === 1"
        class="footer-region">
        <view class="footer-box">
          <view
            v-if="auditInfo.isRecheck === 1"
            class="footer-button recall"
            @click="handleAuditAction('cancel')">
            撤回
          </view>
          <template v-if="auditInfo.isCheck === 1">
            <view class="footer-button refuse" @click="handleAuditAction('refuse')">
              拒绝
            </view>
            <view class="footer-button pass" @click="handleAuditAction('pass')">
              通过
            </view>
          </template>
        </view>
      </view>
    </view>

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

<script>
  import {
    QueryExamineInfo,
    GetField,
    DeleteOaExamine
  } from 'API/oa/examine'
  import { QueryExamineRecordList, AuditExamine } from 'API/examine'

  import TravelItem from './components/travelItem.vue'
  import RelevanceSection from '@/components/base/relevance-section.vue'
  import DetailTableItem from './components/detailTableItem.vue'

  import { downloadFile } from '@/utils/file.js'
  import fieldValueMixins from '@/mixins/fieldValueMixins.js'

  // 0待审、1审批中、2通过、3失败、4撤销
  export default {
    name: 'OaExamineDetail',
    components: {
      TravelItem,
      RelevanceSection,
      DetailTableItem
    },
    mixins: [fieldValueMixins],
    data() {
      return {
        title: '普通审批',
        id: null,
        routerQuery: {},
        auditType: '',

        fieldList: [], // 审批的自定义字段
        auditInfo: {}, // 审批流程信息
        stepList: [], // 审批人列表
        detailData: {}, // 页面数据
        detailTableList: [], // 明细表格字段

        dialogMsg: '',
        dialogType: '',
        webUrl: '',
        refreshPage: false,
        refreshPrevPage: false
      }
    },
    computed: {
      statusObj() {
        return this.calcStatus(this.detailData.examineStatus)
      },
      // 明细数据
      causeData() {
        const findRes = this.fieldList.find(v => v.fieldName === 'cause')
        if (findRes) return findRes
        return {}
      },
      // 显示关联数据
      showRelevance() {
        return !this.$isEmpty(this.detailData.customerList) ||
          !this.$isEmpty(this.detailData.contactsList) ||
          !this.$isEmpty(this.detailData.businessList) ||
          !this.$isEmpty(this.detailData.contractList)
      },
      // 关联业务数据
      relevanceData() {
        return {
          customerList: this.detailData.customerList || [],
          contactsList: this.detailData.contactsList || [],
          businessList: this.detailData.businessList || [],
          contractList: this.detailData.contractList || []
        }
      },
      commandList() {
        const arr = [
          { label: '审批记录', value: 'read', imgIcon: 'read', noCheck: true},
          { label: '编辑', value: 'edit', imgIcon: 'update', noCheck: true },
          { label: '删除', value: 'delete', imgIcon: 'delete', noCheck: true }
        ]
        if ([2, 4].includes(this.detailData.examineStatus)) {
          return arr
        } else {
          return arr.slice(0, 1)
        }
      }
    },
    onLoad(options) {
      this.routerQuery = options
      this.id = this.routerQuery.id
      this.examineId = this.routerQuery.examineId
      this.getData()
    },
    onShow() {
      if (this.refreshPage) {
        this.refreshPage = false
        this.refreshPrevPage = true
        this.getData()
      }
    },
    onBackPress(evt) {
      if (evt.from === 'backbutton' && this.refreshPrevPage) {
        this.$refreshAndToPrev(this)
        return true // 返回值为 true 时，表示不执行默认的返回
      }
      return false
    },
    methods: {
      /**
       * 审批详情
       */
      getData() {
        QueryExamineInfo({
          examineId: this.id
        }).then(response => {
          this.detailData = response
          this.title = response.categoryTitle
          this.getAuditInfo()
          this.getField()
        })
      },

      /**
       * 获取自定义字段
       */
      getField() {
        GetField({
          id: this.examineId,
          isDetail: 1,
          examineId: this.id,
          label: 10,
          type: 1
        }).then(response => {
          this.fieldList = response.filter(o => o.formType !== 'detail_table')
          this.detailTableList = response.filter(o => o.formType === 'detail_table')
        }).catch()
      },

      /**
       * 打电话
       * @param item
       */
      handlerCall(item) {
        let tel = this.getFieldValue(item)
        if (!tel) return
        uni.makePhoneCall({
          phoneNumber: tel
        })
      },

      /**
       * 打开网址
       * @param {Object} item
       */
      handlerWebsite(item) {
        this.webUrl = this.getFieldValue(item)
        if (!this.webUrl) return
        if (
          !this.webUrl.startsWith('http://') ||
          !this.webUrl.startsWith('https://')
        ) {
          this.webUrl = `http://${this.webUrl}`
        }
        this.dialogMsg = `使用浏览器打开 ${this.webUrl} ？`
        this.dialogType = 'url'
        this.$refs.popup.open()
      },

      /**
       * 获取审批步骤
       */
      getAuditInfo() {
        QueryExamineRecordList({
          recordId: this.detailData.examineRecordId
        }).then(response => {
          this.auditInfo = response
          this.stepList = response.steps

          console.log('res step list: ', response)
        }).catch()
      },

      handleCommand(command) {
        if (this.$isEmpty(this.detailData)) return
        if (command.value === 'edit') {
          this.$Router.navigateTo({
            url: '/pages_examine/add',
            query: {
              id: this.id,
              title: this.detailData.categoryTitle,
              examineId: this.detailData.categoryId
            }
          })
        } else if (command.value === 'delete') {
          this.dialogMsg = '您确定要删除这次审批吗？'
          this.dialogType = 'delete'
          this.$refs.popup.open()
        } else if (command.value === 'read') {
          this.$Router.navigateTo({
            url: '/pages_examine/record',
            query: {
              id: this.detailData.examineRecordId
            }
          })
        }
      },

      handleDialogConfirm(next) {
        next()
        if (this.dialogType === 'delete') {
          this.dialogType = ''
          DeleteOaExamine({examineId: this.id}).then(response => {
            this.$toast('删除成功')
            this.$refreshAndToPrev(this)
          }).catch()
        } else if (this.dialogType === 'url') {
          this.dialogType = ''
          // #ifdef APP-PLUS
          plus.runtime.openURL(this.webUrl)
          // #endif
          // #ifdef H5
          window.open(this.webUrl, '_blank')
        // #endif
        }
      },

      handleAuditAction(action) {
        // cancel 撤回 refuse 拒绝 pass 通过
        this.auditType = 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:', form)
        AuditExamine(params).then(() => {
          this.$toast(params.status === 4 ? '撤销成功' : '审核成功')
          this.getData()
          this.refreshPrevPage = true
        }).catch()
      },

      downloadFile(file) {
        downloadFile(file)
      }
    }
  }
</script>

<style scoped lang="scss">
.main-container {
  .container {
    flex: 1;
    background-color: white;
    padding: 20rpx 0;
    overflow-y: scroll;

    .section {
      padding: 0 30rpx;
    }

    .user-info {
      margin-bottom: 20rpx;
      @include left;
      .avatar {
        width: 80rpx;
        height: 80rpx;
        margin-right: 15rpx;
      }
      .info {
        flex: 1;
        .info-name {
          color: $dark;
          font-size: $wk-font-medium;
        }
        .info-time {
          color: $light;
          font-size: $wk-font-sm;
        }
      }
      .status {
        color: $dark;
        font-size: $wk-font-base;
        @include left;
        .dot {
          width: 15rpx;
          height: 15rpx;
          border-radius: 50%;
          margin-right: 10rpx;
        }
      }
    }

    .fields-info {
      .fields-info-item {
        width: 100%;
        font-size: 26rpx;
        line-height: 50rpx;
        color: $dark;

        .item-box {
          display: flex;
          align-items: baseline;
          justify-content: flex-start;
          overflow: hidden;
          .item-box-label {
            max-width: 50%;
            color: $light;
          }
          .item-box-value {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            .file {
              color: $theme-color;
              text-align: left;
              @include ellipsis;
            }

          }
        }

        .handwriting-sign {
          .handwriting-sign-label {
            color: $light;
          }
          .handwriting-sign-value {
          }
        }
      }

      .desc_text {
        font-size: $wk-font-base;
        margin: 10rpx 0;
      }
    }

    .attachment-conent {
      padding-top: 15rpx;
      padding-bottom: 15rpx;
      .base-file-title {
        font-size: 26rpx;
        margin-top: 20rpx;
      }
    }

    .empty {
      width: 100%;
      height: 15rpx;
      background-color: $main-bg;
    }

    .examine-flow-container {
      padding: 30rpx;
      .flow-item {
        position: relative;
        margin-bottom: 20rpx;
        &::after {
          content: '';
          position: relative;
          left: 52rpx;
          top: 10rpx;
          width: 1rpx;
          height: 60rpx;
          border-left: 1rpx dashed #ccc;
          display: block;
        }
        &:last-child::after {
          display: none;
        }
      }
    }
  }

  .footer-region {
    background-color: white;
    width: 100%;
    height: 120rpx;
    padding: 0 30rpx;
    border-top: 1rpx solid $border-color;

    .footer-box {
      width: 100%;
      height: 100%;
      @include center;

      .footer-button {
        width: 210rpx;
        height: 72rpx;
        font-size: $wk-font-base;
        border-radius: 6rpx;
        @include center;
      }

      .refuse {
        background-color: $error;
        color: white;
        margin-right: 30rpx;
      }

      .pass {
        background-color: $theme-color;
        color: white;
      }

      .recall {
        color: $gray;
        background-color: #F5F5F5;
        margin-right: 30rpx;
      }
    }
  }
}
</style>
