<template>
  <view class="uni-app">
    <view class="status-bar" />
    <view class="main-container">
      <wk-nav-bar :title="navTitle" :refresh-prev="refreshPrevPage" />
			
      <view class="container">
        <view class="flow-list">
          <view
            v-for="(item, index) in flowList"
            :key="index"
            class="flow-list-item">
            <view
              :class="{active: item.isOver}"
              class="icon-box" />
						
            <view class="content">
              <view class="content-title">
                <text class="content-title-text">
                  {{ item.flowName }}
                </text>
                <text v-if="item.rate" class="content-title-desc">
                  （赢单率10%）
                </text>
              </view>
              <view
                class="content-body"
                @click="handleToStageDetail(item)">
                <template v-if="!item.flowType">
                  <image :src="$static('images/icon/money_active.png')" class="icon" />
                  <text class="text">
                    阶段信息
                  </text>
                </template>
              </view>
            </view>
          </view>
        </view>
      </view>
			
      <view
        v-if="flowData.finalStatus === 0"
        class="footer-btn-group">
        <button
          class="button choose-product-btn"
          @click="handleToChangeFlow">
          推进阶段流程
        </button>
      </view>
    </view>
		
    <uni-popup
      ref="popup"
      type="bottom" 
      radius="20rpx 20rpx 0 0">
      <view class="popup">
        <view class="header">
          <view class="back-icon" @click="handlePopupClose">
            <text class="wk wk-close icon" />
          </view>
          <view class="title" />
          <view class="save-btn" @click="handlePopupConfirm">
            确定
          </view>
        </view>
				
        <view class="options-group">
          <view
            v-for="(item, index) in flowList"
            :key="index"
            :class="{active: index === activeIndex}"
            class="options-group-item"
            @click="handleOptionClick(index, item)">
            <text class="text">
              {{ item.flowName }}
            </text>
            <text v-if="activeIndex === index" class="wk wk-check icon" />
          </view>
        </view>
      </view>
    </uni-popup>
		
    <uni-popup ref="popupDialog" type="dialog">
      <uni-popup-dialog
        :content="dialogMsg"
        type="warning"
        @confirm="handleDialogConfirm" />
    </uni-popup>
  </view>
</template>

<script>
  import {
    QueryFlowSettingList,
    UpdateFlowDataStatusAPI
  } from '@/api/crm/flow.js'
  import { crmEnum } from './enum.js'
  import { deepCopy } from '@/utils/lib.js'
	
  export default {
    name: 'CustomFlowList',
    data() {
      return {
        routerQuery: {},
				
        flowData: {},
        flowList: [],
				
        activeIndex: null,
				
        dialogMsg: '',
        refreshPrevPage: false,
        refreshPage: false
      }
    },
    computed: {
      crmType() {
        return (this.routerQuery.type || '').replace('crm_', '')
      },
			
      navTitle() {
        return `${crmEnum[this.crmType].label}流程详情`
      }
    },
    onLoad(options) {
      this.routerQuery = options || {}
      this.getFlowList()
    },
    onShow() {
      this.refreshNowPage()
    },
    onBackPress(evt) {
      if (evt.from === 'backbutton' && this.refreshPrevPage) {
        this.$refreshAndToPrev(this)
        return true // 返回值为 true 时，表示不执行默认的返回
      }
      return false
    },
    methods: {
      refreshNowPage() {
        console.log('refresh now page: ', this.refreshPage)
        if (this.refreshPage) {
          this.$nextTick(function() {
            console.log('refresh')
            this.refreshPage = false
            this.refreshPrevPage = true
            this.getFlowList()
          })
        }
      },
			
      /**
       * 获取流程信息
       */
      getFlowList() {
        const type = crmEnum[this.crmType].type

        QueryFlowSettingList({
          label: type,
          typeId: this.routerQuery.typeId
        }).then(res => {
          this.flowData = res
          this.formatList()
        }).catch(() => {})
      },
			
      /**
       * 格式化流程数据
       */
      formatList() {
        const list = deepCopy(this.flowData.settingList)
        let flag = false
        list.forEach(item => {
          item.isOver = !flag
          if (item.id === this.flowData.dataId) {
            flag = true
          }
        })

        const temp = {
          examineRecordId: null,
          examineStatus: null,
          flowName: null,
          id: null,
          rate: null,
          status: 0,
          isOver: false
        }
				
        const successText = this.crmType === 'business' ? '赢单' : this.flowData.successName
        const failText = this.crmType === 'business' ? '输单' : this.flowData.failedName

        list.push({
					...temp,
					id: 1,
          isOver: this.flowData.finalStatus === 1,
					flowName: successText,
					flowType: 'success'
        })
        list.push({
					...temp,
					id: 2,
          isOver: this.flowData.finalStatus > 1,
					flowName: failText,
					flowType: 'fail'
        })
        this.flowList = list
      },
			
      /**
       * 查看阶段详情
       */
      handleToStageDetail(item) {
        // 选择的阶段Id等于当前阶段、有审批当前阶段审核状态为未通过、无审批当前状态为未完成允许编辑修改
        const editAuth = item.id === this.flowData.dataId &&
          [0, 2, 4].includes(item.examineStatus) &&
          item.status === 0

        const url = editAuth ? '/pages_crm/customFlowUpdate' : '/pages_crm/customFlowDetail'
        this.$Router.navigateTo({
          url,
          query: {
						...this.routerQuery,
						id: item.id
          }
        })
      },
			
      handleToChangeFlow() {
        this.activeIndex = null
        this.$refs.popup.open()
      },
			
      /**
       * 选择阶段
       * @param {Object} index
       */
      handleOptionClick(index) {
        this.activeIndex = index
      },
			
      /**
       * 关闭阶段选择
       */
      handlePopupClose() {
        this.$refs.popup.close()
      },
			
      /**
       * 确定选择阶段
       */
      handlePopupConfirm() {
        this.dialogMsg = '确定要推进至' + this.flowList[this.activeIndex].flowName + '？'
        this.$refs.popupDialog.open()
      },

      /**
       * 推进阶段
       */
      handleDialogConfirm() {
        const item = this.flowList[this.activeIndex]
        const flag = ['success', 'fail'].includes(item.flowType)

        // console.log('推进阶段: ', {
        // 	dataId: flag ? this.flowData.dataId : item.id,
        // 	finalStatus: flag ? item.id : ''
        // })
				
        UpdateFlowDataStatusAPI({
          dataId: flag ? this.flowData.dataId : item.id,
          finalStatus: flag ? item.id : ''
        }).then(res => {
          this.activeIndex = null
          this.refreshPrevPage = true
          this.getFlowList()
          this.handlePopupClose()
        }).catch(() => {})
				
        this.$refs.popupDialog.close()
      }
    }
  }
