<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"
      @scrolltolower="handleScrollTolower">
      <view class="header-top">
        <view class="bg linear-gradient" />
        <view class="card">
          <view class="title-cell">
            <image :src="$static('images/crm/gray_customer.png')" class="type-icon" />
            <view class="title-text">
              <text class="text">
                {{ detailData.customerName || '' }}
              </text>
              <text v-if="detailData.status === 2" class="wk wk-lock" />
            </view>
            <view :class="detailData.dealStatus === 1 ? 'success' : 'info'" class="title-status">
              <text>{{ detailData.dealStatus === 1 ? '已成交' : '未成交' }}</text>
            </view>
          </view>

          <view class="main-info">
            <view class="info-item">
              负责人：{{ detailData.ownerUserName || '&#45;&#45;' }}
            </view>
            <view class="info-item">
              联系方式：{{ detailData.mobile || '&#45;&#45;' }}
            </view>
          </view>

          <image
            v-if="detailData.mobile"
            :src="$static('images/icon/call_up.png')"
            class="call-up"
            @click="ringUp(detailData.mobile)" />

          <view class="main-info">
            <flow-progress
              v-if="detailData"
              :type="comType"
              :detail-id="id"
              :detail-data="detailData" />
          </view>
        </view>
      </view>

      <view ref="wkTabs" 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,
    Transfer,
    Lock,
    UpdateCustomerByIds,
    DeleteByIds,
    SetDealStatus
  } from 'API/crm/customer'
  import {
    QueryById as MainUser
  } from 'API/crm/concat'
  import {
    PoolNameList
  } from 'API/crm/pool'

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

  import detailMixins from '../mixins/detail.js'

  export default {
    name: 'CustomerDetail',
    components: {
      DetailBaseInfo,
      DetailActivityList,
      DetailAbout,

      FlowProgress
    },
    mixins: [detailMixins],
    data() {
      return {
        comType: 'crm_customer',
        mainUserInfo: {},

        commandList: [
          {
            label: '转移',
            imgIcon: 'transfer',
            auth: 'crm.customer.transfer',
            value: 'transfer'
          },
          {
            label: '锁定',
            imgIcon: 'lock',
            auth: 'crm.customer.lock',
            value: 'lock'
          },
          {
            label: '放入公海',
            imgIcon: 'putinpool',
            auth: 'crm.customer.putinpool',
            value: 'putinpool'
          },
          {
            label: '更改成交状态',
            imgIcon: 'dealStatus',
            auth: 'crm.customer.dealStatus',
            value: 'dealStatus'
          },
          {
            label: '编辑',
            imgIcon: 'update',
            auth: 'crm.customer.update',
            value: 'update'
          },
          {
            label: '删除',
            imgIcon: 'delete',
            auth: 'crm.customer.delete',
            value: 'delete'
          },
        ]
      }
    },
    methods: {
      getDetail() {
        QueryById({
          customerId: this.id
        }).then(res => {
          console.log('detail: ', res)
          this.detailData = res
          this.commandList[1].label = res.status === 2 ? '解锁' : '锁定'
          this.commandList[1].imgIcon = res.status === 2 ? 'unlock' : 'lock'
          this.getMainUser()
        }).catch(() => {
          this.goBack()
        })
      },

      /**
       * 获取首要联系人详情
       */
      getMainUser() {
        if (!this.detailData.contactsId) return
        MainUser({
          contactsId: this.detailData.contactsId
        }).then(res => {
          if (!res.hasOwnProperty('dataAuth')) {
            this.mainUserInfo = res
          }
        }).catch()
      },

      handleCommand(command) {
        this.commandValue = command.value
        switch (command.value) {
        case 'transfer':
          this.handleToChangeOwnerUser()
          break
        case 'lock':
          this.dialogMsg = `您确定要${command.label}该客户吗？`
          this.$refs.popup.open()
          break
        case 'putinpool':
          this.handleToChoosePool()
          break
        case 'dealStatus':
          this.dialogMsg = `您确定要将该客户更改为${this.detailData.dealStatus === 0 ? '已成交' : '未成交'}吗？`
          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 'lock':
          this.lockCustomer()
          break
        case 'dealStatus':
          this.changeDealStatus()
          break
        case 'delete':
          this.deleteCustomer()
          break
        }
        next()
      },

      handleToChoosePool() {
        const bridge = getApp().globalData.selectedValBridge
        const that = this
        bridge.options = {
          guid: this.guid,
          title: '选择公海',
          defaultVal: [],
          maxlength: 1,
          request: PoolNameList,
          config: {
            labelField: 'poolName',
            valueField: 'poolId',
            checkFn: ({ data }) => {
              if (data.length === 0) {
                this.$toast('请选择要放入的公海')
                return false
              }
              return true
            }
          }
        }
        uni.$on('selected-options', this.selectedPool)
        this.$Router.navigateTo('/pages_common/selectList/options')
      },

      selectedPool(data) {
        if (this.guid === data.guid) {
          if (data.data.length > 0) {
            this.$nextTick(function() {
              this.seasCustomer(data.data[0])
            })
          }
        }
        uni.$off('selected-options')
      },

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

      toContactsDetail() {
        if (!this.mainUserInfo.contactsId) return
        this.$Router.navigateTo({
          url: '/pages_crm/contacts/detail',
          query: {
            id: this.mainUserInfo.contactsId
          }
        })
      },

      /**
       * 锁定/解锁
       */
      lockCustomer() {
        let params = {
          ids: this.id,
          status: this.detailData.status === 1 ? 2 : 1
        };
        Lock(params).then(() => {
          this.$toast(this.detailData.status === 1 ? '锁定成功' : '解锁成功')
          this.getDetail()
        }).catch()
      },

      /**
       * 更改成交状态
       */
      changeDealStatus() {
        SetDealStatus({
          ids: this.id,
          dealStatus: this.detailData.dealStatus === 0 ? 1 : 0
        }).then(() => {
          this.$toast('修改成功')
          this.getDetail()
        }).catch()
      },

      /**
       * 放入公海
       */
      seasCustomer(data) {
        UpdateCustomerByIds({
          ids: [this.id],
          poolId: data.poolId
        }).then(() => {
          this.$toast('放入公海成功')
          this.$refreshAndToPrev(this)
        })
      },

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

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

	.header-top {
		.card {
			.title-status {
				&.success {
					color: #FFFFFF;
					background-color: #FF8700;
				}
				&.info {
					color: #BBBBBB;
					background-color: #EEEEEE;
				}
			}

			.main-info {
				margin-bottom: 25rpx;
			}

			.call-up {
				position: absolute;
				right: 20rpx;
				top: 105rpx;
				width: 116rpx;
				height: 116rpx;
			}
		}
	}
</style>
