<template>
  <view class="uni-app">
    <view class="status-bar" />
    <view class="main-container">
      <wk-nav-bar title="写跟进">
        <!-- #ifndef MP-WEIXIN -->
        <button
          class="button white-btn"
          @click="handleSave">
          保存
        </button>
        <!-- #endif -->
      </wk-nav-bar>

      <view class="container">
        <view class="scroll-content">
          <wk-form ref="form" :fields="fieldArr" />

          <view class="textarea-wrapper">
            <view class="title">
              跟进内容
            </view>
            <view class="content">
              <textarea
                v-model="content"
                maxlength="500"
                placeholder="请填写跟进记录内容"
                placeholder-class="wk-placeholder"
                class="textraea-core" />
            </view>
          </view>

          <view class="cell-box">
            <view class="cell" @click="addPic">
              <view class="cell-left">
                <image :src="$static('images/icon/image.png')" class="pic-icon" />
                图片
              </view>
              <view class="cell-right add-icon">
                <text class="wk wk-plus" />
              </view>
            </view>

            <wk-image-content
              v-if="imgList.length > 0"
              :list="imgList"
              show-delete
              @delete="deleteImg" />
          </view>

          <view class="cell-box">
            <view class="cell" @click="addAdjunct">
              <view class="cell-left">
                <image :src="$static('images/icon/clip.png')" class="pic-icon" />
                附件
              </view>
              <view class="cell-right add-icon">
                <text class="wk wk-plus" />
              </view>
            </view>

            <wk-file-content
              v-if="fileList.length > 0"
              :list="fileList"
              show-delete
              @delete="deleteFile" />
          </view>

          <view
            v-if="type === 'crm_customer'"
            class="cell-box">
            <view class="cell" @click="handlePopShow">
              <view class="cell-left">
                <image :src="$static('images/icon/relate.png')" class="pic-icon" />
                关联业务
              </view>
              <view class="cell-right add-icon">
                <text class="wk wk-plus" />
              </view>
            </view>

            <relevance-section
              v-if="showRelevance"
              :is-add="true"
              :relevance-data="relevanceData"
              @delete="relevanceDelete" />
          </view>
        </view>
      </view>

      <!-- #ifdef MP-WEIXIN -->
      <view class="footer-btn-group">
        <button class="button" @click="handleSave">
          保存
        </button>
      </view>
      <!-- #endif -->
    </view>

    <uni-popup ref="popup">
      <view class="pop-wrapper">
        <view
          v-for="(item, index) in popOptions"
          :key="index"
          class="pop-item"
          @click.stop="handleSelectOptions(item)">
          {{ item.label }}
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
  import {
    GetCrmActivityPageList,
    AddCrmActivityRecord,
    QueryRecordOptions
  } from 'API/crm/crmActivity'
  import { FileDeleteById } from 'API/file'
  import { QueryContacts, QueryBusiness } from 'API/crm/customer.js'

  import RelevanceSection from '@/components/base/relevance-section.vue'

  import Fields from '@/utils/fields.js'
  import WkFile from '@/utils/file.js'
  import moment from 'moment'

  export default {
    name: 'AddRecord',
    components: {
      RelevanceSection
    },
    data() {
      return {
        guid: null,
        type: '',
        id: '',

        activityMap: {
          crm_leads: 1,
          crm_customer: 2,
          crm_contacts: 3,
          crm_product: 4,
          crm_business: 5,
          crm_contract: 6,
          crm_receivables: 7
        },
        fieldArr: [
          new Fields({
            name: '记录类型',
            formType: 'select',
            fieldName: 'category',
            setting: [],
            isNull: 1,
            value: '',
          }),
          new Fields({
            name: '下次联系时间',
            formType: 'datetime',
            fieldName: 'nextTime',
            isNull: 0,
            value: null
          })
        ],

        batchId: '',
        content: '', // 跟进内容
        imgList: [], // 图片列表
        fileList: [], // 附件列表
        contactsList: [], // 联系人列表
        businessList: [], // 商机列表

        controlList: [], // 底部控制按钮列表

        popOptions: [
          { label: '联系人', value: 'contacts' },
          { label: '商机', value: 'business' },
        ]
      }
    },
    computed: {
      showRelevance() {
        return this.contactsList.length > 0 ||
          this.businessList.length > 0
      },
      relevanceData() {
        return {
          contactsList: this.contactsList,
          businessList: this.businessList
        }
      }
    },
    onLoad(options) {
      this.type = options.type
      this.id = options.id
      this.guid = this.$guid()
      this.getRecordOptions()
    },
    methods: {
      getRecordOptions() {
        QueryRecordOptions().then(res => {
          this.$set(this.fieldArr[0], 'setting', res)
          this.$set(this.fieldArr[0], 'value', [{ label: res[0], value: res[0]}])
        }).catch()
      },

      /**
       * 添加图片
       */
      addPic() {
        const params = {
          type: 'img'
        }
        if (this.batchId) {
          params.batchId = this.batchId
        }
        const fileUpload = new WkFile(params)
        fileUpload.choose().then(data => {
          console.log('upload res: ', data)
          this.batchId = data[0].batchId
          this.imgList = this.imgList.concat(data)
        })
      },

      /**
       * 添加附件
       */
      addAdjunct() {
        const params = {}
        if (this.batchId) {
          params.batchId = this.batchId
        }
        const fileUpload = new WkFile(params)
        fileUpload.choose().then(data => {
          console.log('upload res: ', data)
          this.batchId = data[0].batchId
          this.fileList = this.fileList.concat(data)
        })
      },

      /**
       * 删除图片
       * @param {Number} index
       */
      deleteImg(index) {
        const fileId = this.imgList[index].fileId
        this.imgList.splice(index, 1)
        FileDeleteById({id: fileId}).then().catch()
      },

      /**
       * 删除附件
       * @param {Number} index
       */
      deleteFile(index) {
        const fileId = this.fileList[index].fileId
        this.fileList.splice(index, 1)
        FileDeleteById({id: fileId}).then().catch()
      },

      handlePopShow() {
        this.$refs.popup.open()
      },

      handleSelectOptions(item) {
        this.$refs.popup.close()
        switch (item.value) {
        case 'contacts':
          this.hanldeToChooseRevelance('contacts')
          break
        case 'business':
          this.hanldeToChooseRevelance('business')
          break
        }
      },

      hanldeToChooseRevelance(type) {
        const bridge = getApp().globalData.selectedValBridge
        bridge[type] = {
          guid: this.guid,
          defaultVal: this[`${type}List`] || [],
          params: {
            customerId: this.id
          },
          request: type === 'contacts' ? QueryContacts : QueryBusiness
        }
        uni.$once('selected-relevance', this.selectedRelevance)
        this.$Router.navigateTo({
          url: '/pages_common/selectList/relevance',
          query: {
            type: type
          }
        })
      },

      selectedRelevance(data) {
        if (this.guid === data.guid) {
          this[`${data.type}List`] = data.data
          console.log('data: ', this)
        }
        uni.$off('selected-relevance')
      },

      relevanceDelete(type, index) {
        this[`${type}List`].splice(index, 1)
      },

      handleSave() {
        this.$refs.form.getForm().then(form => {
          const params = form.entity
          if (!this.content) {
            this.$toast('跟进内容不能为空')
            return
          }
          if (this.type === 'crm_customer') {
            params.businessIds = this.businessList.map(item => {
              return item.businessId
            })

            params.contactsIds = this.contactsList.map(item => {
              return item.contactsId
            })
          }
          params.content = this.content
          params.activityTypeId = this.id
          params.activityType = this.activityMap[this.type]
          // params.category = params.category instanceof Array ? params.category[0] : params.category
          params.batchId = this.batchId || ''
          console.log('save: ', params)

          AddCrmActivityRecord(params).then(res => {
            this.$toast('添加成功')
            this.$refreshAndToPrev(this)
          }).catch()
        }).catch()
      }
    }
  }
