<template>
  <div class="integral_entry_box">
    <van-nav-bar :title="title" left-text="返回" @click-left="$route_back" left-arrow></van-nav-bar>
    <div class="body_com has_header">
      <scroller>
        <van-cell-group class="head_title">
          <div class="top_tip">已有B分事件?
            <EventSelector @confirm="event_select" title="去关联"></EventSelector>
          </div>
          <van-cell>
            <Mtextarea v-model="text" placeholder="输入A分描述" required name="描述" v-validate="'required|min:3|max:100'"
                       :text_max="100" :imgs_max="3" images speech :imgs.sync="imgs"></Mtextarea>
          </van-cell>
        </van-cell-group>
        <van-cell-group>
          <!-- 不能为0   -->
          <NumberInput v-model="point" :min="-100000" title="A分分值" name="分值" v-validate="'required|max:100000'"
                       :max="100000"></NumberInput>
        </van-cell-group>
        <van-cell-group>
          <CategorySelectorCell @get_items="get_items" title="选择分类" name="分类" v-validate="'required'"
                                v-model="cate_list" :max="1" :multi="false" required></CategorySelectorCell>
          <van-cell title="选择规则" is-link @click="item_show = true" v-if="!item_info.rule_id"></van-cell>

          <van-cell @click="item_show = true" v-if="item_info.rule_id" :title="item_info.remark" is-link>
            <template slot="label">
              <span class="record color_green" v-if="item_info.min_point < 0">{{(item_info.range_type == 1 ? item_info.min_point : item_info.min_point+'～'+item_info.max_point)}}</span>
              <span class="record color_red" v-if="item_info.min_point > 0">+ {{(item_info.range_type == 1 ? item_info.min_point : item_info.min_point+'～'+item_info.max_point)}}</span>
              <span class="type">{{types_list[item_info.pt_id].name}}</span>
            </template>
          </van-cell>

        </van-cell-group>

        <van-cell-group>
          <van-cell required title="录入对象" @click="show_employee_selector = true" is-link
                    :value="members_name"></van-cell>
        </van-cell-group>
        <van-cell-group>
          <van-cell required title="发生时间" @click="date_show = true" is-link :value="event_time"></van-cell>
        </van-cell-group>
        <van-cell-group>
          <EmployeeSelectorCell title="审批人" v-model="approval_employee" :multi="false"></EmployeeSelectorCell>
        </van-cell-group>
        <div style="padding:0.32rem;">
          <van-button type="info" block @click="sava_btn" style="margin-top:0.2rem;">提交</van-button>
        </div>
        <div style="height: 1rem;"></div>
      </scroller>

      <!-- 选择对象 -->
      <EmployeeSelector :can_select_employee="true" :can_select_dept="false" :dept_multi="false" @confirm="move_confirm"
                        :visible.sync="show_employee_selector" :selected="selected"
                        @cancel="move_cancel"></EmployeeSelector>

      <!-- 发生时间 -->
      <van-calendar color="#238dfa" v-model="date_show" @confirm="dateConfirm"/>


      <van-popup v-model="item_show" position="bottom" closeable>
        <div style="padding:0.32rem;">选择规则</div>
        <van-cell-group v-show="item_list.length > 0">
          <van-cell v-for="(item, index) in item_list" :key="index" :title="item.remark"
                    @click="item_confirm(item, index)">
            <template slot="label">
              <span class="record color_green" v-if="item.min_point < 0">{{(item.range_type == 1 ? item.min_point : item.min_point+'～'+item.max_point)}}</span>
              <span class="record color_red" v-if="item.min_point > 0">+ {{(item.range_type == 1 ? item.min_point : item.min_point+'～'+item.max_point)}}</span>
              <span class="type">{{types_list[item.pt_id].name}}</span>
            </template>
            <template slot="icon">
              <van-checkbox v-model="item.checked" style="margin-right:0.16rem;"></van-checkbox>
            </template>
          </van-cell>
        </van-cell-group>
        <div v-show="item_list.length == 0"
             style="padding:0.32rem; text-align: center; font-size: 0.32rem; color:#999;">
          当前分类没有规则可选
        </div>
      </van-popup>


    </div>
  </div>
