<!-- 改约 -->
<template>
  <view class="content-view">
    <view class="con-box">
      <view class="title">{{ traceTitles[0] }}</view>
      <view class="u-flex u-flex-wrap">
        <view
          v-for="(item, index) in options['owns']"
          :key="index"
          @click="changeOwn(index, item.name, item.types)"
          :class="{ 'txt-item': true, active: curOwn == index }"
        >
          <text class="txt">{{ item.name }}</text>
        </view>
      </view>
      <u-gap height="30"></u-gap>
      <view class="title">{{ traceTitles[1] }}</view>
      <view class="u-flex u-flex-wrap">
        <view
          v-for="(txt, index) in options['owns'][curOwn]['types']"
          :key="index"
          @click="changeType(index, txt)"
          :class="{ 'txt-item': true, active: trace.reason == txt }"
          style="width: 306rpx;margin-right: 18rpx"
        >
          <text class="txt">{{ txt }}</text>
        </view>
      </view>
      <view class="input-view">
        <u-input
          v-model="trace.remark"
          class="textarea"
          height="156"
          type="textarea"
          placeholder="请补充详细说明，以便于记录您的接单信用分"
        ></u-input>
      </view>
    </view>
    <view class="time-view">
      <appoint-time
        :dateList="dateList"
        :title="appointTitle"
        :timeList="timeList"
        :type="type"
        :defaultAppointRangeItem="defaultAppointRangeItem"
        @dateChange="dateChange"
        @timeChange="timeChange"
        @weekChange="weekChange"
      ></appoint-time>
    </view>
  </view>
</template>