</script>

<style lang="scss" scoped>
	.container {
		flex: 1;
		background-color: white;
		overflow: auto;
		padding: 40rpx 30rpx;
		
		.flow-list {
			.flow-list-item {
				position: relative;
				padding: 10rpx 0;
				display: flex;
				align-items: flex-start;
				justify-content: flex-start;
				
				&::before {
					position: absolute;
					top: 38rpx;
					left: 17rpx;
					content: '';
					width: 1rpx;
					height: 100%;
					border-left: 1rpx dashed $light;
					display: block;
				}
				&:last-child::before {
					display: none;
				}
				
				.icon-box {
					position: relative;
					z-index: 1;
					width: 35rpx;
					height: 35rpx;
					background-color: white;
					border: 1rpx solid $light;
					border-radius: 50%;
					@include center;
					&::before {
						content: '';
						width: 18rpx;
						height: 18rpx;
						background-color: white;
						border-radius: 50%;
						display: block;
					}
					
					&.active {
						border-color: $warning;
						background-color: $warning;
					}
				}
				
				.content {
					width: 100%;
					height: 136rpx;
					border-bottom: 1rpx solid $border-color;
					margin-left: 30rpx;

					.content-title {
						width: 100%;
						.content-title-text {
							font-weight: 500;
							font-size: $wk-font-base;
						}
						.content-title-desc {
							font-size: $wk-font-mini;
							color: $light;
						}
					}
					.content-body {
						color: $theme-color;
						font-size: $wk-font-base;
						margin-top: 15rpx;
						.icon {
							width: 28rpx;
							height: 28rpx;
							vertical-align: middle;
							margin-right: 15rpx;
						}
						.text {
							vertical-align: middle;
						}
					}
				}
			}
		}
	}
	
	.popup {
		padding-bottom: 36rpx;
		.header {
			position: relative;
			width: 100%;
			height: 80rpx;
			@include center;
			.back-icon, .save-btn {
				position: absolute;
				top: 0;
				height: 100%;
				font-size: $wk-font-medium;
				color: $gray;
				padding: 20rpx;
				@include center;
			}
			.back-icon {
				left: 16rpx;
				transform: rotate(180deg);
				.icon {
					font-size: inherit;
				}
			}
			.save-btn {
				right: 16rpx;
				color: $theme-color;
				font-size: $wk-font-base;
			}
		}
		
		.options-group {
			width: 100%;
			padding: 0 36rpx;
			.options-group-item {
				color: $dark;
				font-size: $wk-font-base;
				border-bottom: 1rpx solid $border-color;
				padding: 22rpx 0;
				@include left;
				.text {
					flex: 1;
				}
				.icon {
					font-size: $wk-font-medium;
					color: inherit;
					line-height: 1;
				}
				&.active {
					color: $theme-color;
				}
			}
		}
	}
</style>