</script>

<style scoped lang="scss">
.container {
  flex: 1;
  margin-top: 20rpx;
  overflow: hidden;
  .scroll-content {
    width: 100%;
    height: 100%;
    overflow: auto;
    .cell-box {
      background-color: white;
      padding: 15rpx 32rpx;
      .cell {
        width: 100%;
        font-size: 30rpx;
        @include left;
        .cell-left {
          flex: 1;
          @include left;
          .pic-icon {
            width: 38rpx;
            height: 38rpx;
            margin-right: 15rpx;
          }
        }
        .add-icon {
          width: 38rpx;
          height: 38rpx;
          background-color: #E1E1E1;
          border-radius: 50%;
          @include center;
          .wk {
            font-size: $wk-font-mini;
            line-height: normal;
            color: white;
          }
        }
      }
    }

    .textarea-wrapper {
      background-color: white;
      margin-top: 20rpx;
      padding: 0 30rpx;
      .title {
        font-size: 30rpx;
        padding: 24rpx 0;
      }
      .textraea-core {
        width: 100%;
        height: 200rpx;
        font-size: 28rpx;
      }
    }

    .file-section, .revelance-section {
      background-color: white;
      padding: 0 30rpx 10rpx;
      overflow: hidden;
    }
  }
}
</style>
