<template>
  <div>
    <van-nav-bar title="重新发起申请" left-text="返回" @click-left="$route_back" left-arrow></van-nav-bar>
    <div class="body_com has_header">
      <scroller :isNeed="isNeed">
        <div v-for="(item,index) in fromData.items" :key="index" class="item_class" @click="itemIndex = index">
          <div class="clear operation">
            <span class="fl color_ccc">申请(第{{index+1}}条)</span>
          </div>
          <van-cell required title="录入对象" right-icon="arrow">
            <Wxopendata type="userName" :openid="item.employee_name"></Wxopendata>
          </van-cell>
          <van-cell center title="指定规则">
            <template #right-icon>
              <div>
                <van-switch v-model="item.show_rule" inactive-color="#9a9a9a" size="24" @change="onRuleSwitchChange(item)" />
              </div>
            </template>
          </van-cell>

          <div v-show="item.show_rule">
            <RuleCategorySelectorCell @confirm="rule_item_confirm" title="选择分类和规则" v-model="rule_item" :multi="false"
              :max="1"></RuleCategorySelectorCell>
            <van-cell v-for="(d, i) in rule_item" :key="i" size="large" :label="d.remark">
              <template slot="title">
                {{ get_point_name(d.pt_id) }}
                <span v-show="d.range_type == 1">{{ d.min_point }}</span>
                <span v-show="d.range_type == 2">{{ d.min_point }}—{{ d.max_point }}</span>
              </template>
            </van-cell>
          </div>

          <van-cell required>
            <Mtextarea v-model="item.remark" name="申请事由" v-validate="'required|max:300'" placeholder="请输入申请事由(最多300字)"
              :text_max="300" :imgs_max="3" images speech :imgs.sync="item.files"></Mtextarea>
          </van-cell>
          <DateCell required title="发生时间" v-model="item.event_time"></DateCell>
          <van-cell required title="审批人" right-icon="arrow">
            <Wxopendata type="userName" :openid="item.reviewer_name"></Wxopendata>
          </van-cell>
        </div>
        <div style="padding:0.32rem; box-sizing: border-box;">
          <van-button size="large" @click="data_verify" :disabled="subloading || !hasRules" type="info">提交</van-button>
        </div>
      </scroller>
    </div>
  </div>
