<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>
          <div class="tip" slot="title" style="text-align: right;">使用之前的绩效工作？
             <quoteMark @confirm="event_select" :base_point="base_point" title="去引用"></quoteMark>
          </div>
          <van-cell required>
            <!-- <Mtextarea name="任务内容" v-validate="'required|min:3'" :images="true" required v-model="data.task_name" placeholder="输入任务内容" :text_max="20"></Mtextarea> -->
            <Mtextarea
              v-model="data.task_name"
              placeholder="输入任务内容"
              name="任务内容"
              v-validate="'required|min:3'"
              :text_max="20"
              :imgs_max="3"
              images
              :imgs.sync="data.file_list"
            ></Mtextarea>
          </van-cell>
        </van-cell-group>
        <van-cell-group>
          <div class="tip" slot="title" v-if="(surplus/base_point*100).toFixed(0) >= 0">
            <div v-if="surplus_mark == 0">权重还剩余{{(surplus/base_point*100).toFixed(0)}}%可以分配</div>
            <div v-if="surplus_mark > 0">权重分配已超出100%，当前额外分配<span style="color:#26A2FF;">{{surplus_mark}}%</span></div>
          </div>
          <van-field label="权重" @input="changeunqualified" v-model="data.weight" name="权重" placeholder="请输入权重百分比" type="Number" right-icon="%" v-validate="'required'" required >
          <template slot="right-icon">
              <smallTip icon="question-o" position="30%">
                <p style="margin: 0; line-height: 0.6rem; text-align: left;">本条任务占月绩效的比重，权重越高越重要</p>
            </smallTip>
          </template>
          </van-field>
          <van-field :disabled="true" label="任务积分" name="任务积分" v-model="data.base_point" type="Number" v-validate="'required|numeric'" placeholder="月平衡分*权重" required />
        </van-cell-group>
        <van-cell-group>
        <DateTimeCell required v-validate="'required'" name="截止时间" title="截止时间" v-model="data.expire_time"></DateTimeCell>
      </van-cell-group>
        <van-cell-group>
          <van-cell>
            <Mtextarea v-model="data.task_remark" placeholder="输入任务备注" :text_max="100"></Mtextarea>
          </van-cell>
        </van-cell-group>
        <van-cell-group>
          <EmployeeSelectorCell required title="审批人" :employee_list="superior_list" use_employee_list  v-model="reviewer_list" v-validate="'required'" name="审批人" :multi="false"></EmployeeSelectorCell>
        </van-cell-group>
        <div style="padding:0.32rem;">
          <van-button size="large" @click="data_verify" type="info">发布</van-button>
        </div>
      </scroller>
    </div>
  </div>
</template>
<script>
  import Vue from 'vue'
  import request from '@/utils/request'
  import Mtextarea from '@/components/common/Mtextarea'
  import EmployeeSelectorCell from '@/components/common/EmployeeSelectorCell'
  import DateTimeCell from "@/components/common/DateTimeCell";
  import smallTip from '@/components/common/smallTip'
  import quoteMark from '@/components/common/quoteMark'
  import moment from 'moment'
  import {Overlay, calendar} from 'vant'
  Vue.use(Overlay).use(calendar);
  export default {
    name: "form_demo",
    components: {
      DateTimeCell,
      quoteMark,
      smallTip,
      Mtextarea, EmployeeSelectorCell
    },
    data(){
      return {
        data: {
          targets: [],
          pt_id: 0,
          task_name: '',
          task_remark: '',
          base_point: null,
          expire_time: '',
          package_id: 0,
          weight: null,
          reviewer_id: 0,
          timeout_deduction_point: 0,
          cate_id: 0,
          file_list: []
        },
        reviewer_list: [],
        superior_list: [],
        targets_list: [],
        base_point: 0,
        surplus: 0
      }
    },
    watch: {
      'data.weight': function (val, old) {
        this.data.base_point = (val/100 * this.base_point).toFixed(0)
      },
      reviewer_list(val,old){
        if (val.length > 0) {
          this.data.reviewer_id = val[0].id
        }
      }
    },
    computed:{
      usedWeight(){
        return (this.base_point - this.surplus) / (this.base_point || 1) * 100
      },
      surplus_mark(){
        if((this.surplus/this.base_point*100).toFixed(0) - this.data.weight < 0){
          return Math.abs((this.surplus/this.base_point*100).toFixed(0) - this.data.weight)
        }
        return 0
      }
    },
    methods: {
      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)))
      },
      changeunqualified(val) {
        if(val == 1 &&  this.data.base_point == 0) {

          this.data.base_point = 1;
        }
        let str = '' + this.data.weight;
        let str2 = ''
        if (str.indexOf('.') != -1) {
          let arr = str.split('');
          arr.splice(arr.length - 1);
          let str2 = arr.join('');
          this.data.weight = +str2;
        }
      },
      // 关联事件回填
      event_select(item) {
        let point = ((item.base_point)/this.base_point*100).toFixed(0);
        this.data.task_name = item.task_name;
        this.data.task_remark = item.task_remark;
        this.data.weight = point;
      },
      data_verify(){
        let self = this
        self.$validator.validateAll().then(result => {
          if(!result){
            self.$notify({ type: 'danger', message: self.$validator.errors.items[0].msg });
          }else{
            if(self.data.weight == '0'){
              self.$notify({ type: 'danger', message: '权重不能为0' });
            }else{
              self.send()
            }
          }
        })
      },
      send(){
        let self = this
        self.send_loading = true
        self.$toast.loading({
          message: '正在处理'
        })
        let data = JSON.parse(JSON.stringify(self.data))
        if(data.task_remark == ''){
          delete data.task_remark
        }
        request('post','/api/integral/work/publish',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('efficiency_detail_update', {})
            setTimeout(() => {
              self.$route_back()
            }, 500)
          }else{
            self.$toast(res.data.msg)
          }
        }).catch(e => {
          self.send_loading = false
          self.$toast.clear()
        })
      }
    },
    created(){
      let point_types = this.$store.getters.point_types
      for(let i in point_types){
        if(point_types[i].code == 'JX'){
          this.data.pt_id = point_types[i].id
        }
      }
      if(this.$route.query.employee_id){
        this.data.targets = [this.$route.query.employee_id]
      }
      if(this.$route.query.package_id){
        this.data.package_id = this.$route.query.package_id
      }
      if(this.$route.query.base_point){
        this.base_point = this.$route.query.base_point * 1
      }
      if(this.$route.query.surplus){
        this.surplus = this.$route.query.surplus * 1
      }
    },
    // 组件挂载完成
    mounted() {
      let employee_id =this.$route.query.employee_id
      this.superior_list = this.$store.getters.employee_map[employee_id].superior_list
      if (this.superior_list.length > 0) {
        this.reviewer_list = [this.superior_list[0]]
        this.data.reviewer_id = this.superior_list[0].id
      }
    },
  }
</script>
<style scoped>
  .body_com{height: calc(100% - 0.92rem); position: relative;}
</style>
