<template>
  <div class="efficiency_task_box">
    <van-nav-bar :title="title" left-text="返回" @click-left="$route_back" left-arrow></van-nav-bar>
    <div class="body_com has_header">
      <scroller ref="my_scroller">
        <van-cell-group>
          <van-cell required title="月份绩效" is-link @click="show_date = true" :value="datetime"></van-cell>
        </van-cell-group>
        <van-cell-group>
        <!-- <div class="tip red" v-if="performance_ex" slot="title">{{datetime}}已有绩效，<span @click="efficiency_detail">去查看</span></div> -->

        <EmployeeSelectorCell  bar_title="选择执行人" required v-validate="'required'" title="执行人" use_employee_list :employee_list="executor_scope" :include_self="false" v-model="employee_list"  :multi="true" />

        </van-cell-group>
        <van-cell-group>
          <div class="tip" slot="title">任务按预期完成可得月平衡分，最终得分根据实际情况上下浮动</div>
          <van-field required label="月平衡分" name="月平衡分" type="Number" v-model="score" right-icon="warning-o" @click-right-icon="tipsMsg" placeholder="请输入分值" />
        </van-cell-group>
        <van-cell-group>
          <div class="tip" slot="title">建议部门经理或人事主管作为月绩效终审人</div>
          <EmployeeSelectorCell bar-title="选择终审人" required v-validate="'required'" title="终审人" use_employee_list :employee_list="reviewed_score" v-model="reviewed"  :multi="false" />
        </van-cell-group>
        <van-cell-group>
          <div class="tip" slot="title">监察员可查看此员工的月绩效，参与月终的绩效评审</div>
          <EmployeeSelectorCell title="监察员"  bar_title="选择监察员"  :can_select_dept="false" :max="10" :dept_multi="false" v-model="inspector" />
        </van-cell-group>
        <div style="padding: 0.32rem">
          <van-button type="info" block @click="sava_btn">发布</van-button>
        </div>
      </scroller>

      <van-popup v-model="showResult" position="right" style="width: 100vw;height: 100vh;">
        <van-nav-bar title="提交结果" :class="isPhone?'isPhone':''"></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 resultListDiv">
            <scroller>
              <van-cell-group>
                <van-cell v-for="(item,index) in list" :key="index" :title="item.target" :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>
        </div>
        <van-row style="position: absolute;left: 0;right: 0;bottom: 0;">
          <van-col span="24">
            <van-button type="primary" block @click="$route_back">知道了</van-button>
          </van-col>
        </van-row>
      </van-popup>

      <van-popup v-model="show_date" position="bottom">
        <van-datetime-picker
          v-model="currentDate"
          type="year-month"
          :min-date="minDate"
          :formatter="formatter"
          @confirm="datetime_confirm"
          @cancel="datetime_cancel"
        />
      </van-popup>
    </div>
  </div>
</template>
<script>
import request from '@/utils/request'
import moment from 'moment'
import Vue from 'vue'
import EmployeeSelectorCell from '@/components/common/EmployeeSelectorCell'
import EmployeeSelector from '@/components/common/EmployeeSelector'

