<template>
  <div>
    <van-nav-bar :title="type==1?'录入A分':'奖扣B分'" left-text="返回" @click-left="$route_back" left-arrow></van-nav-bar>
    <div class="body_com has_header">
      <scroller :isNeed="isNeed">
        <van-cell-group>
          <EmployeeSelectorCell
            use_employee_list
            required
            bar_title="选择录入对象"
            title="录入对象"
            name="录入对象"
            v-validate="'required'"
            :employee_list="manage_scope"
            v-model="employee_list"
            :multi="true"
            :max="10"
          ></EmployeeSelectorCell>
        </van-cell-group>

        <div v-for="(item, index) in diy_rule_item" :key="index">
          <van-cell-group>
            <div class="item-title" slot="title">
              {{'第'+(index+1)+'条'}}
              <a v-if="diy_rule_item.length > 1"
                class="item-del-btn color-blue"
                @click="diy_item_del(index)"
              >删除</a>
            </div>
            <van-cell title="指定规则">
              <template slot="right-icon">
                <!-- <div class="switchall" :class="{scitchBlue:!item.diy}"> -->
                <div>
                  <van-switch v-model="item.diy" inactive-color="#9a9a9a" size="24"/>
                </div>
              </template>
            </van-cell>
            <RuleCategorySelectorCell
              v-if="item.diy && showRule"
              required
              name="选择规则"
              v-validate="'required'"
              ref="rule_selector"
              title="选择规则"
              v-model="item.items"
              :multi="false"
              :max="20"
              :pt_code="pt_code"
            ></RuleCategorySelectorCell>
            <CategorySelectorCell
              v-if="!item.diy"
              title="选择分类"
              name="选择分类"
              v-validate="'required'"
              v-model="item.rule_cate"
              :max="1"
              :multi="false"
              required
            ></CategorySelectorCell>

            <NumberInput
              v-model="item.point"
              :min.sync="item.min_point"
              title="积分"
              name="积分"
              required
              v-validate="'required'"
              :border="item.point_remark == ''"
              :max.sync="item.max_point"
            ></NumberInput>
            <div v-if="item.point_remark != ''" class="point-remark-box">{{item.point_remark}}</div>
            <DateCell
              required
              title="发生时间"
              v-validate="'required'"
              name="日期"
              v-model="item.event_time"
            ></DateCell>
            <!-- <div v-if="reviewed_score.length > 0"> -->
            <div v-if="!isCreator">
              <EmployeeSelectorCell
                bar_title="选择递交审批人"
                title="递交审批"
                name="递交审批"
                v-model="item.reviewer_list"
                :multi="false"
                :max="1"
                use_employee_list
                :employee_list="reviewed_score"
              ></EmployeeSelectorCell>
            </div>
            <!-- <van-cell v-if="reviewed_score.length == 0" title="递交审批" is-link @click.stop="$toast('您没有递交审批人，请联系管理员')" /> -->

            <van-cell required>
              <Mtextarea
                v-model="item.remark"
                placeholder="请输入事件内容"
                name="申请事由"
                v-validate="'required|max:100'"
                :text_max="100"
                :imgs_max="3"
                images
                speech
                :imgs.sync="item.files"
              ></Mtextarea>
            </van-cell>
          </van-cell-group>
        </div>

        <van-cell-group>
          <van-cell class="add_item_cell" title="增加一条" @click="add_diy_item" icon="plus"></van-cell>
        </van-cell-group>

        <div style="padding:0.32rem;">
          <van-button size="large" @click="data_verify" :disabled="subloading" type="info">提交</van-button>
        </div>
        <div style="height: 1rem;"></div>
      </scroller>
    </div>
    <van-popup v-model="showRes" style=" width: 100vw; height: 100vh;">
      <!-- <div style="height: 20px;background-color: #26A2FF;"></div> -->
      <div style="background-color: #26A2FF;"></div>
      <van-nav-bar title="返回结果" left-text="返回" @click-left="back()" left-arrow></van-nav-bar>
      <div class="rentrun">
        <div class="successful_alert">
          <van-row class="head_icon" type="flex" align="center" justify="center">
            <icon name="overdue_deduction" v-if="total === err_count" class="overdue_deduction"></icon>
            <icon name="sucessful_icon" v-else class="sucessful_icon"></icon>
          </van-row>
          <van-row style="text-align: center; padding: 0.32rem;">
            <van-col v-if="total === err_count" span="24">提交失败</van-col>
            <van-col v-else span="24">提交成功</van-col>
          </van-row>
        </div>

        <van-row class="row_line_bg">
          <van-col span="24">
            <span class="color_blue">提交成功: {{success_count}}</span> /
            <span class="color_red">提交失败：{{err_count}}</span> /
            <span class="color_grey">已提交：{{total}}</span>
          </van-col>
        </van-row>

        <div class="body_com result has_header">
          <scroller>
            <van-cell-group>
              <van-cell v-for="(item,index) in list" :key="index" :label="item.msg || item.rule_item" >
                <template slot="title">
                  <Wxopendata type="userName" :openid="item.target"></Wxopendata>
                </template>
                <template #value>
                  <span v-if="item.point != 0" :class="item.point>0?'color_blue':'color_red'">{{item.point}}</span>
                </template>
              </van-cell>
            </van-cell-group>
          </scroller>
        </div>
        <!--  style="border-top: 1px solid #f1f1f1;" -->
        <van-row>
          <van-col span="12" :offset="6">
            <van-button type="info" @click="back()" block>我知道了</van-button>
        </van-col>
          <!--
          <van-col span="12">
            <div class="buttom_btn one" @click="go">+ 继续添加</div>
          </van-col>
          <van-col span="12">
            <div class="buttom_btn color_blue" @click="$router.replace('/')">> 回到首页</div>
          </van-col>
          -->
        </van-row>
      </div>
    </van-popup>

  </div>
