<template>
  <div>
    <van-nav-bar title="审批" left-text="返回" @click-left="$route_back" left-arrow></van-nav-bar>
    <div class="body_com has_header">
      <scroller>
        <van-cell-group>
          <van-cell title="指定规则" v-if="can_edit_rule">
            <template slot="right-icon">
              <div>
                <van-switch v-model="select_cate" inactive-color="#9a9a9a" size="24" />
              </div>
            </template>
          </van-cell>

          <CategorySelectorCell
            v-if="can_edit_rule && !select_cate"
            ref="cate_selector"
            title="选择分类"
            name="分类"
            v-validate="'required'"
            v-model="cate_list"
            :max="1"
            :multi="false"
            required
          ></CategorySelectorCell>

          <van-cell title="分类" v-show="!can_edit_rule" :value="rule_name"></van-cell>

          <RuleCategorySelectorCell :pt_code="pt_code" :multi="false" title="选择规则" v-model="item_list" v-if="can_edit_rule && select_cate"></RuleCategorySelectorCell>

          <van-cell v-if="item_info.rule_id && item_list.length > 0" :title="item_info.remark">
            <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] }}</span>
            </template>
          </van-cell>

          <div v-show="detail_data.item_id && detail_data.rule_id">
            <van-cell title="选择规则" value="选择了1条规则" is-link></van-cell>
            <van-cell v-if="detail_data.item_id" :title="detail_data.item_name">
              <template slot="label">
                <span class="record color_green" v-if="detail_data.item_min_point <= 0">
                  {{ detail_data.item_range_type == 1 ? detail_data.item_min_point : detail_data.item_min_point + '～' + detail_data.item_max_point }}
                </span>
                <span class="record color_red" v-if="detail_data.item_min_point > 0">
                  + {{ detail_data.item_range_type == 1 ? detail_data.item_min_point : detail_data.item_min_point + '～' + detail_data.item_max_point }}
                </span>
                <span class="type">{{ types_list[detail_data.pt_id] }}</span>
              </template>
            </van-cell>
          </div>
        </van-cell-group>

        <div class="expiryTip" v-show="expiryDay > 0">任务每逾期1天扣{{ expiryPoints }}分，当前逾期{{ expiryDay }}天</div>

        <van-cell-group v-show="detail_data.item_id && detail_data.rule_id">
          <NumberInput
            title="积分"
            v-show="detail_data.rule_id && detail_data.item_range_type == 1"
            :min="detail_data.item_min_point"
            :max="detail_data.item_max_point"
            required
            v-model="data.point"
            name="积分"
            v-validate="'required'"
          ></NumberInput>

          <NumberInput
            title="积分"
            v-show="detail_data.rule_id && detail_data.item_range_type == 2 && detail_data.pid==0"
            :min="detail_data.item_min_point"
            :max="detail_data.item_max_point"
            required
            v-model="data.point"
            name="积分"
            v-validate="'required'"
          ></NumberInput>

           <div class="flex-box flex-v-ce jf" v-show="detail_data.rule_id && detail_data.item_range_type == 2 && detail_data.pid!=0">
             <div>积分</div>
             <div style="color: #ff1e1c;">
                <span v-if="data.point>0">+ {{data.point}}</span>
                <span v-else>- {{data.point}}</span>
             </div>
           </div>
          <NumberInput title="积分" v-show="!detail_data.rule_id" required v-model="data.point" name="积分" v-validate="'required'"></NumberInput>
        </van-cell-group>
        <van-cell-group v-show="!detail_data.item_id && !detail_data.rule_id">
          <NumberInput
            title="积分"
            v-show="item_info.rule_id && item_info.range_type == 1"
            :min="item_info.min_point"
            :max="item_info.min_point"
            required
            v-model="data.point"
            name="积分"
            v-validate="'required'"
          ></NumberInput>
          <NumberInput
            title="积分"
            v-show="item_info.rule_id && item_info.range_type == 2"
            :min="item_info.min_point"
            :max="item_info.max_point"
            required
            v-model="data.point"
            name="积分"
            v-validate="'required'"
          ></NumberInput>
          <NumberInput title="积分" v-show="!item_info.rule_id" required v-model="data.point" name="积分" v-validate="'required'"></NumberInput>
        </van-cell-group>

        <van-cell-group v-show="!detail_data.item_id && detail_data.rule_id">
          <NumberInput title="积分" required v-model="data.point" name="积分" v-validate="'required'"></NumberInput>
        </van-cell-group>

        <van-cell-group>
          <div class="tip" slot="title">奖票多用于优秀表现和重要事项的表彰</div>
          <van-cell center title="发放奖票">
            <template #right-icon>
              <div>
                <van-switch v-model="ticket_count" inactive-color="#9a9a9a" size="24" />
              </div>
            </template>
          </van-cell>
        </van-cell-group>
        <van-cell-group v-if="!isCreator"><EmployeeSelectorCell title="递交审批" v-model="reviewer" :multi="false" :employee_list="superior_list" :use_employee_list="true"></EmployeeSelectorCell></van-cell-group>
        <van-cell-group>
          <van-cell><Mtextarea v-model="data.remark" placeholder="填写意见（选填）"></Mtextarea></van-cell>
        </van-cell-group>

        <div style="padding:0.32rem;"><van-button size="large" @click="sava_btn" type="info">提交</van-button></div>
      </scroller>
    </div>

    <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>
