<template>
  <view class="uni-app">
    <view class="status-bar" />
    <view class="main-container">
      <wk-nav-bar :title="navTitle">
        <!-- #ifndef MP-WEIXIN -->
        <button class="button white-btn" @click="handleConfirm">
          确定
        </button>
        <!-- #endif -->
      </wk-nav-bar>

      <view class="search-wrapper">
        <wk-search-box class="search-box" @search="handleSearch" />
        <view
          v-if="showCreate"
          class="new-btn"
          @click="handleAdd">
          新增
        </view>
      </view>

      <wk-scroll-view
        :status="listStatus"
        :refresh="false"
        class="list-scroll"
        @loadmore="getList()">
        <wk-select-list
          v-if="listData.length > 0"
          v-model="defaultVal"
          :list="listData"
          :label-field="typeObj.labelField"
          :value-field="typeObj.valueField"
          :max="bridge.maxlength"
          @change="handleChange" />
      </wk-scroll-view>

      <!-- #ifdef MP-WEIXIN -->
      <view class="footer-btn-group">
        <button class="button" @click="handleConfirm">
          确定
        </button>
      </view>
      <!-- #endif -->
    </view>
  </view>
</template>

<script>
	/**
	 * 选择关联项
	 * @pageEvent {Function} selected-relevance 选中的关联项发生变化后触发
	 */
  import {GetList as crmCustomerIndex} from 'API/crm/customer'
  import {GetList as crmContactsIndex} from 'API/crm/concat'
  import {GetList as crmBusinessIndex} from 'API/crm/business'
  import {GetList as crmContractIndex} from 'API/crm/contract'

  export default {
    name: 'RelevanceChoose',
    data() {
      return {
        listData: [],
        selectedList: [],
        defaultVal: [],

        params: {
          page: 0,
          limit: 15,
          search: ''
        },
        listStatus: 'more',

        reqMap: {
          customer: crmCustomerIndex,
          contacts: crmContactsIndex,
          business: crmBusinessIndex,
          contract: crmContractIndex,
        },

        routerQuery: {},
        bridge: {}, // 附加参数
        refreshPage: false
      }
    },
    computed: {
      typeObj() {
        if (!this.routerQuery || !this.routerQuery.type) return {}

        const obj = {
          customer: {labelField: 'customerName', valueField: 'customerId', title: '客户'},
          contacts: {labelField: 'name', valueField: 'contactsId', title: '联系人'},
          business: {labelField: 'businessName', valueField: 'businessId', title: '商机'},
          contract: {labelField: 'name', valueField: 'contractId', title: '合同'},
        }[this.routerQuery.type] || {}

        if (this.bridge && this.bridge.config) {
          const config = this.bridge.config || {}
          return {
            labelField: config.labelField || obj.labelField,
            valueField: config.valueField || obj.valueField,
            title: this.bridge.title || obj.title,
          }
        } else {
          return obj
        }
      },
      navTitle() {
        if (this.bridge.title) return this.bridge.title
        return ('选择' + this.typeObj.title) || '选择关联项'
      },
      showCreate() {
        const type = this.routerQuery.type || null
        let authFlag = false
        if (type) {
          authFlag = this.$auth(`crm.${type}.save`)
        }
        return Boolean(this.bridge.config && this.bridge.config.showCreate && authFlag)
      }
    },
    onLoad(options) {
      this.routerQuery = options || {}
      this.bridge = getApp().globalData.selectedValBridge[options.type] || {}
      // console.log('bridge: ', bridge)
      // console.log('routerQuery: ', this.routerQuery)
      this.defaultVal = this.bridge.defaultVal || []
      this.handleChange(this.defaultVal)
      this.getList()
    },
    onShow() {
      if (this.refreshPage) {
        this.$nextTick(function() {
          this.refreshPage = false
          this.params.page = 0
          this.params.search = ''
          this.getList({}, true)
        })
      }
    },
    onUnload() {
      getApp().globalData.selectedValBridge = {}
    },
    methods: {
      /**
       * 获取选项列表
       */
      getList() {
        if (!this.$isEmpty(this.bridge.list)) {
          this.listData = this.bridge.list
          return
        }

        if (!this.routerQuery || !this.routerQuery.type) return {}
        const type = this.routerQuery.type // 类型
        const otherParams = this.bridge.params || {} // 路由附加参数
        this.params.page++

        const request = this.bridge.request || this.reqMap[type]
        if (!request) return

        this.listStatus = 'loading'
        const params = {
					...this.params,
					...otherParams
        }
        if (params.pageType === 0) {
          delete params.page
          delete params.limit
        }
        request(params).then(res => {
          if (this.params.page === 1) {
            this.listData = []
          }
          console.log(res.list)
          this.listData = this.listData.concat(res.list)
          this.listStatus = res.lastPage ? 'noMore' : 'more'
        }).catch(() => {
          this.listStatus = 'more'
        })
      },

      /**
       * 搜索
       * @param {String} keyword
       */
      handleSearch(keyword) {
        this.params.search = keyword
        this.params.page = 0
        this.getList()
      },

      /**
       * 保存记录选择的项
       * @param {Object} data
       */
      handleChange(data) {
        this.selectedList = data
      },

      /**
       * 新建
       */
      handleAdd() {
        const type = this.routerQuery.type || null
        if (!type) return
        this.$Router.navigateTo({
          url: `/pages_crm/${type}/create`
        })
      },

      /**
       * 确认选择，通知上一级页面，关联项已经选择
       */
      handleConfirm() {
        this.selectedList.forEach((item, index) => {
          item.contactsName = item.name
        })
        const data = {
          type: this.routerQuery.type,
          guid: this.bridge.guid,
          bridge: this.bridge,
          data: this.selectedList
        }
        if (this.bridge.config && this.bridge.config.checkFn) {
          const res = this.bridge.config.checkFn(data)
          if (!res) return
        }
        uni.$emit('selected-relevance', data)
        this.$Router.navigateBack()
      }
    }
  }
</script>

<style scoped lang="scss">
	.main-container {
		display: flex;
		flex-direction: column;
		overflow: hidden;

		.search-wrapper {
			padding: 0 3%;
			@include left;
			.search-box {
				flex: 1;
				padding-left: 0;
				padding-right: 0;
			}
			.new-btn {
				font-size: $wk-font-base;
				color: $theme-color;
				margin-left: 20rpx;
			}
		}

		.list-scroll {
			flex: 1;
			overflow: hidden;
			padding-bottom: 20rpx;
		}
	}
</style>