</template>
<script>
import request from '@/utils/request'
import {getRole_four2} from '@/utils/auth'
import Mtextarea from '@/components/common/Mtextarea'
import NumberInput from '@/components/common/NumberInput'
import EmployeeSelectorCell from '@/components/common/EmployeeSelectorCell'
import RuleCategorySelectorCell from '@/components/common/RuleCategorySelectorCell1'
import CategorySelectorCell from '@/components/common/CategorySelectorCell'
import DateCell from '@/components/common/DateCell'
import moment from 'moment'
import Vue from 'vue'
import {Switch} from 'vant'

var getRole=getRole_four2();
Vue.use(Switch)
export default {
  name: 'integral_entry_b',
  components: {
    DateCell,
    Mtextarea,
    EmployeeSelectorCell,
    RuleCategorySelectorCell,
    CategorySelectorCell,
    NumberInput
  },
  watch: {
    rule_item: {
      handler (val) {
        let date = moment().format('YYYY-MM-DD')
        let pt_id = 0
        for (let i in this.types_list_array) {
          if (this.types_list_array[i].code == 'BF') {
            pt_id = this.types_list_array[i].id
          }
        }
        for (let i in val) {
          if (typeof (val[i]['reviewer_id']) === 'undefined') {
            this.rule_item[i]['reviewer_id'] = 0
          }
          if (typeof (val[i]['rule_id']) === 'undefined') {
            this.rule_item[i]['rule_id'] = val[i].rule_id
          }
          if (typeof (val[i]['item_id']) === 'undefined') {
            this.rule_item[i]['item_id'] = val[i].id
          }
          if (typeof (val[i]['event_time']) === 'undefined') {
            this.rule_item[i]['event_time'] = date
          }
          if (typeof (val[i]['point']) === 'undefined') {
            this.rule_item[i]['point'] = val[i].min_point
          }
          if (typeof (val[i]['remark']) === 'undefined') {
            this.rule_item[i]['remark'] = ''
          }
          if (typeof (val[i]['pt_id']) === 'undefined') {
            this.rule_item[i]['pt_id'] = 0
          }
          if (typeof (val[i]['files']) === 'undefined') {
            this.rule_item[i]['files'] = []
          }
          if (typeof (val[i]['remark']) === 'undefined') {
            this.rule_item[i]['remark'] = ''
          }
          if (typeof (val[i]['reviewer_list']) === 'undefined') {
            this.rule_item[i]['reviewer_list'] = []
          }
          if (val[i].reviewer_list && val[i].reviewer_list.length > 0 && val[i]['reviewer_id'] != val[i].reviewer_list[0].id) {
            this.rule_item[i]['reviewer_id'] = val[i].reviewer_list[0].id
          } else if (val[i].reviewer_list.length == 0) {
            this.rule_item[i]['reviewer_id'] = 0
          }
        }
        if (this.rule_item.length > 0) {
          this.entry_type = 1
        }
        if (this.rule_item_change_count < 1) {
          this.rule_item_change_count++
          this.rule_item = JSON.parse(JSON.stringify(this.rule_item))
        } else if (this.rule_item_change_count == 1) {
          this.rule_item_change_count = 0
        }
      },
      deep: true
    },
    diy_rule_item: {
      handler (val, old) {
        for (let i in val) {
          if (!val[i].diy) {
            if (val[i].rule_cate && val[i].rule_cate.length > 0 && val[i]['rule_id'] != val[i].rule_cate[0].id) {
              this.diy_rule_item[i]['rule_id'] = val[i].rule_cate[0].id
            } else if (val[i].rule_cate.length == 0) {
              this.diy_rule_item[i]['rule_id'] = 0
              this.diy_rule_item[i]['item_id'] = 0
            }
            this.diy_rule_item[i]['point_remark'] = ''
            delete this.diy_rule_item[i]['min_point']
            delete this.diy_rule_item[i]['max_point']
          } else {
            if (val[i].items && val[i].items.length > 0 && val[i]['item_id'] != val[i].items[0].id) {
              this.diy_rule_item[i]['item_id'] = val[i].items[0].id
              this.diy_rule_item[i]['rule_id'] = val[i].items[0].rule_id
              this.diy_rule_item[i]['point'] = val[i].items[0].min_point
              this.diy_rule_item[i]['min_point'] = val[i].items[0].min_point
              this.diy_rule_item[i]['max_point'] = val[i].items[0].max_point
              this.diy_rule_item[i]['remark'] = val[i].items[0].remark
              if (val[i].items[0].range_type == 1) {
                this.diy_rule_item[i]['point_remark'] = '固定：' + val[i].items[0].min_point + this.types_list_map[val[i].items[0].pt_id].name
              } else {
                this.diy_rule_item[i]['point_remark'] = '范围(可修改)：' + val[i].items[0].min_point + '至' + val[i].items[0].max_point + this.types_list_map[val[i].items[0].pt_id].name + ''
              }
            } else if (val[i].items.length == 0) {
              this.diy_rule_item[i]['rule_id'] = 0
              this.diy_rule_item[i]['item_id'] = 0
              this.diy_rule_item[i]['point_remark'] = ''
            }
          }

          if (val[i].reviewer_list && val[i].reviewer_list.length > 0 && val[i]['reviewer_id'] != val[i].reviewer_list[0].id) {
            this.diy_rule_item[i]['reviewer_id'] = val[i].reviewer_list[0].id
          } else if (val[i].reviewer_list.length == 0) {
            this.diy_rule_item[i]['reviewer_id'] = 0
          }
        }
      },
      deep: true
    },
    employee_list: function (val) {
      if (val.length > 0) {
        let superior_arr = []
        this.data.members = []
        // this.reviewed_score = []
        let employee_map = window.plus ? JSON.parse(plus.storage.getItem('SET_EMPLOYEE_MAP')) : JSON.parse(localStorage.getItem('SET_EMPLOYEE_MAP'))
        val.forEach(element => {
          this.data.members.push(element.id)
          if (employee_map[element.id].superior_list) {
            superior_arr.push(employee_map[element.id].superior_list)
          }
        })
        // let reviewed_arr = this.intersection(superior_arr)
        // for (const i in employee_map) {
        //   reviewed_arr.findIndex((item) => {
        //     if (item == employee_map[i].id) {
        //       this.reviewed_score.push(employee_map[i])
        //     }
        //   })
        // }
      } else {
        this.data.members = []
        // this.reviewed_score = []
      }
    }
  },
  data () {
    let date = moment().format('YYYY-MM-DD')
    let types_list_array = this.$store.getters.point_types
    return {
      isNeed:this.$getCache('isAndroid')==1? false: true,
      manage_scope: this.$store.getters.user_info.employee_detail.manage_scope,
      entry_type: 1,
      types_list_array: types_list_array,
      types_list_map: {},
      pt_code: 'BF',
      pt_id: null,
      data: {
        members: [],
        items: []
      },
      diy_rule_item: [{
        checked: true,
        diy: true,
        items: [],
        event_time: date,
        files: [],
        item_id: 0,
        point: 0,
        pt_id: '0',
        remark: '',
        point_remark: '',
        reviewer_id: 0,
        rule_id: 0,
        reviewer_list: [],
        rule_cate: []
      }],
      types_list: {},
      rule_item: [],
      rule_item_change_count: 0,
      send_loading: false,
      employee_list: [],
      // 1为A分，2为B分
      type: this.$route.query.type,
      subloading: false,
      showRule: false,

      showRes: false,
      list: [],
      err_count: '',
      success_count: '',
      total: '',
      reviewed_score: [],
      isCreator:getRole
    }
  },
  methods: {
    back () {
      this.showRes = false
      this.$route_back()
    },
    init_diy_item () {
      let date = moment().format('YYYY-MM-DD')
      let pt_id = 0
      for (let i in this.types_list_array) {
        if (this.types_list_array[i].code == 'BF' && this.type == 2) {
          pt_id = this.types_list_array[i].id
        }
        if (this.types_list_array[i].code == 'AF' && this.type == 1) {
          pt_id = this.types_list_array[i].id
        }
      }
      this.diy_rule_item = [
        {
          checked: true,
          diy: true,
          point_remark: '',
          items: [],
          event_time: date,
          files: [],
          item_id: 0,
          point: 0,
          pt_id: '0',
          remark: '',
          reviewer_id: 0,
          rule_id: 0,
          reviewer_list: [],
          rule_cate: []
        }
      ]
    },
    add_diy_item () {
      let date = moment().format('YYYY-MM-DD')
      this.diy_rule_item.push({
        checked: true,
        diy: true,
        point_remark: '',
        event_time: date,
        files: [],
        items: [],
        item_id: 0,
        point: 0,
        pt_id: '0',
        remark: '',
        reviewer_id: 0,
        rule_id: 0,
        reviewer_list: [],
        rule_cate: []
      })
    },
    entry_diy () {
      this.$refs['rule_selector'].show_dept_selector = false
      this.entry_type = 2
      this.rule_item = []
    },
    item_del (index) {
      this.rule_item.splice(index, 1)
    },
    diy_item_del (index) {
      this.diy_rule_item.splice(index, 1)
    },
    isNumber (value) {
      return !Number.isNaN(Number(value))
    },
    data_verify () {
      let self = this
      self.$validator.validateAll().then(result => {
        if (!result) {
          self.$notify({type: 'danger', message: self.$validator.errors.items[0].msg})
        } else {
          const pass = this.diy_rule_item.every(item => this.isNumber(item.point) && item.point !== 0)
          if (pass) {
            this.validatePointPermission(this.diy_rule_item, err => {
              if (err) {
                this.$notify({type: 'danger', message: err.message})
              } else {
                self.subloading = true
                this.send()
              }
            })
          } else {
            this.$notify({type: 'danger', message: '积分不能为0'})
          }
        }
      })
    },
    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 === 3)
      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 （ 未完成 0914 ）
          /** 在 ruleLimitCheck 为0的时候， 超出积分权限都要选择审批人提交 */
          // if (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.type == 2 && 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))
          })
          // } else {
          //   /** 在 ruleLimitCheck 为1的时候， 1.选择了规则就不强制选择申请人  2.未选规则超出权限分要提交审批人 */
          //   // this.validateRuleLimit(items, callback, b => !b.diy && 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(`第${index + 1}条输入分值超出权限，请选择审批人递交`)) : callback(new Error(`第${index + 1}条输入分值超出权限，请选择审批人递交`))
          return false
        }
        return true
      })
      res && callback()
    },
    send () {
      let self = this
      self.send_loading = true
      self.$toast.loading({
        message: '正在处理'
      })
      let data = null
      // self.diy_rule_item[0].pt_id = self.pt_id
      this.diy_rule_item.forEach(element => {
        element.pt_id = self.pt_id
      })
      self.data.items = self.diy_rule_item
      data = self.data
      request('post', self.type == 1 ? '/api/integral/review/a/entry' : '/api/integral/point/entry', data).then(res => {
        self.send_loading = false
        self.$toast.clear()
        if (res.data.code == 1) {
          const resultData = res.data.data
          this.list = resultData.list
          this.err_count = resultData.fail_count
          this.success_count = resultData.success_count
          this.total = resultData.total
          this.showRes = true
          let date = moment().format('YYYY-MM-DD')
          let types_list_array = self.$store.getters.point_types
          let pt_id = 0
          for (let i in types_list_array) {
            if (types_list_array[i].code == 'BF' && self.type == 2) {
              pt_id = types_list_array[i].id
            }
            if (types_list_array[i].code == 'AF' && self.type == 1) {
              pt_id = types_list_array[i].id
            }
          }
          self.data.members = []
          self.data.items = []
          self.rule_item = []
          self.employee_list = []
          self.diy_rule_item = [{
            checked: true,
            diy: true,
            items: [],
            point_remark: '',
            event_time: date,
            files: [],
            item_id: 0,
            point: 0,
            pt_id: pt_id,
            remark: '',
            reviewer_id: 0,
            rule_id: 0,
            reviewer_list: [],
            rule_cate: []
          }]
          if (window.plus) {
            setTimeout(() => {
              plus.navigator.setStatusBarStyle('dark')
              document.documentElement.style.backgroundColor = '#fff'
            }, 100)
          }
        } else {
          self.$toast(res.data.msg)
        }
      }).catch(e => {
        self.send_loading = false
        self.$toast.clear()
      }).finally(() => { self.subloading = false })
    },
    intersection (arr) {
      const arrSet = []
      const intersectionSet = new Set()
      arr.forEach(items => {
        arrSet.push(new Set(items.map(item => item.id)))
        items.forEach(item => intersectionSet.add(item.id))
      })

      return [...intersectionSet].filter(item => arrSet.every(set => set.has(item)))
    }
  },
  mounted () {
    this.reviewed_score = this.$store.getters.user_info.employee_detail.superior_list
    for (let i in this.types_list_array) {
      this.types_list_map[this.types_list_array[i].id] = this.types_list_array[i]
    }
    //刷新当前角色下级上级
    request('get', '/api/employee/detail').then(res => {
        let list = res.data.data.user
        this.manage_scope = list.employee_detail.manage_scope
        this.reviewed_score = list.employee_detail.superior_list
      })
  },
  activated () {
    this.type = this.$route.query.type
    for (let i in this.types_list_array) {
      if (this.types_list_array[i].code == 'BF' && this.type == 2) {
        this.pt_id = this.types_list_array[i].id
      }
      if (this.types_list_array[i].code == 'AF' && this.type == 1) {
        this.pt_id = this.types_list_array[i].id
      }
    }
    this.pt_code = this.$route.query.type == 2 ? 'BF' : 'AF'
    this.showRule = false
    this.$nextTick(() => {
      this.showRule = true
    })
  }
}
</script>
<style scoped lang="less">
  .body_com {
    height: calc(100% - 0.92rem);
    overflow-y: scroll;
    position: relative;
  }
  .body_com.result{
    height: calc(100vh - 6.6rem);
    position: relative;
  }
  .add_item_cell .van-icon {
    color: #1989fa;
  }

  .add_item_cell .van-cell__title span {
    color: #1989fa;
  }

  .color-blue {
    color: #1989fa;
  }

  .item-del-btn {
    float: right;
  }

  .point-remark-box {
    color: #969799;
    padding: 0.16rem 0.32rem;
    position: relative;
    padding-top: 0;
    padding-left: 2.1rem;
    font-size: 0.24rem;
  }

  .point-remark-box:after {
    position: absolute;
    box-sizing: border-box;
    content: ' ';
    pointer-events: none;
    right: 0;
    bottom: 0;
    left: 0.32rem;
    border-bottom: 0.02rem solid #ebedf0;
    -webkit-transform: scaleY(0.5);
    transform: scaleY(0.5);
  }
  .rentrun {
  width:100vw;
  background: #fff;
}
.successful_alert{
  padding-top:0.5rem;
}
.successful_alert /deep/ .head_icon .sucessful_icon{
  width:1.28rem;
  height:1.28rem;
  color:#26A2FF;
  padding-top:0.5rem;
}
.successful_alert /deep/ .head_icon .overdue_deduction{
  width:1.28rem;
  height:1.28rem;
  color:#F56C6C;
  padding-top:0.5rem;
}

.row_line_bg{
  background: #f1f1f1;
  font-size: 0.32rem;
  padding: 0.1rem 0.32rem;
}

.buttom_btn{
  line-height: 0.83rem;
  text-align: center;
  font-size: 0.32rem;
  position: relative;
  /* color: #909399 */
}
.buttom_btn.one::after{
  content: '';
  width: 1px;
  height: 0.85rem;
  background: #f1f1f1;
  display: block;
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
}

.color_blue{
  color:#26A2FF;
}
.color_red{
  color: #F56C6C;
}
.color_grey{
  color: #909399;
}
</style>