</template>
<script>
import request from '@/utils/request'
import integralApplyItem from '@/components/common/integralApplyItem'
import moment from 'moment'
import Mtextarea from '@/components/common/Mtextarea'
import RuleCategorySelectorCell from '@/components/common/RuleCategorySelectorCell1'
import DateCell from '@/components/common/DateCell'
export default {
  name: 'integral_application',
  components: {integralApplyItem, Mtextarea, RuleCategorySelectorCell, DateCell},
  

  
  data () {
    let date = moment().format('YYYY-MM-DD')
    return {
      isNeed:this.$getCache('isAndroid') == 1 ? false: true,
      close_buttom: false,
      detail_info: {},
      fromData: {
        items: []
      },
      itemIndex: 0,
      rule_item: [],
      point_types: JSON.parse(localStorage.getItem('SET_POINT_TYPES')) || JSON.parse(plus.storage.getItem('SET_POINT_TYPES')),
      itemData: {},
      hasRules: false,
      subloading: false,
      employee_map: JSON.parse(localStorage.getItem('SET_EMPLOYEE_MAP')) || JSON.parse(plus.storage.getItem('SET_EMPLOYEE_MAP')),
    }
  },

  created() {
    this.initData();
  },

 
  methods: {
    initData () {
      this.detail_info = JSON.parse(this.$route.query.detail_info)
      let obj = {
        employee_id: this.detail_info.employee_id,
        employee_name: this.detail_info.employee_info.name,
        event_time: '',
        reviewer_id: this.detail_info.reviewer_id,
        reviewer_name: this.employee_map[this.detail_info.reviewer_id].name,
        rule_id: this.detail_info.rule_id,
        item_id: this.detail_info.item_id,
        show_rule: this.detail_info.rule_id && this.detail_info.rule_id != 0 ? true : false,
        remark: this.detail_info.item_name,
        files: []
      }
      // 处理事件时间
      let timeData = this.detail_info.detail.find(item => item.key === '事件时间')
      if (timeData && timeData.value) {
        obj.event_time = timeData.value
      }
      // 处理附件
      let fileData = this.detail_info.detail.find(item => item.key === '附件')
      if (fileData && fileData.value && fileData.value.length) {
        obj.files = fileData.value
      }
      this.fromData.items.splice(0, 1, obj);
      this.hasRules = this.fromData.items.every(item => !item.show_rule  || item.show_rule && item.rule_id && item.rule_id !== 0)
      // 处理规则项
      if (this.detail_info.rule_id && this.detail_info.rule_id != 0) {
        this.rule_item = [{
          checked: true,
          cycle_type: this.detail_info.item_cycle_type,
          pt_id: this.detail_info.pt_id,
          rule_id: this.detail_info.rule_id,
          id: this.detail_info.item_id,
          remark: this.detail_info.rule_name,
          prize_type: this.detail_info.item_prize_type,
          range_type: this.detail_info.item_range_type,
          min_point: this.detail_info.item_min_point,
          max_point: this.detail_info.item_max_point,
          is_attendance: this.detail_info.item_is_attendance
        }]
      }
    },

    rule_item_confirm(index, data) {
      if (data.length == 0) {
        this.fromData.items[this.itemIndex].rule_id = 0
        this.fromData.items[this.itemIndex].item_id = 0
        this.fromData.items[this.itemIndex].remark = ''
        this.rule_item = []
        return
      }
      this.rule_item = data
      this.fromData.items[this.itemIndex].rule_id = data[0].rule_id
      this.fromData.items[this.itemIndex].item_id = data[0].id
      this.fromData.items[this.itemIndex].remark = data[0].remark
    },

    onRuleSwitchChange(item) {
      if (!item.show_rule) {
        item.rule_id && item.item_id ? item.remark = '' : ''
        this.rule_item = []
        item.rule_id = 0
        item.item_id = 0
      }
      this.hasRules = this.fromData.items.every(i => !i.show_rule  || i.show_rule && i.rule_id && i.rule_id !== 0)
    },

    get_point_name(id) {
      let name = ''
      this.point_types.forEach(element => {
        if (element.id == id) {
          name = element.name
        }
      })
      return name
    },

    data_verify () {
      let self = this
      self.$validator.validateAll().then(result => {
        if (!result) {
          self.$notify({ type: 'danger', message: self.$validator.errors.items[0].msg })
        } else {
          self.send()
        }
      })
    },


    send () {
      let self = this
      self.subloading = true
      for (const i in self.fromData.items) {
        if (!self.fromData.items[i].employee_id) {
          self.$notify({ type: 'danger', message: '第' + (parseInt(i) + 1) + '条请选择录入对象'})
          self.subloading = false
          return false
        }
        if (!self.fromData.items[i].event_time) {
          self.$notify({ type: 'danger', message: '第' + (parseInt(i) + 1) + '条请选择发生时间'})
          self.subloading = false
          return false
        }
        if (!self.fromData.items[i].reviewer_id) {
          self.subloading = false
          self.$notify({ type: 'danger', message: '第' + (parseInt(i) + 1) + '条请选择审批人'})
          return false
        }
        if (!self.fromData.items[i].remark) {
          self.$notify({ type: 'danger', message: '第' + (parseInt(i) + 1) + '条请输入申请事由'})
          self.subloading = false
          return false
        }
      }
      self.$toast.loading({
        message: '正在处理'
      })
      if (this.close_buttom == false) { // 第一次点击提交为false，为false可进入请求。请求成为 为true。0.5秒后变为false
        request('post', '/api/integral/review/apply', self.fromData, 'v2').then(res => {
          self.$toast.clear()
          if (res.data.code == 1) {
            if (res.data.data.list.some(item => item.status != 0)) {
              this.$toast.success("申请成功")
              this.fromData = {
                items: [{}]
              }
              this.itemData = {}
              setTimeout(() => {
                this.$router.push({ path: '/integral_application_list' })
              }, 500)
              // localStorage.setItem('callback_data', JSON.stringify({detail_url: this.$route.path, result: res.data.data}))
              // this.$router.push({path: '/callback_new'})
            } else {
              let index = res.data.data.list.findIndex(item => item.status == 0)
              self.$notify({ type: 'danger', message: res.data.data.list[0].msg})
            }
          } else {
            self.$notify({ type: 'danger', message: res.data.msg})
          }
        }).catch(e => {
          self.$toast.clear()
        }).finally(() => {
          self.subloading = false
          self.close_buttom = true
          setTimeout(() => {
            self.close_buttom = false
          }, 1000)
        })
      } else {
        self.subloading = false
      }
    }
  }
}
</script>
<style scoped lang="less">
  .body_com{
    height: calc(100% - 0.92rem);
    position: relative;
    overflow-y: scroll;
  }
  .item_class{
    .operation{
      padding: 0.24rem 0.32rem;
      font-size: 0.3rem;
      box-sizing: border-box;
      .del_btn{
        color: #26A2FF;
      }
    }
  }
  .color_bule{
    color: #26A2FF;
  }
</style>