</template>
<script>
  import request from '@/utils/request'
  import moment from 'moment'
  import Vue from 'vue'
  import Mtextarea from '@/components/common/Mtextarea'
  import NumberInput from '@/components/common/NumberInput'
  import EventSelector from '@/components/common/EventSelector'
  import EmployeeSelector from '@/components/common/EmployeeSelector'
  import CategorySelectorCell from '@/components/common/CategorySelectorCell'
  import EmployeeSelectorCell from '@/components/common/EmployeeSelectorCell'
  import {calendar} from 'vant'

  Vue.use(calendar)
  export default {
    // 数据
    data () {
      let types_list = {}
      let point_types = this.$store.getters.point_types
      for (let i in point_types) {
        types_list[point_types[i].id] = point_types[i]
      }
      return {
        types_list: types_list,
        item_info: {},
        item_list: [],
        item_show: false,
        title: '录入A分',
        show_employee_selector: false,
        date_show: false,
        // show_approver: false,
        point: 0,
        members_name: '',
        members: [],
        selected: {employee: [], dept: []},
        approver_selected: {employee: [], dept: []},
        event_time: '',
        formData: {
          items: [{
            item_id: '',
            pt_id: '',
          }]
        },
        // 语音输入
        imgs: [],
        text: '',
        cate_list: [],
        approval_employee: []
      }
    },
    mounted () {

    },
    // 组件
    components: {
      EmployeeSelector, Mtextarea, CategorySelectorCell, NumberInput, EventSelector, EmployeeSelectorCell
    },
    // 方法
    methods: {
      item_confirm (item, index) {
        this.item_show = false
        for (let i in this.item_list) {
          this.$set(this.item_list[i], 'checked', false)
        }
        this.item_info = item
        this.$set(this.item_list[index], 'checked', true)
      },
      get_items (data) {
        this.item_info = {}
        for (let i in data) {
          if (!data[i].checked) {
            data[i]['checked'] = false
          }
        }
        this.item_list = data
      },
      event_select (item) {
        //通过ID查到详情来填充
        this.showLoading()
        request('get','/api/integral/statistics/integral/info',{event_id: item.id}).then(res => {
          this.$toast.clear()
          if (res.data.code == 1) {
            this.cate_list = [{id: res.data.data.rule_id, name: res.data.data.rule_list}]
            this.members = [item.employee_id]
            this.members_name = res.data.data.employee_name
            this.text = res.data.data.remark.customize
            this.event_time = res.data.data.date
          } else {
            this.$toast(res.data.msg)
          }
        })
      },
      // 加载
      showLoading () {
        this.$toast.loading({loadingType: 'spinner', message: '正在处理'})
      },
      sub () {
        const data = this.getFormData()

        this.validatePointPermission(data.items, err => {
          if (err) {
            this.$notify({type: 'danger', message: err.message})
          } else {
            this.showLoading()
            request('post','/api/integral/review/a/entry',data).then((res) => {
              if (res.data.code == 1) {
                this.$toast.clear()
                this.$toast(res.data.msg)
                if (window.plus) {
                  setTimeout(() => {
                    plus.navigator.setStatusBarStyle('dark')
                    document.documentElement.style.backgroundColor = '#fff'
                  }, 100)
                }
                localStorage.setItem('callback_data', JSON.stringify({title: '申请成功', detail_url: ''}))
                this.$router.replace({path: '/callback?replace=2'})
              } else {
                this.$toast.clear()
                this.$toast(res.data.msg)
              }
            }).catch((e) => {
              this.$toast.clear()
            })
          }
        })
      },
      getFormData () {
        let pt_id = 0
        let types = this.$store.getters.point_types
        for (let i in types) {
          if (types[i].code === 'AF') {
            pt_id = types[i].id
          }
        }
        let item = {
          rule_id: this.cate_list[0].id,
          item_id: 0,
          point: this.point,
          remark: this.text,
          event_time: this.event_time,
          reviewer_id: 0,
          pt_id: pt_id,
          files: this.imgs,
        }
        if (this.item_info.id) {
          item.item_id = this.item_info.id
        }
        if (this.approval_employee.length !== 0) {
          item.reviewer_id = this.approval_employee[0].id
        }
        return {members: this.members, items: [item]}
      },
      // 关闭选择部门弹窗
      move_cancel () {
        this.show_employee_selector = false
      },
      // 选择人员 完成
      move_confirm (data) {
        let self = this
        if (data.employee) {
          let id_arr = [], name_arr = []
          data.employee.forEach(v => {
            self.members.push(v.id)
            name_arr.push(v.name)
          })
          self.members_name = name_arr.join(',')
          self.selected = data
        }
        self.move_cancel()
      },
      // 发生事件确认
      dateConfirm (date) {
        this.date_show = false
        this.event_time = moment(date).format('YYYY-MM-DD')
      },
      sava_btn () {
        let self = this
        self.$validator.validate().then(result => {
          if (!result) {
            self.$notify({type: 'danger', message: self.$validator.errors.items[0].msg})
          } else {
            if (!self.members_name) {
              self.$notify({type: 'danger', message: '录入对象不能为空'})
            } else if (!self.event_time) {
              self.$notify({type: 'danger', message: '发生时间不能为空'})
            } else if (self.point == 0) {
              self.$notify({type: 'danger', message: '分值不能为0'})
            } else {
              self.sub()
            }
          }
        })
      },
      validatePointPermission (items, callback) {
        const userInfo = this.$store.getters.user_info
        const pointConfig = userInfo.point_config
        const index = pointConfig.point_limit.findIndex(o => o.pt_id === 2)
        if (index < 0 || userInfo.is_creator === 1) {
          callback()
        } else {
          const maxPointPermission = parseInt(pointConfig.point_limit[index].point)
          /** maxPointPermission 等于-1时 不做任何限制 */
          if (maxPointPermission === -1) {
            callback()
          } else {
            const ruleLimitCheck = userInfo.site_config.rule_limit_check
            /** 在 ruleLimitCheck 为0的时候， 超出积分权限都要选择审批人提交 */
            if (ruleLimitCheck === 0) {
              this.validateRuleLimit(items, callback, a => a.point > maxPointPermission && a.reviewer_id <= 0)
            } else {
              /** 在 ruleLimitCheck 为1的时候， 1.选择了规则就不强制选择申请人  2.未选规则超出权限分要提交审批人 */
              this.validateRuleLimit(items, callback, b => b.item_id === 0 && b.point > maxPointPermission)
            }
          }
        }
      },
      validateRuleLimit (items, callback, conditionCallback) {
        if (typeof callback !== 'function') {
          throw new TypeError('callback is not a function')
        }

        const res = items.every((item, index) => {
          if (conditionCallback(item, index)) {
            index === 0 ?
              callback(new Error('输入分值超出权限，请选择审批人递交')) :
              callback(new Error(`第${index + 1}条输入分值超出权限，请选择审批人递交`))
            return false
          }
          return true
        })
        res && callback()
      }
    }
  }
</script>
<style rel="stylesheet/less" lang="less">
  .body_com {
    height: calc(100% - 0.92rem);
    position: relative;
  }

  .top_tip {
    font-size: 0.3rem;
    text-align: right;
    color: #909399;
    background-color: rgb(245, 245, 245);
    padding-top: 0.1rem;
    padding-bottom: 0.1rem;
    padding-right: 0.32rem;

    span {
      color: #26A2FF;
    }
  }

  .integral_entry_box .head_title {
    margin: 0.1rem 0;
  }

  .integral_entry_box .head_title:after {
    border: none;
  }
</style>
