<template>
  <div class="edit_user_power_box">
    <van-nav-bar :title="title" left-text="返回" @click-left="$route_back" left-arrow></van-nav-bar>
    <div class="body_com has_header">
      <scroller>

        <div class="head-box" v-if="user_info != null">
          <userImage  :img_url="user_info.img_url" :user_name="user_info.name" width="1.5rem" height="1.5rem"></userImage>
          <div class="employee-name"><Wxopendata type="userName" :openid="user_info.name"></Wxopendata></div>
          <div class="role-list">
            <van-tag size="medium" plain type="warning" v-for="(item, index) in roles" :key="index" v-if="item.id == role_id">{{item.remark}}</van-tag>
          </div>
        </div>

        <van-cell-group class="manager_box">
          <div title="什么是管理范围，请提供文案"></div>
          <EmployeeSelectorCell title="管理范围" v-model="getscope" :selected_all="true" :employee_not_select="employee_not_select" :can_select_employee="true"></EmployeeSelectorCell>
        </van-cell-group>

        <van-cell-group class="manager_box">
          <div title="什么是积分权限，请提供文案"></div>
          <van-cell title="积分权限" is-link @click="open_ponit_power(2)"/>
        </van-cell-group>
        <van-cell-group class="manager_box">
          <div title="什么是奖扣目标，请提供文案"></div>
          <van-cell title="奖扣目标" is-link @click="open_ponit_power(1)"/>
        </van-cell-group>

        <div style="padding:0.32rem;">
          <van-button size="large" @click="del" type="danger">删除</van-button>
        </div>

        <div style="height: 1rem;"></div>
      </scroller>
    </div>
    <van-popup v-model="showHelp" class="popup-help__container" position="right">
      <div :style="'padding-top:' + bar_height + 'px;background-color: #26A2FF;'"></div>
      <van-nav-bar title="帮助" left-text="返回" @click-left="showHelp = false" left-arrow/>
      <van-cell-group :border="false">
        <div class="help-desc__content"><span>奖扣任务的说明</span></div>
        <div class="help-sub__content">
          <span>奖扣分权限为了让管理者更好地行使好管理的职权，我们通常会给予他们奖扣分的权利。针对不同的管理岗位，可赋予每个管理者不同的奖扣分权限奖扣分权限不足的将自动递交给其上级审核。</span>
        </div>
        <div class="help-desc__content"><span>B分月奖扣任务</span></div>
        <div class="help-sub__content">
          <span>积分是否能落地，奖扣分的执行最为关键。赋予一定的人员奖扣分任务，比如经理，主管，积分专员，行政人事等，更利于整个积分制管理的落地和实施。月奖扣任务要求相关人员需按照以下1~3种标准执行</span>
        </div>
        <div class="help-item__content"><span>1、对奖分和扣分的分值作要求。未达分值任务的按差额扣分举例说明：奖分任务1000，扣分任务100实际奖分980（差20分），实际扣分90（差10分）奖分、扣分任务均属未达成。差额=20+10=30分</span>
        </div>
        <div class="help-item__content"><span>2、对奖分和扣分的次数作要求。未达次数要求的按标准扣分</span></div>
        <div class="help-item__content"><span>3、对奖分和扣分的比例作要求。未达奖扣比例要求的按标准扣分</span></div>
      </van-cell-group>
    </van-popup>
    <van-popup v-model="show_point_limit_popup" position="right" style="height:100%; width:100%; background-color: rgb(245, 245, 245);">
      <div :style="'padding-top:' + bar_height + 'px;background-color: #26A2FF;'"></div>
      <van-nav-bar :title="setting_title" left-text="返回" @click-left="set_ponit_power_close" @click-right="save_data" left-arrow right-text="保存">
      </van-nav-bar>
      <div class="body_com">
        <scroller>
          <div v-show="setting1_show">
            <integralTypes rightIcon="question-o" rightIconPosition="28%" v-model="limit_list.reward_task_monthly" title="积分是否能落地，奖扣分的执行最为关键。赋予一定的人员奖扣分任务，比如经理，主管，积分专员，行政人事等，更利于整个积分制管理的落地和实施。" >
              <div style="text-align: left;">
                <div class="margin-bottom-5">对奖分分值作任务要求。未达分值任务的按差额扣分</div>
                <div class="margin-bottom-5">举例说明：奖分任务1000，实际奖分980（差额20分），则该执行人员将被扣20分。反之，如实际奖分达到或超出1000分，不对执行人员实行扣分</div>
              </div>
            </integralTypes>
            <integralTypes rightIcon="question-o" rightIconPosition="28%" v-model="limit_list.deduct_task_monthly" class="reward_point" >
              <div style="text-align: left;">
                <div class="margin-bottom-5">对扣分分值作任务要求。未达分值任务的按差额扣分</div>
                <div class="margin-bottom-5">举例说明：扣分任务100，实际扣分80（差额20分），则该执行人员将被扣20分。反之，如实际扣分达到或超出100分，不对执行人员实行扣分</div>
              </div>
            </integralTypes>
            <van-cell-group>
              <div slot="title">对奖分和扣分的执行次数作任务要求</div>
              <van-field label="月奖扣次数" name="月奖扣次数" type="Number" required v-validate="'required'" v-model="limit_list.exec_count" placeholder="输入数值">
                <template slot="right-icon">
                  <smallTip icon="question-o" class="small_tip" position="26%">
                    <div>
                      <div class="margin-bottom-5">举例说明：奖扣次数任务100，实际执行次数95（差5次），假如每少一次扣5分，则该执行人员将被扣5*5=25分。反之，如果任务达标，不对执行人员实行扣分</div>
                    </div>
                  </smallTip>
                </template>
              </van-field>
              <van-field label="每少一次扣" name="每少一次扣分" type="Number" required v-validate="'required'" v-model="limit_list.exec_count_point" placeholder="输入数值">
                <template slot="right-icon">
                  <smallTip icon="question-o" class="small_tip" position="26%">
                    <div>
                      <div class="margin-bottom-5">每少一次：扣x分  </div>
                      <div class="margin-bottom-5">奖扣次数未达任务要求的，每少一次扣对应分值</div>
                    </div>
                  </smallTip>
                </template>
              </van-field>
            </van-cell-group>

            <van-cell-group>
              <div slot="title">对奖分和扣分的比例作任务要求</div>
              <van-field label="月奖扣比例" name="月奖扣比例" class="proportion" type="Number" required v-validate="'required'" v-model="limit_list.reward_ratio" input-align="center" placeholder="奖分比例">
                <template slot="button">
                  <van-field class="deduction_input" v-model="value" input-align="center" disabled placeholder="扣分比例"/>
                  <smallTip icon="question-o" class="small_tip" position="28%">
                    <div>
                      <div class="margin-bottom-5">举例说明：奖扣比例任务10:1，实际执行奖扣比例11:1（管理者当老好人，不敢执行扣分，导致扣分占比过低），则视为未完成，该执行人员将被扣对应分值。反之比例小于10:1，任务为达标，不对执行人员实行扣分</div>
                    </div>
                  </smallTip>
                </template>
                <template slot="right-icon">
                  <span style="padding: 0 0.3rem;">:</span>
                </template>
              </van-field>
            </van-cell-group>
            <!-- <div class="cell_title">奖扣次数每少一次自动扣管理者积分</div> -->

            <van-cell-group>
              <div slot="title">以上数据将作为每月奖扣目标，若不达标，将自动扣管理者积分</div>
              <van-field label="不达标扣" name="不达标扣分" required v-validate="'required'" type="Number" v-model="limit_list.reward_ratio_point" placeholder="输入数值" ></van-field>
            </van-cell-group>
          </div>
          <div v-show="setting2_show">
            <integralTypes :rightShow="false" title="针对不同的管理岗位，可赋予每个管理者不同的奖扣积分权限，权限不足时须递交给其上级审批" v-model="limit_list.point_limit"></integralTypes>

            <van-cell-group>
              <div slot="title">限制奖励出去的B分不超过设置的上限，当达到上限时，将不能继续奖扣B分（不限制审批操作）</div>
              <van-field label="月奖分上限" type="digit" v-model="limit_list.entry_limit" placeholder="无限制"/>
            </van-cell-group>
          </div>
          <div style="height: 1rem;"></div>
        </scroller>
      </div>
    </van-popup>

  </div>