<script>
let now = new Date(new Date().toLocaleDateString()).getTime()
import appointTime from '@/components/appoint/appoint-time.vue'
export default {
  components: {
    appointTime,
  },
  props: {
    // 报备(预约): 'filing', 改约: 'subscribe'
    type: {
      type: String,
      default: 'subscribe',
    },
    categoryId: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      feedback: null,
      options: [
        {
          name: '报备',
          owns: [
            {
              name: '客户',
              types: [
                '等客户报装电表',
                '等客户与物业沟通',
                '等客户改造电源',
                '客户不确定安装时间',
                '等客户通知安装时间',
                '客户电话未打通',
                '客户反馈暂不安装',
              ],
            },
            { name: '个人', types: [] },
            { name: '客观', types: [] },
          ],
        },
        {
          name: '改约',
          owns: [
            {
              name: '客户',
              types: ['有事耽搁', '未带齐工具', '个人改约', '其他'],
            },
            { name: '个人', types: [] },
            { name: '客观', types: [] },
          ],
        },
      ],
      dateList: [
        { day: now, timeRange: [] },
        { day: now + 1 * 86400000, timeRange: [] },
        { day: now + 2 * 86400000, timeRange: [] },
        { day: now + 3 * 86400000, timeRange: [] },
        { day: now + 4 * 86400000, timeRange: [] },
        { day: now + 5 * 86400000, timeRange: [] },
        { day: now + 6 * 86400000, timeRange: [] },
      ],
      timeList: [
        { name: '06:00-08:00', pkey: 'appointment_range_8', disabled: false },
        { name: '08:00-10:00', pkey: 'appointment_range_10', disabled: false },
        { name: '10:00-12:00', pkey: 'appointment_range_12', disabled: false },
        { name: '12:00-14:00', pkey: 'appointment_range_14', disabled: false },
        { name: '14:00-16:00', pkey: 'appointment_range_16', disabled: false },
        { name: '16:00-18:00', pkey: 'appointment_range_18', disabled: false },
        { name: '18:00-20:00', pkey: 'appointment_range_20', disabled: false },
        { name: '20:00-22:00', pkey: 'appointment_range_22', disabled: false },
        { name: '22:00-24:00', pkey: 'appointment_range_24', disabled: false },
      ],

      traceTitles: ['问题归属', '问题类型'],
      appointTitle: '改约时间',
      appoint: ['下次联系时间', '改约时间'],
      trace: {
        reasonType: '报备', // 反馈类型
        reasonRelegation: '客户', // 反馈归属
        reason: '', // 反馈原因
        remark: '', // 备注
        traceDate: null, // 反馈时间
        timeRange: null, // 反馈时间段
        dateItem: null,
        timeItem: null,
      },
      curOwn: 0,
      num: 0,
    }
  },
  computed: {
    curTab() {
      return this.isSubscribe ? 1 : 0
    },
    isSubscribe() {
      return this.type == 'subscribe'
    },
    disabledSubmit() {
      let self = this
      if (
        self.trace.reasonRelegation &&
        self.trace.reason &&
        self.trace.traceDate &&
        self.trace.timeRange
      ) {
        return false
      }

      return true
    },
    types() {
      return { 报备: 'filing', 改约: 'subscribe' }
    },
    typeKeys() {
      return { filing: '报备', subscribe: '改约' }
    },
    // timeType() {
    //   return this.types[this.options.name]
    // },
    defaultAppointRangeItem() {
      return this.options.defaultAppointRangeItem
    },
    submitData() {
      if (this.isSubscribe) {
        // 改约

        let params = {
          reason: this.trace.reason,
          reasonRelegation: this.trace.reasonRelegation,
          reasonType: this.trace.reasonType,
          remark: this.trace.remark,
        }

        params.appointmentDatetime = this.trace.traceDate
        params.appointmentDatetimeRange = this.trace.timeRange
        return params
      } else {
        // 报备（预约)
        let data = {
          reason: this.trace.reason,
          reasonRelegation: this.trace.reasonRelegation,
          reasonType: this.trace.reasonType,
          remark: this.trace.remark,
        }

        data.appointmentDatetime = this.trace.traceDate

        data.appointmentDatetimeRange = this.trace.timeRange
        // 最后一个24：00点，按照23：59分处理
        if (
          this.trace.timeItem &&
          this.trace.timeItem.pkey &&
          this.trace.traceDate
        ) {
          let traceDate = this.moment(this.trace.traceDate)
          let timeArr = this.trace.timeItem.pkey.split('_')
          if (this.trace.timeItem.pkey == 'appointment_range_24') {
            let traceDateTime = traceDate
              .clone()
              .add(23, 'hours')
              .add(59, 'minutes')
            data.nextTraceDatetime = traceDateTime.unix() * 1000
          } else {
            let hours = timeArr && timeArr.length && timeArr.pop()
            let traceDateTime = traceDate.clone().add(Number(hours), 'hours')
            data.nextTraceDatetime = traceDateTime.unix() * 1000
          }
        }
        return data
      }
    },
  },
  watch: {
    disabledSubmit(val) {
      this.$emit('change', val)
    },
    categoryId(val) {
      if (val) {
        this.initPageData()
      }
    },
  },
  created() {
    if (this.categoryId) {
      this.initPageData()
    }
  },
  methods: {
    /* 初始化页面数据 */
    async initPageData() {
      let self = this
      await Promise.all([self.loadCalendar(), self.loadTimerange()])
      let params = { categoryId: self.categoryId }
      let res = await self.$u.api.feedbackConfig(params)
      if (res && res.code == 200) {
        self.feedback = res.data || {}
        self.buildConfig()
      }
      uni.hideLoading()
    },
    /* 组装数据项参数 */
    buildConfig() {
      let self = this
      if (self.feedback) {
        let key = self.typeKeys[this.type]
        let data = self.feedback[key]
        let configs = {}
        let owns = Object.keys(data)
        let ownVals = Object.values(data)
        var defaultAppointRangeItem =
          //   this.isSubscribe
          //     ? {
          //         name: '',
          //         pkey: '',
          //         disabled: false,
          //       }
          // :
          {
            name: '22:00-24:00',
            pkey: 'appointment_range_24',
            disabled: false,
          }
        configs = {
          name: key,
          owns: [],
          defaultAppointRangeItem: defaultAppointRangeItem,
        }

        owns.forEach(function(own, key) {
          configs['owns'][key] = { name: own, types: ownVals[key] }
        })

        // 数组改写需要刷新绑定数据
        self.options = configs
        this.initParams()
      }
    },
    /* 初始化参数 */
    initParams() {
      let self = this
      if (self.options) {
        let tabList = self.options
        self.trace.reasonType = tabList.name
        self.trace.reasonRelegation = tabList['owns'][self.curOwn].name
        self.trace.reason = tabList['owns'][self.curOwn]['types'][0]
        self.appointTitle = self.appoint[self.curTab]
        self.trace.remark = ''
        self.trace.traceDate = null
        self.trace.timeRange = null
        self.trace.dateItem = null
        // if (self.trace.reasonType == '改约') { // 屏蔽改约对时间段选择的限制
        //   if (self.dateList && self.timeList) {
        //     self.timeList.map((item, index) => {
        //       if (
        //         (self.trace.dateItem &&
        //           self.trace.dateItem.timeRange &&
        //           self.trace.dateItem.timeRange.indexOf(item.pkey) > -1) ||
        //         item.isEnd
        //       ) {
        //         item.disabled = true
        //       } else {
        //         item.disabled = false
        //       }
        //     })
        //   }
        // } else {
        self.timeList.map((item, index) => {
          item.disabled = false
        })
        // }
      }
    },

    /* 加载日历数据 */
    async loadCalendar() {
      let self = this
      let res = await this.$u.api.workerCalendar({ num: this.num })
      if (res && res.code == 200) {
        self.dateList = res.data
      }
    },

    /* 加载预约时间段 */
    async loadTimerange() {
      let self = this
      let res = await this.$u.api.openTimerange()
      if (res && res.code == 200) {
        let list = res.data
        list.map((item, index) => {
          item.disabled = false
        })
        self.timeList = list
      }
    },

    changeOwn(index, own, types) {
      let self = this
      self.curOwn = index
      self.trace.reasonRelegation = own
      self.trace.reason = types[0]
    },
    changeType(index, type) {
      this.trace.reason = type
    },
    weekChange(data) {
      // 点击下一周
      console.log(data, 'week-data')
      if (data && data.time) {
        let num = data.num
        let time = data.time
        this.num = num
        if (num == 0) {
          this.loadCalendar()
        } else {
          this.loadCalendar()
        }
      }
    },
    dateChange(data) {
      // 点击日期选择
      let self = this
      self.trace.dateItem = data.item
      // if (self.trace.reasonType == '改约') {  // 屏蔽改约对时间段选择的限制
      //   self.timeList.map((item, index) => {
      //     if (
      //       (data.item.timeRange &&
      //         data.item.timeRange.indexOf(item.pkey) > -1) ||
      //       item.isEnd
      //     ) {
      //       item.disabled = true
      //     } else {
      //       item.disabled = false
      //     }
      //   })
      // } else {
      self.timeList.map((item, index) => {
        item.disabled = false
      })
      // }
      self.trace.traceDate = data.item.day
      self.trace.timeRange = null
    },
    timeChange(data) {
      // 时间段选择变化
      console.log(data, 'week-data')
      this.trace.timeRange = data.item.pkey
      this.trace.timeItem = data.item
    },
  },
}
</script>
<style lang="scss" scoped>
.content-view {
  height: 100%;
  border-radius: 12rpx;
  overflow: auto;

  .time-view {
    border-radius: 12rpx;
    background-color: #ffffff;
    padding-bottom: 20rpx;
  }
}

.con-box {
  padding: 30rpx 30rpx 8rpx 30rpx;
  border-radius: 12rpx;
  background-color: #ffffff;
  margin-bottom: 20rpx;
  .title {
    font-weight: bold;
    font-size: 32rpx;
    line-height: 32rpx;
    color: #333;
  }
  & > .u-flex {
    margin-top: 40rpx;
    margin-right: -24rpx;
    .txt-item {
      border-radius: 12rpx;
      padding: 24rpx 38rpx;
      width: 196rpx;
      height: 72rpx;
      text-align: center;
      margin-right: 22rpx;
      margin-bottom: 20rpx;
      background-color: #f4f5f7;
      &.active {
        background-color: #2272ff;
        .txt {
          color: #fff;
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
        }
      }
    }
  }

  .txt {
    display: block;
    font-size: 26rpx;
    line-height: 26rpx;
    color: #333;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }
  .input-view {
    margin-top: 24rpx;
    margin-bottom: 24rpx;
    border: 2rpx solid #ececec;
    padding: 18rpx 30rpx;
  }
}
</style>
