<template>
  <view class="travel-item">
    <view class="travel-item-header">
      <text class="title">
        {{ title }}明细（{{ index + 1 }}）
      </text>
      <text v-if="length > 1" class="control" @click="handleDelete(index)">
        删除
      </text>
    </view>

    <wk-form
      ref="form"
      :fields="fieldArr"
      class="form"
      @change="handlerChange" />

    <view v-if="type === 'examine'" class="img-content">
      <view class="img-content-title" @click="addFile">
        <view class="left">
          <image :src="$static('images/icon/image.png')" class="pic-icon" />
          发票图片文件
        </view>
        <view class="right add-icon">
          <text class="wk wk-plus" />
        </view>
      </view>

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

<script>
/**
 * event
 * ------ 事件名 -- 参数  ------------------- 事件描述 -------------------
 *       delete   index(当前的序列号)       删除当前明细
 *                 type(类型)
 *       change    {Object}              明细发生改变
 * ---------------------------------------------
 *
 * props   itemData  {Object}  默认详情数据
 *         type  {String}  类型
 *         index {Number}  当前序列号
 */
  import { FileDeleteById } from 'API/file'
  import Fields from 'UTIL/fields'
  import WkFile from '@/utils/file.js'
  import moment from 'moment'

  export default {
    name: 'TravelAdd',
    props: {
      itemData: {
        type: Object,
        default: () => {}
      },
      type: {
        type: String,
        default: 'travel'
      },
      index: {
        type: Number,
        default: 0
      },
      length: {
        type: Number,
        default: 0
      }
    },
    data() {
      // 交通工具
      const transportation = ['飞机', '火车', '汽车', '其他'];
      // 行程属性
      const trafficType = ['单程', '往返'];

      return {
        title: '',
        intDays: '',

        travelForm: [
          new Fields({name: '交通工具', formType: 'select', fieldName: 'vehicle', setting: transportation}),
          new Fields({name: '单程往返', formType: 'select', fieldName: 'trip', setting: trafficType}),
          new Fields({name: '出发城市', formType: 'text', fieldName: 'startAddress'}),
          new Fields({name: '目的城市', formType: 'text', fieldName: 'endAddress'}),
          new Fields({name: '开始时间', formType: 'datetime', fieldName: 'startTime'}),
          new Fields({name: '结束时间', formType: 'datetime', fieldName: 'endTime'}),
          new Fields({name: '时长（天）', formType: 'floatnumber', fieldName: 'duration', precisions: 1}),
          new Fields({name: '备注', formType: 'textarea', fieldName: 'description'}),
        ],
        examineForm: [
          new Fields({name: '出发城市', formType: 'text', fieldName: 'startAddress'}),
          new Fields({name: '目的城市', formType: 'text', fieldName: 'endAddress'}),
          new Fields({name: '开始时间', formType: 'datetime', fieldName: 'startTime'}),
          new Fields({name: '结束时间', formType: 'datetime', fieldName: 'endTime'}),
          new Fields({name: '交通费（元）', formType: 'floatnumber', fieldName: 'traffic', defaultValue: '0.00', precisions: 2}),
          new Fields({name: '住宿费（元）', formType: 'floatnumber', fieldName: 'stay', defaultValue: '0.00', precisions: 2}),
          new Fields({name: '餐饮费（元）', formType: 'floatnumber', fieldName: 'diet', defaultValue: '0.00', precisions: 2}),
          new Fields({name: '其他费用（元）', formType: 'floatnumber', fieldName: 'other', defaultValue: '0.00', precisions: 2}),
          new Fields({name: '费用明细描述', formType: 'textarea', fieldName: 'description'}),
        ],
        fieldArr: [],

        imgList: [],
        fileBatchId: null
      }
    },
    created() {
      if (this.type === 'travel') {
        this.fieldArr = this.travelForm
        this.title = '行程'
      } else if (this.type === 'examine') {
        this.fieldArr = this.examineForm
        this.title = '费用'
      }
      this.$nextTick(() => {
        // 给表单设置默认值
        if (this.itemData.img) {
          this.imgList = [].concat(this.itemData.img)
          if (this.imgList.length > 0) {
            this.fileBatchId = this.imgList[0].batchId
          }
        }
        this.setDefaultForm(this.itemData)
      })
    },
    methods: {
      /**
       * 设置默认值
       * @param {Object} data
       */
      setDefaultForm(data) {
        const form = {}
        this.fieldArr.forEach(o => {
          if (data.hasOwnProperty(o.fieldName)) {
            let val = data[o.fieldName]
            if (o.formType === 'select') {
              form[o.fieldName] = this.$isEmpty(data[o.fieldName]) ? [] : [{ label: val, value: val }]
            } else {
              form[o.fieldName] = data[o.fieldName]
            }
          }
        })
        console.log('form: ', form)
        this.$nextTick(() => {
          this.$refs.form.setForm(form)
        })
      },

      handleDelete(index) {
        this.$emit('delete', index)
      },

      addFile() {
        let params = {type: 'img'}
        if (this.fileBatchId) params.batchId = this.fileBatchId
        let fileObj = new WkFile(params)
        fileObj.choose().then(res => {
          this.imgList = this.imgList.concat(res)
          this.fileBatchId = res[0].batchId
          // console.log('res', res, this.imgList)
          this.handlerChange()
        })
      },

      deleteFile(index) {
        console.log('oooo', this.imgList, index)
        const fileId = this.imgList[index].fileId
        this.imgList.splice(index, 1)
        this.handlerChange()
        FileDeleteById({
          id: fileId
        }).then().catch()
      },

      calcTimeDiff(item) {
      // if (item.startTime && item.endTime) {
      //   const startDate = moment(item.startTime)
      //   const endDate = moment(item.endTime)
      //   const diff = endDate.diff(startDate, 'hours')
      //   let intDays = Math.floor(diff / 24)
      //   const remainder = diff % 24
      //   if (remainder >= 4 && remainder < 8) {
      //     intDays += 0.5
      //   } else if (remainder >= 8) {
      //     intDays += 1
      //   }
      //   item.duration = intDays
      // 	if (this.intDays != intDays) {
      // 		this.intDays = intDays
      // 		this.$refs.form.setFormVal('duration', intDays)
      // 	}
      // }
      },

      handlerChange(data) {
        // console.log('args: ', data)
        this.$refs.form.getForm().then(res => {
          const data = res.entity
          if (this.imgList.length > 0 && this.fileBatchId) {
            data.batchId = this.fileBatchId
            data.img = this.imgList
          }
          if (this.type === 'travel') {
            this.calcTimeDiff(data)
          }
          this.$emit('change', data, this.index)
        }).catch()
      }
    }
  }
</script>

<style scoped lang="scss">
.form {
  margin: 0;
  padding-bottom: 20rpx;
}

.travel-item {
  .travel-item-header {
    font-size: 28rpx;
    color: $gray;
    padding: 18rpx 30rpx;
    background-color: #F3F5FA;
    @include left;
    .title {
      flex: 1;
    }
    .control {
      color: $theme-color;
    }
  }

  .img-content {
    background-color: white;
    overflow: hidden;
    padding: 0 30rpx 20rpx;
    margin-top: -20rpx;
    .img-content-title {
      padding: 15rpx 0;
      @include left;
      .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;
        }
      }
    }
  }
}

</style>


