<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="handleSave">
          保存
        </button>
        <!-- #endif -->
      </wk-nav-bar>

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

          <view class="cell-box">
            <view class="cell">
              <view class="cell-left">
                关联销售简报
              </view>
              <view class="cell-right">
                <switch
                  :checked="concatSale"
                  color="#007AFF"
                  class="switch-core"
                  @change="concatSale = !concatSale" />
              </view>
            </view>
          </view>

          <view class="cell-box">
            <view class="cell" @click="handleAddFile()">
              <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 class="cell-box">
            <view class="cell" @click="handleAddFile('img')">
              <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="getRelevancePopOptions">
              <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="handleDeleteRelevance" />
          </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 { AddOrUpdate, QueryById } from 'API/oa/journal'
  import { FileDeleteById } from 'API/file'

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

  import Fields from '@/utils/fields.js'
  import WkFile from '@/utils/file.js'
  import { guid } from '@/utils/lib.js'

  export default {
    name: 'AddLog',
    components: {
      RelevanceSection
    },
    data() {
      return {
        id: null,
        categoryId: null,
        guid: null,
        routerQuery: {},
        batchId: guid(),

        concatSale: true,
        popOptions: [],

        fileList: [],
        imgList: [],

        customerList: [],
        contactsList: [],
        businessList: [],
        contractList: [],
      }
    },
    computed: {
      navTitle() {
        const str1 = this.id ? '编辑' : '写'
        const str2 = {
          1: '日报',
          2: '周报',
          3: '月报'
        }[this.categoryId] || '日志'
        return str1 + str2
      },
      fieldArr() {
        const arr = {
          1: ['今日', '明日'],
          2: ['本周', '下周'],
          3: ['本月', '下月']
        }[this.categoryId]

        return [
          new Fields({
            name: arr[0] + '工作内容',
            formType: 'textarea',
            fieldName: 'content',
            value: '',
          }),
          new Fields({
            name: arr[1] + '工作内容',
            formType: 'textarea',
            fieldName: 'tomorrow',
            value: '',
          }),
          new Fields({
            name: '遇到的问题',
            formType: 'textarea',
            fieldName: 'question',
            value: '',
          }),
          new Fields({
            name: '发送给谁',
            formType: 'user',
            fieldName: 'sendUserIds',
            value: '',
          })
        ]
      },

      showRelevance() {
        return this.customerList.length > 0 ||
          this.contactsList.length > 0 ||
          this.businessList.length > 0 ||
          this.contractList.length > 0
      },
      relevanceData() {
        return {
          customerList: this.customerList || [],
          contactsList: this.contactsList || [],
          businessList: this.businessList || [],
          contractList: this.contractList || [],
        }
      }
    },
    created() {
      this.guid = this.$guid()
    },
    onUnload() {
      getApp().globalData.selectedValBridge = {}
    },
    onLoad(options) {
      this.routerQuery = options || {}
      this.id = this.routerQuery.id || null
      this.categoryId = Number(this.routerQuery.type) || null
      if (![1, 2, 3].includes(this.categoryId)) {
        this.categoryId = 1
      }
      if (this.id) {
        this.getDetail()
      }
    },
    methods: {
      getDetail() {
        QueryById({logId: this.id}).then(response => {
          let detailData = response || {}

          this.imgList = detailData.img || []
          this.fileList = detailData.file || []
          this.batchId = detailData.batchId

          let keys = ['customerList', 'contactsList', 'businessList', 'contractList']
          keys.forEach(key => {
            this[key] = detailData[key] || []
          })

          this.$nextTick(() => {
            this.$refs.form.setForm({
              content: detailData.content,
              tomorrow: detailData.tomorrow,
              question: detailData.question,
              sendUserIds: detailData.sendUserList || []
            })
          })
        }).catch()
      },

      /**
       * 添加附件/图片
       * @param {Object} type
       */
      handleAddFile(type) {
        const params = {}
        if (type === 'img') {
          params.type = type
        }
        if (this.batchId) {
          params.batchId = this.batchId
        }
        const fileUpload = new WkFile(params)
        fileUpload.choose().then(data => {
          console.log('upload res: ', data)
          if (type === 'img') {
            this.imgList = this.imgList.concat(data)
          } else {
            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()
      },

      /**
       * 弹出选择关联业务
       */
      getRelevancePopOptions() {
        const map = [
          { label: '客户', value: 'customer', auth: 'crm.customer.index' },
          { label: '联系人', value: 'contacts', auth: 'crm.contacts.index' },
          { label: '商机', value: 'business', auth: 'crm.business.index' },
          { label: '合同', value: 'contract', auth: 'crm.contract.index' }
        ]
        this.popOptions = map.filter(o => {
          return this.$auth(o.auth)
        })
        this.$refs.popup.open()
      },

      /**
       * 去选择关联项
       * @param {Object} opt
       */
      handleSelectOptions(opt) {
        this.$refs.popup.close()
        console.log(opt)
        const bridge = getApp().globalData.selectedValBridge
        bridge[opt.value] = {
          guid: this.guid,
          defaultVal: this[`${opt.value}List`] || []
        }
        if (opt.value !== 'user') {
          uni.$on('selected-relevance', this.selectedRelevance)
          this.$Router.navigateTo({
            url: '/pages_common/selectList/relevance',
            query: {
              type: opt.value
            }
          })
        } else {
          uni.$on('selected-user', this.selectedUser)
          this.$Router.navigateTo('/pages_common/selectList/user')
        }
      },

      /**
       * 选中关联项
       * @param {Object} data
       */
      selectedRelevance(data) {
        if (this.guid === data.guid) {
          this[`${data.type}List`] = data.data
        }
        uni.$off('selected-relevance')
      },

      /**
       * 删除关联项
       * @param {string} type
       * @param {number} index
       */
      handleDeleteRelevance(type, index) {
        this[`${type}List`].splice(index, 1)
      },

      handleSave() {
        this.$refs.form.getForm().then(form => {
          form = form.entity
          if (
            this.$isEmpty(form.content) &&
            this.$isEmpty(form.tomorrow) &&
            this.$isEmpty(form.question)
          ) {
            this.$toast('请填写日志内容')
            return
          }
          form = {
          ...form,
          categoryId: this.categoryId,
          batchId: this.batchId
          }

          form.customerIds = this.customerList.map(o => o.customerId).join(',') || ''
          form.contactsIds = this.contactsList.map(o => o.contactsId).join(',') || ''
          form.contractIds = this.contractList.map(o => o.contractId).join(',') || ''
          form.businessIds = this.businessList.map(o => o.businessId).join(',') || ''

          if (this.concatSale) {
            form.getBulletin = 1
          }
          if (this.id) {
            form.logId = this.id
          }
          console.log('save: ', form)
          AddOrUpdate(form).then(() => {
            this.$toast(this.id ? '修改成功' : '添加成功')
            this.$refreshAndToPrev(this)
          }).catch(() => {})
        }).catch(() => {})
      }
    }
  }
</script>

<style scoped lang="scss">
.main-container {
  .container {
    flex: 1;
    overflow: hidden;
    background-color: white;
    padding-bottom: 30rpx;

    .scroll-content {
      width: 100%;
      height: 100%;
      overflow: auto;
    }

    .cell-box {
      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;
          }
        }
        .switch-core {
          transform: translateX(10%) scale(0.8);
        }
        .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;
          }
        }
      }
    }
  }
}
</style>