import {DatetimePicker} from 'vant'
Vue.use(DatetimePicker)
export default {
  name: 'efficiency_task',
  // 数据
  data () {
    return {
      title: '发布绩效',
      include_self: false,
      currentDate: new Date(),
      show_date: false,
      datetime: moment().month(moment().month() + 1).startOf('month').format('YYYY-MM'),
      performance_ex: false,
      executor_scope: [],
      employee_list: [],
      implement: [],
      reviewed_score: [],
      reviewed: [],
      score: '',
      inspector: [],
      notice_ids: '',
      minDate: new Date(),
      list: null,
      showResult: false,
      resultList: [],
      err_count: '',
      success_count: '',
      total: '',
      isPhone: false
    }
  },
  mounted () {
    if (this.$route.query.target_id) {
      let employee = JSON.parse(localStorage.getItem('SET_EMPLOYEE_MAP'))[this.$route.query.target_id] || JSON.parse(plus.storage.getItem('SET_EMPLOYEE_MAP'))[this.$route.query.target_id] || this.$store.getters.employee_map[this.$route.query.target_id]
      if (employee) {
        if (employee.img_url == '') {
          employee.img_url = 'static/images/defalut_custmer_headicon.png'
        }
        this.employee_list = [employee]
        this.implement = [...this.$route.query.target_id]
      }
    }
    if (this.$store.getters.user_info.employee_detail.manage_scope.length > 0) {
      this.executor_scope = this.$store.getters.user_info.employee_detail.manage_scope
    }
    if (this.$route.query.package_date) {
      let datetime = this.$route.query.package_date
      this.datetime = datetime
    }
    window.plus ? this.isPhone = true : this.isPhone = false
  },
  // 组件
  components: {
    EmployeeSelectorCell, EmployeeSelector
  },
  watch: {
    datetime (val) {
      this.getNotSelectorEmployee()
    },
    employee_list (val, old) {
      if (val.length == 0) {
        this.implement = []
      } else {
        let superior_arr = []
        this.implement = []
        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.implement.push({id: element.id, name: element.name})
          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])
            }
          })
        }
      }
    },
    reviewed_score (val) {
      if (val.length > 0) {
        this.reviewed = [val[0]]
      }
    },
    inspector (val) {
      if (val.length == 0) {
        this.inspector = ''
      } else {
        this.notice_ids = ''
        val.forEach(element => {
          this.notice_ids += element.id + ','
        })
      }
    }
  },
  // 方法
  methods: {
    getNotSelectorEmployee () {
      let self = this
      request('get', '/api/integral/performance/employee', {month: self.datetime}, 'v2').then(res => {
        if (res.data.code == 1) {
          self.list = res.data.data.list
          let executor_scope_arr = JSON.parse(JSON.stringify(self.executor_scope))
          let executor_scope_arr1 = [...executor_scope_arr].filter(x => [...self.list].every(y => y.id !== x.id))
          self.executor_scope = executor_scope_arr1
        }
      }).finally(() => this.loading = false)
    },
    tipsMsg () {
      this.$dialog.alert({
        message: '为了保证分值的完整准确性，绩效分仅支持输入100的倍数'
      }).then(() => { })
    },
    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)))
    },
    // 加载
    showLoading () {
      this.$toast.loading({
        loadingType: 'spinner',
        message: '正在处理'
      })
    },
    formatter (type, val) {
      if (type === 'year') {
        return `${val}年`
      } else if (type === 'month') {
        return `${val}月`
      }
      return val
    },
    datetime_confirm (data) {
      this.show_date = false
      this.datetime = moment(data).format('YYYY-MM')
    },
    datetime_cancel () {
      this.show_date = false
    },
    post_data () {
      let self = this
      if (this.score % 100 > 0) {
        this.$toast('月平衡分请输入100的倍数')
        return false
      }
      if (this.score < 1) {
        this.$toast('分值不能为0，不能为负')
        return false
      }

      let data = {packages: []}
      self.implement.forEach(element => {
        data.packages.push({employee_id: element.id, employee_name: element.name, month: self.datetime, base_point: self.score, reviewer_id: self.reviewed[0].id, notice_ids: self.notice_ids})
      })
      self.showLoading()
      request('post', '/api/integral/performance', data, 'v2').then((res) => {
        if (res.data.code == 1) {
          self.showResult = true
          self.$toast.clear()
          self.$toast.success(res.data.msg)
          self.$keep_alive_update('efficiency_detail_update', {})
          var callback_data = res.data.data
          self.list = callback_data.list
          self.err_count = callback_data.fail_count
          self.success_count = callback_data.success_count
          self.total = callback_data.total
        } else {
          self.$toast.clear()
          self.$toast(res.data.msg)
        }
      }).catch((e) => {
        self.$toast.clear()
      })
    },
    sava_btn () {
      let self = this
      self.$validator.validate().then(result => {
        if (self.datetime == '') {
          self.$notify({ type: 'danger', message: '请选择月份绩效'})
        } else if (!self.implement) {
          self.$notify({ type: 'danger', message: '请选择执行人'})
        } else if (!self.score) {
          self.$notify({ type: 'danger', message: '请输入月平衡分'})
        } else if (Number.isInteger(Number(self.score)) === false) {
          self.$notify({ type: 'danger', message: '月平衡分必须是整数'})
        } else if (self.reviewed.length == 0) {
          self.$notify({ type: 'danger', message: '请选择审批人'})
        } else {
          self.post_data()
        }
      })
    }

    // // 绩效详情
    // efficiency_detail(){
    //   let self = this
    //   self.$router.push({name: 'efficiency_detail', query: {date: self.datetime, employee_id: self.implement}})
    // }
  }

}
</script>
<style rel="stylesheet/less" lang="less" scoped>
.body_com{height: calc(100% - 1rem); position: relative;}
.tip{
  font-size: .24rem;
  color: #909399;
  line-height: .34rem;
  background-color: rgb(245, 245, 245);
  span{
    color: #26a2ff;
    text-decoration: underline;
  }
}
.red{
  color: #F56C6C;
}
.efficiency_task_box /deep/ .van-datetime-picker .van-picker__cancel{
  width: 50%;
}
.efficiency_task_box /deep/ .van-datetime-picker .van-picker__cancel:nth-child(1){
  color:#323232;
  border-right:none;
}
.efficiency_task_box /deep/ .selected_btn .van-button--primary{
  background:#238dfa;
  border:0.02rem solid #238dfa;
}
.efficiency_task_box /deep/ .bottom_menu .selected_box .name_mini{
  -o-text-overflow: ellipsis;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

.body_com.resultListDiv{
  height: calc(100vh - 6.4rem);
  position: relative;
}
.rentrun {
  width:100vw;
  background: #fff;
}
.successful_alert{
  // padding-top:1rem;
}
.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;
}
.isPhone{
  padding-top: 0.5rem;
}

.row_line_bg{
  background: #f1f1f1;
  font-size: 0.32rem;
  padding: 0.1rem 0.32rem;
}
.color_blue{
  color:#26A2FF;
}
.color_red{
  color: #F56C6C;
}
.color_grey{
  color: #909399;
}
</style>