</template>
<script>
import request from '@/utils/request'
import EmployeeSelectorCell from '@/components/common/EmployeeSelectorCell'
import integralTypes from '@/components/power/integral_types'
import userImage from '@/components/common/user_image.vue'
import smallTip from '@/components/common/smallTip'

export default {
  // 数据
  data () {
    return {
      role_id: 0,
      show_point_limit_popup: false,
      bar_height: 0,
      setting1_show: false,
      setting2_show: false,
      title: '管理者权限',
      setting_title: '积分权限',
      showHelp: false,
      limit_list: {
        deduct_task_monthly: [],
        point_limit: [],
        reward_task_monthly: [],
        employee_id: this.$route.query.id,
        reward_ratio: '',
        exec_count: '',
        exec_count_point: '',
        reward_ratio_point: '',
        entry_limit: ''
      },
      user_info: null,
      getPerson: [],
      getscope: [],
      roles: [],
      mangerId: [],
      point_types: this.$store.getters.point_types,
      listid: [],
      first_load: true,
      value: 1,
      limit_list_copy: null,
      employee_not_select: [],
      employee_map: {},
    }
  },
  watch: {
    getscope (val) {
      let newarray = []
      for (let i = 0; i < val.length; i++) {
        newarray.push(val[i].id)
      }
      this.listid = newarray
      if (!this.first_load) {
        this.ScopeGet()
      }
      this.first_load = false
    }
  },
  // 组件
  components: {
    EmployeeSelectorCell, integralTypes, userImage, smallTip
  },
  // 方法
  methods: {
    del () {
      let self = this
      this.$dialog.confirm({
        title: '删除管理者',
        message: '确定要删除当前管理者吗？'
      }).then(() => {
        self.$toast.loading({
          mask: true,
          message: '处理中...'
        })
        request('delete','/api/role/user',{role_id: self.role_id, employee_id: self.$route.query.id}).then((res) => {
          self.$toast.clear()
          if (res.data.code == 1) {
            self.$toast.success('删除成功')
            this.$store.dispatch('get_employee_map', true).then(res => {})
            self.$keep_alive_update('del_user_list', 'str')
            setTimeout(() => {
              self.$route_back()
            }, 300)
          } else {
            self.$toast(res.data.msg)
          }
        })
      })
    },
    // 加载
    showLoading () {
      this.$toast.loading({
        loadingType: 'spinner',
        message: '正在处理'
      })
    },
    // 查询权限
    get_power_list () {
      let self = this
      self.showLoading()
      request('get','/api/integral/employee/limit',{employee_id: self.$route.query.id}).then((res) => {
        if (res.data.code == '1') {
          if (res.data.data.point_limit.length == 0) {
            for (let j in self.point_types) {
              if (self.point_types[j].code == 'BF' || self.point_types[j].code == 'AF') {
                res.data.data.point_limit.push({
                  name: self.point_types[j].name + '权限',
                  pt_id: self.point_types[j].id,
                  point: 0
                })
              }
            }
            self.limit_list.point_limit = res.data.data.point_limit
          } else {
            const {point_limit} = res.data.data
            for (let j in point_limit) {
              if (point_limit[j].pt_id === 2 || point_limit[j].pt_id === 3) {
                self.limit_list.point_limit.push(point_limit[j])
              }
            }
          }
          if (res.data.data.deduct_task_monthly.length == 0) {
            for (let j in self.point_types) {
              if (self.point_types[j].code == 'BF') {
                res.data.data.deduct_task_monthly.push({name: '月扣分任务', pt_id: self.point_types[j].id, point: 0})
              }
            }
            self.limit_list.deduct_task_monthly = res.data.data.deduct_task_monthly
          } else {
            for (let j in res.data.data.deduct_task_monthly) {
              if (res.data.data.deduct_task_monthly[j].pt_id === 3) {
                self.limit_list.deduct_task_monthly.push({
                  name: '月扣分任务',
                  pt_id: res.data.data.deduct_task_monthly[j].pt_id,
                  point: res.data.data.deduct_task_monthly[j].point
                })
              }
            }
          }
          if (res.data.data.reward_task_monthly.length == 0) {
            for (let j in self.point_types) {
              if (self.point_types[j].code == 'BF') {
                res.data.data.reward_task_monthly.push({name: '月奖分任务', pt_id: self.point_types[j].id, point: 0})
              }
            }
            self.limit_list.reward_task_monthly = res.data.data.reward_task_monthly
          } else {
            for (let j in res.data.data.reward_task_monthly) {
              if (res.data.data.reward_task_monthly[j].pt_id === 3) {
                self.limit_list.reward_task_monthly.push({
                  name: '月奖分任务',
                  pt_id: res.data.data.reward_task_monthly[j].pt_id,
                  point: res.data.data.reward_task_monthly[j].point
                })
              }
            }
          }
          self.limit_list.reward_ratio = res.data.data.reward_ratio
          self.limit_list.exec_count = res.data.data.exec_count
          self.limit_list.exec_count_point = res.data.data.exec_count_point
          self.limit_list.reward_ratio_point = res.data.data.reward_ratio_point
          if (res.data.data.entry_limit == '-1') {
            self.limit_list.entry_limit = ''
          } else {
            self.limit_list.entry_limit = res.data.data.entry_limit
          }
        } else {
          self.$toast(res.data.msg)
        }
      }).catch((e) => {
        self.$toast(e)
      })
    },
    // 管理范围保存
    ScopeGet () {
      let self = this
      self.showLoading()
      let params = {
        employee_id: self.$route.query.id, // 管理者id
        id: self.listid // 管理范围id
      }
      request('post','/api/employee/scope', params).then((res) => {
        self.$toast.clear()
        if (res.data.code == 1) {
          self.$toast('保存成功')
        } else {
          self.$toast(res.data.msg)
        }
      }).catch((e) => {
        self.$toast.clear()
      })
    },
    // 用户积分权限保存
    save_data () {
      let self = this
      self.$validator.validate().then(result => {
        if (!result) {
          self.$notify({type: 'danger', message: self.$validator.errors.items[0].msg})
        } else {
          if (self.limit_list.deduct_task_monthly[0].point === '') {
            self.$notify({type: 'danger', message: '月扣分任务不能为空'})
            return false
          } else if (self.limit_list.point_limit[0].point === '') {
            self.$notify({type: 'danger', message: 'A分不能为空'})
            return false
          } else if (self.limit_list.point_limit[1].point === '') {
            self.$notify({type: 'danger', message: 'B分不能为空'})
            return false
          } else if (self.limit_list.reward_task_monthly[0].point === '') {
            self.$notify({type: 'danger', message: '月奖分任务不能为空'})
            return false
          }
          // else if (parseInt(self.limit_list.entry_limit) > 0 && (self.setting2_show || self.setting1_show)) {
          //   for (let i = 0; i < self.limit_list.point_limit.length; i++) {
          //     if (Number(self.limit_list.point_limit[i].point) > self.limit_list.entry_limit) {
          //       self.$notify({type: 'danger', message: '月奖分上限不能低于AB分'})
          //       return false
          //     }
          //   }
          // }
          self.showLoading()
          self.limit_list['employee_id'] = self.$route.query.id
          let data = JSON.parse(JSON.stringify(self.limit_list))
          data.entry_limit == '' ? data.entry_limit = '-1' : ''
          request('post','/api/integral/employee/limit', data).then((res) => {
            self.$toast.clear()
            if (res.data.code == 1) {
              data.entry_limit == '' ? self.limit_list.entry_limit = '-1' : ''
              self.$toast.success('保存成功')
              self.show_point_limit_popup = false
            } else {
              self.$toast(res.data.msg)
            }
          }).catch((e) => {
            self.$toast.clear()
          })
        }
      })
    },
    get_employee_info (id) {
      let self = this
      self.showLoading()
      if(window.plus){
        self.employee_map = JSON.parse(plus.storage.getItem('SET_EMPLOYEE_MAP'))
      }else{
        self.employee_map = JSON.parse(localStorage.getItem('SET_EMPLOYEE_MAP'))
      }
      for (const key in self.employee_map) {
        self.employee_map[key].role_list.forEach(element => {
          if (element.name == 'creator') {
            self.employee_not_select.push(self.employee_map[key].id)
          }
        })
      }
      request('get','/api/employee/info',{id: id}).then((res) => {
        if (res.data.code == 1) {
          self.getscope = res.data.data.employee_detail.manage_scope
          self.roles = res.data.data.employee_detail.role_list
          self.getPerson = [{name: res.data.data.name, id: res.data.data.id, img_url: res.data.data.img_url}]
          self.user_info = res.data.data
          self.employee_not_select.push(res.data.data.id)
        }
        self.$toast.clear()
      }).catch((e) => {

      })
    },
    // 打开弹窗
    open_ponit_power (type) {
      if (type == 1) {
        this.setting1_show = true
        this.setting2_show = false
        this.setting_title = '奖扣目标'
      } else if (type == 2) {
        this.setting_title = '积分权限'
        this.setting1_show = false
        this.setting2_show = true
      }

      this.limit_list_copy = this.limit_list
      this.show_point_limit_popup = true
    },
    set_ponit_power_close () {
      this.show_point_limit_popup = false
    }
  },
  mounted () {
    let self = this
    self.get_power_list()
    self.get_employee_info(self.$route.query.id)
    self.role_id = self.$route.query.role_id
    if (window.plus) {
      self.bar_height = window.plus.navigator.getStatusbarHeight()
    }
  }
}
</script>
<style scoped lang="less">
  .body_com {
    height: calc(100% - 0.92rem);
    position: relative;
  }

  .reward_point /deep/ .van-cell-group {
    margin-top: 0;
  }

  .popup-help__container {
    width: 100%;
    height: 100%;
    background: #fff;

    & .help-desc__content {
      padding: 0.24rem 0.32rem;
      font-size: 0.32rem;
      color: #303133;
      font-weight: 600;
      text-indent: 2em
    }

    & .help-sub__content {
      padding: 0 0.32rem;
      color: #666;
      font-size: 0.28rem;
      font-weight: 400;
      text-indent: 2em
    }

    & .help-item__content {
      padding: 0.1rem 0.32rem;
      color: #666;
      font-size: 0.28rem;
      font-weight: 400;
    }
  }

  .van-cell-group__title {
    padding: 0.24rem 0.32rem 0.08rem 0.32rem;
  }

  .cell_title {
    padding: 0.08rem 0.32rem 0.24rem 0.32rem;
    color: #969799;
    font-size: 0.28rem;
    line-height: 0.32rem;
  }
  .proportion{
    & .deduction_input {
      padding: 0;
      width: 25vw;
      &::after{
        border-bottom-color: transparent;
      }
    }
    /deep/ & .van-field__button{
      display: flex;
    }
  }

  .head-box{padding:0.5rem 1rem; text-align: center;}
  .small_tip{
    text-align: left;
  }
  /deep/ .van-cell-group__title .tip{
    font-size: 0.28rem;
  }
  .margin-bottom-5{
    margin-bottom: 0.2rem;
  }
</style>