</template>

<script>
import NumberInput from '@/components/common/NumberInput'
import Mtextarea from '@/components/common/Mtextarea'
import EmployeeSelectorCell from '@/components/common/EmployeeSelectorCell'
import RuleCategorySelectorCell from '@/components/common/RuleCategorySelectorCell1'
import CategorySelectorCell from '@/components/common/CategorySelectorCell'
import request from '@/utils/request'
import Vue from 'vue'
import { Collapse, CollapseItem, Switch, Image } from 'vant'
import {getRole_four2} from '@/utils/auth'

Vue.use(Image)
Vue.use(Collapse)
Vue.use(Switch)
Vue.use(CollapseItem)
var isCreator = getRole_four2()
export default {
  name: 'performance',
  components: {
    Mtextarea,
    EmployeeSelectorCell,
    RuleCategorySelectorCell,
    CategorySelectorCell,
    NumberInput
  },
  data () {
    return {
      isCreator: isCreator,
      pt_code: '',
      select_cate: false,
      item_name: '',
      ticket_count: false,
      cate_list: [],
      item_info: {},
      item_list: [],
      item_show: false,
      can_edit_rule: true,
      types_list: {},
      rule_list: [],
      rule_name: '',
      data: {
        review_id: 0,
        action: 'complete',
        rule_id: 0,
        item_id: 0,
        point: 0,
        reviewer_id: 0,
        remark: '',
        ticket_count: 0
      },
      expiryDay: null,
      expiryPoints: null,
      reviewer: [],
      detail_data: {},
      superior_list: this.$store.getters.user_info.employee_detail.superior_list
    }
  },
  methods: {
    item_del () {
      this.item_show = false
      for (let i in this.item_list) {
        this.$set(this.item_list[i], 'checked', false)
      }
      this.item_info = {}
      this.data.point = 0
      this.data.item_id = 0
    },
    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.data.point = item.min_point
      this.data.item_id = item.id
      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
      for (let i in data) {
        if (this.data.item_id == data[i].id) {
          this.item_confirm(data[i], i)
        }
      }
    },
    showLoading () {
      this.$toast.loading({
        loadingType: 'spinner',
        message: '正在处理'
      })
    },
    get_point_types () {
      let self = this
      for (let i in this.$store.getters.point_types) {
        self.types_list[this.$store.getters.point_types[i].id] = this.$store.getters.point_types[i].name
      }
    },
    choseItem () {
      if (this.item_name == '') {
        this.item_show = true
      } else {
        this.item_show = false
      }
    },
    get_data () {
      this.$toast.loading({ message: '正在加载' })
      request('get', '/api/integral/review', { review_id: this.data.review_id })
        .then(res => {
          this.data.item_id = res.data.data.item_id
          this.data.point = res.data.data.point
          this.item_name = res.data.data.item_name
          this.pointTypeId = res.data.data.pt_id
          res.data.data.detail.forEach(element => {
            if (element.key === '逾期天数') {
              this.expiryDay = element.value
            }
            if (element.key === '逾期扣分') {
              this.expiryPoints = element.value
            }
          })
          if (res.data.data.pt_id > 0) {
            this.pt_code = res.data.data.pt_code
          }
          if (res.data.data.rule_id > 0) {
            this.cate_list = [{ id: res.data.data.rule_id, name: res.data.data.rule_name }]
            this.can_edit_rule = false
            this.rule_name = res.data.data.rule_name
          }
          this.detail_data = res.data.data
        }).finally(() => this.$toast.clear())
    },
    send () {
      let self = this
      if (self.data.point === 0) {
        self.$toast('积分不能为0')
        return
      }
      self.validatePointPermission([self.data], self.pointTypeId, err => {
        if (err) {
          self.$notify({ type: 'danger', message: err.message })
        } else {
          self.send_loading = true
          self.$toast.loading({ message: '正在处理' })
          request('post', '/api/integral/review', self.data)
            .then(res => {
              self.send_loading = false
              self.$toast.clear()
              if (res.data.code == 1) {
                self.$toast.success(res.data.msg)
                self.$keep_alive_update('update_approval_detail', self.data)
                self.$keep_alive_update('update_approval_list', self.data)
                setTimeout(() => {
                  self.$route_back()
                }, 500)
              } else {
                self.$toast(res.data.msg)
                self.$keep_alive_update('withdraw_apply', self.data)
              }
            })
            .catch(e => {
              self.send_loading = false
              self.$toast.clear()
            })
        }
      })
    },
    sava_btn () {
      let self = this
      self.$validator.validate().then(result => {
        if (!result) {
          self.$notify({ type: 'danger', message: self.$validator.errors.items[0].msg })
        } else {
          self.send()
        }
      })
    },
    validatePointPermission (items, ptId, callback) {
      const userInfo = this.$store.getters.user_info
      const pointConfig = userInfo.point_config
      const index = pointConfig.point_limit.findIndex(o => o.pt_id === ptId)
      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

          // 20200731
          /** 在 ruleLimitCheck 为0的时候， 超出积分权限都要选择审批人提交 */
          this.validateRuleLimit(items, callback, a => {
            return !(
              (a.reviewer_id && a.point !== 0 && a.rule_id > 0) ||
              (a.reviewer_id <= 0 && a.item_id > 0 && ruleLimitCheck && a.point !== 0 && a.point <= maxPointPermission && Math.abs(a.point) <= maxPointPermission) ||
              (a.reviewer_id <= 0 && !ruleLimitCheck && this.pointTypeId == 3 && a.rule_id > 0) ||
              (a.reviewer_id <= 0 && a.item_id >= 0 && a.point !== 0 && a.point <= maxPointPermission && Math.abs(a.point) <= maxPointPermission && a.rule_id > 0)
            )
          })

          // /** 在 ruleLimitCheck 为0的时候， 超出积分权限都要选择审批人提交 */
          // if (ruleLimitCheck === 0) {
          //   this.validateRuleLimit(items, callback, a => a.reviewer_id && a.point > 0 && a.rule_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()
    }
  },
  watch: {
    select_cate (val) {
      this.item_list = []
      this.cate_list = []
    },
    item_list (val) {
      console.log(val)
      if (val.length == 0) {
        this.data.item_id = 0
        this.data.rule_id = 0
        this.item_info = {}
      } else {
        this.data.point = val[0].min_point
        this.data.rule_id = val[0].rule_id
        this.data.item_id = val[0].id
        this.item_info = val[0]
      }
    },
    ticket_count (val) {
      if (val) {
        this.data.ticket_count = 1
      } else {
        this.data.ticket_count = 0
      }
    },
    cate_list (val) {
      if (val.length == 0) {
        this.data.rule_id = 0
      } else {
        this.data.rule_id = val[0].id
      }
    },
    rule_list (val, old) {
      if (val.length == 0) {
        this.data.item_id = 0
        this.data.rule_id = 0
      } else {
        this.data.rule_id = val[0].rule_id
        this.data.item_id = val[0].id
      }
    },
    reviewer (val, old) {
      if (val.length == 0) {
        this.data.reviewer_id = 0
      } else {
        this.data.reviewer_id = val[0].id
      }
    }
  },
  created () {
    if (this.$route.query.review_id) {
      this.data.review_id = this.$route.query.review_id
    }
    this.get_point_types()
    this.get_data()
  }
}
</script>

<style scoped>
.body_com {
  height: calc(100% - 0.92rem);
  position: relative;
}

.item-clear-btn {
  margin-right: -0.32rem;
}

/deep/ .item-clear-btn span {
  font-size: 0.2rem;
}
.jf{
  padding: 0.24rem 0.32rem;
  font-size: 0.32rem;
  color: #323233;
}
.jf div:nth-child(1){
    width: 1.8rem;
    position: relative;
}
.jf div:nth-child(1)::before {
    position: absolute;
    left: -0.2rem;
    color: #ee0a24;
    font-size: 0.28rem;
    content: '*';
}
.expiryTip {
  padding: 0.2rem 0.32rem 0.1rem 0.32rem;
  color: #ee0a24;
  font-size: 0.24rem;
}
</style>
