<template>
  <div>
    <van-nav-bar title="批量审批" left-text="返回" @click-left="$route_back" left-arrow :right-text="rightText" @click-right="openBatch()"></van-nav-bar>
    <van-search v-model="params.keyword" placeholder="搜索姓名或内容" show-action style="border-bottom: 1px solid #ebedf0;">
      <template #action>
        <van-dropdown-menu style="height: 0.8rem;" class="menu">
          <van-dropdown-item title="筛选" ref="item">
            <div class="sx-item" @click="activeItem(1)">
              <div class="flex-box">
                <div class="flex-1">可直接打分审批（默认）</div>
                <div v-if="activeIndex == 1"><i class="van-icon van-icon-success"></i></div>
              </div>
              <!-- <div style="font-size: 0.28rem;" class="color_ccc">绩效工作不参与批量审批</div> -->
            </div>
            <div class="sx-item" @click="activeItem(2)">
              <div class="flex-box">
                <div class="flex-1">全部</div>
                <div v-if="activeIndex == 2"><i class="van-icon van-icon-success"></i></div>
              </div>
              <!-- <div style="font-size: 0.28rem;" class="color_ccc">绩效工作不参与批量审批</div> -->
            </div>
          </van-dropdown-item>
        </van-dropdown-menu>
      </template>
    </van-search>
    <div class="body_com">
      <!-- 先隐藏掉下来刷新功能 -->
      <!-- <scroller ref="scroller" :on-refresh="onRefresh" :on-infinite="onInfinite"> -->
       <scroller ref="scroller" :on-infinite="onInfinite">
        <div class="flex-box list-item" v-for="(item,index) in data" :key="index">
          <div><van-checkbox v-model="item.activeChecked" @change="activeChange(index)"></van-checkbox></div>
          <div class="flex-1" style="overflow: hidden;">
            <!-- <span class="title" v-show="item.source_type == 1">{{item.employee_name}}的积分任务</span>
            <span class="title" v-show="item.source_type == 2">{{item.employee_name}}的积分申请</span>
            <span class="title" v-show="item.source_type == 3">{{item.employee_name}}的积分奖扣</span>
            <span class="title" v-show="item.source_type == 4">{{item.employee_name}}的绩效工作</span> -->
            <span class="title">
              <Wxopendata type="userName" :openid="item.employee_name"></Wxopendata>
              {{item.source_type == 1?'的积分任务':item.source_type == 2?'的积分申请':item.source_type == 3?'的积分奖扣':item.source_type == 4?'的绩效工作':''}}
            </span>
            <div class="remark">{{item.remark.customize||item.remark.rule}}</div>
            <!-- 有规则有分类 -->
            <template v-if="item.diy">
              <van-cell title="所属分类" is-link :value="item.rule_name"></van-cell>
              <van-cell>
                  <template #title>
                      <div class="remark2">{{item.item_remark}}</div>
                      <div class="flex-box">
                        <div style="width: 1.8rem;">规则积分</div>
                        <div class="flex-box">
                          <span class="record color_green" v-if="item.item_min_point < 0">
                            {{ item.item_range_type == 1 ? item.item_min_point : item.item_min_point + '～' + item.item_max_point }}
                          </span>
                          <span class="record color_red" v-if="item.item_min_point >= 0">
                            + {{ item.item_range_type == 1 ? item.item_min_point : item.item_min_point + '～' + item.item_max_point }}
                          </span>
                          <span style="padding-left: 0.2rem;">{{ types_list[item.pt_id] }}</span>
                        </div>
                      </div>
                  </template>
              </van-cell>
              <div v-if="item.error.rule" style="height: 0.8rem;padding-left: 1.6rem;line-height: 0.8rem;font-size: 0.32rem;" class="color_red">{{item.error.rule}}</div>
              <div v-if="item.error.item" style="height: 0.8rem;padding-left: 1.6rem;line-height: 0.8rem;font-size: 0.32rem;" class="color_red">{{item.error.item}}</div>
              <div  style="border-bottom: 0.02rem solid #ebedf0;">
                <NumberInput
                 v-model="item.point"
                 :min="item.item_min_point"
                 :max="item.item_max_point"
                 title="填写积分"
                 name="积分"
                 required
                 v-if="item.pid==0"
                 v-validate="'required'">
                 </NumberInput>
                 <div class="flex-box flex-v-ce jf" v-else>
                   <div>填写积分</div>
                   <div style="color: #ff1e1c;">
                      <span v-if="item.point>0">+ {{item.point}}</span>
                      <span v-else>- {{item.point}}</span>
                   </div>
                 </div>
               </div>

               <van-cell center title="发放奖票">
                 <template #right-icon>
                   <div>
                    <van-switch v-model="item.ticket_count" inactive-color="#9a9a9a" size="24" />
                   </div>
                 </template>
               </van-cell>

              <EmployeeSelectorCell
                 bar_title="选择递交审批人"
                 title="递交审批"
                 name="递交审批"
                 v-model="item.reviewer_list"
                 :multi="false"
                 :max="1"
                 :is_filtration_creator="true"
                 :use_employee_list="true"
                 :employee_list="superior_list"
               ></EmployeeSelectorCell>
               <div v-if="item.error.reviewer&&item.reviewer_list.length==0" style="height: 0.8rem;padding-left: 1.6rem;line-height: 0.8rem;font-size: 0.32rem;" class="color_red">权限分不足，请选择审批人</div>
            </template>

            <!-- 无规则 -->
            <template v-else>
              <!-- 当只选择了分类 -->
              <template v-if="item.isRule">
                <van-cell title="所属分类" is-link :value="item.rule_name"></van-cell>
                <div v-if="item.error.rule" style="height: 0.8rem;padding-left: 1.6rem;line-height: 0.8rem;font-size: 0.32rem;" class="color_red">{{item.error.rule}}</div>
                <div v-if="item.error.item" style="height: 0.8rem;padding-left: 1.6rem;line-height: 0.8rem;font-size: 0.32rem;" class="color_red">{{item.error.item}}</div>
                <div style="border-bottom: 0.02rem solid #ebedf0;">
                 <NumberInput
                  v-model="item.point"
                  :min="item.item_min_point"
                  :max="item.item_max_point"
                  title="填写积分"
                  name="积分"
                  required
                  v-if="item.pid==0"
                  v-validate="'required'">
                  </NumberInput>
                  <div class="flex-box flex-v-ce jf" v-else>
                    <div>填写积分</div>
                    <div style="color: #ff1e1c;">
                       <span v-if="item.point>0">+ {{item.point}}</span>
                       <span v-else>- {{item.point}}</span>
                    </div>
                  </div>
                </div>
                <van-cell center title="发放奖票">
                  <template #right-icon>
                    <div>
                      <van-switch v-model="item.ticket_count" inactive-color="#9a9a9a" size="24" />
                    </div>
                  </template>
                </van-cell>
              </template>

              <!-- 没有规则也没有分类 -->
              <template v-else>
                <van-cell title="打分参考已有的积分规则制度">
                  <template slot="right-icon">
                   <div>
                    <van-switch v-model="item.diy2" inactive-color="#9a9a9a" size="24" />
                   </div>
                  </template>
                </van-cell>
                 <!-- 规则 -->
                <RuleCategorySelectorCell
                 required name="选择规则"
                 v-if="item.diy2"
                 v-validate="'required'"
                 ref="rule_selector"
                 title="选择规则"
                 v-model="item.items"
                 @getRule="setPoints"
                 :multi="false"
                 :activeIndex="index"
                 :max="20"
                 :pt_code="item.pt_code">
                 </RuleCategorySelectorCell>

                <CategorySelectorCell
                   v-else
                   title="选择分类"
                   name="选择分类"
                   v-validate="'required'"
                   v-model="item.rule_cate"
                   :max="1"
                   :multi="false"
                   required
                 ></CategorySelectorCell>
                 <!-- 规则选择后 -->
                 <template v-if="item.items.length>0 &&item.diy2">
                   <div  style="padding: 0.24rem 0.32rem">
                     <div class="remark2">{{item.items[0].remark}}</div>
                     <div class="flex-box">
                       <div style="width: 1.8rem;">规则积分</div>
                       <div class="flex-box">
                         <span class="record color_green" v-if="item.items[0].min_point < 0">
                           {{ item.items[0].range_type == 1 ? item.items[0].min_point : item.items[0].min_point + '～' + item.items[0].max_point }}
                         </span>
                         <span class="record color_red" v-if="item.items[0].min_point >= 0">
                           + {{ item.items[0].range_type == 1 ? item.items[0].min_point : item.items[0].min_point + '～' + item.items[0].max_point }}
                         </span>
                         <span style="padding-left: 0.2rem;">{{ types_list[item.items[0].pt_id] }}</span>
                       </div>
                     </div>
                   </div>
                 </template>
                 <!-- end -->

                 <div class="flex-box" style="border-bottom: 0.02rem solid #ebedf0;" v-if="item.items.length>0&&item.diy2">
                    <NumberInput
                     v-model="item.point"
                     :min="item.items[0].min_point"
                     :max="item.items[0].max_point"
                     title="填写积分"
                     name="积分"
                     required
                     v-validate="'required'">
                     </NumberInput>
                 </div>
                 <div class="flex-box" style="border-bottom: 0.02rem solid #ebedf0;" v-else>
                    <NumberInput
                     v-model="item.point"
                     title="填写积分"
                     name="积分"
                     required
                     v-validate="'required'">
                     </NumberInput>
                 </div>

                 <van-cell center title="发放奖票">
                   <template #right-icon>
                     <div>
                      <van-switch v-model="item.ticket_count" inactive-color="#9a9a9a" size="24" />
                     </div>
                   </template>
                 </van-cell>
              </template>

                <EmployeeSelectorCell
                   bar_title="选择递交审批人"
                   title="递交审批"
                   name="递交审批"
                   v-model="item.reviewer_list"
                   :multi="false"
                   :max="1"
                   :is_filtration_creator="true"
                   :use_employee_list="true"
                   :employee_list="superior_list">
                 </EmployeeSelectorCell>
                 <div v-if="item.error.reviewer&&item.reviewer_list.length==0" style="height: 0.8rem;padding-left: 1.6rem;line-height: 0.8rem;font-size: 0.32rem;" class="color_red">权限分不足，请选择审批人</div>
            </template>

          </div>
        </div>
        <noData :list="data" />
        <div style="height: 2rem;"></div>
      </scroller>
      <div class="flex-box btns" v-show="rightText" :class="{ isIos: isIos }" >
        <van-button plain type="danger" class="flex-1" style="margin-right: 0.24rem" @click="reject()">驳回</van-button>
        <van-button plain type="info" class="flex-1" @click="pass()">通过</van-button>
      </div>
      <van-dialog v-model="showReject" title="确认驳回" class="reject_popup" show-cancel-button :beforeClose="save_btn">
        <van-cell-group>
          <van-field v-model="reject_text" rows="2" autosize  type="textarea" maxlength="50" placeholder="请输入审批意见"  show-word-limit v-validate="'required'" name="审批意见"/>
        </van-cell-group>
      </van-dialog>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import request from '@/utils/request'
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 {_debounce} from '@/utils/auth'
import { DropdownMenu, DropdownItem, Search, Switch, Radio, Checkbox, Dialog, Notify} from 'vant'
Vue.use(DropdownMenu).use(DropdownItem).use(Search).use(Switch).use(Radio).use(Checkbox).use(Dialog).use(Notify)
export default {
  name: 'batchList',
  components: { NumberInput, EmployeeSelectorCell, RuleCategorySelectorCell, CategorySelectorCell },
  data () {
    return {
      activeIndex: '1',
      data: [],
      pt_code: '',
      reviewed_score: [],
      types_list: {},
      isload: true,
      rightText: '',
      activeCheckedNum: 0, // 已选择的审批条数
      superior_list: this.$store.getters.user_info.employee_detail.superior_list,
      item: {
        diy: true, // 选择分类还是规则
        items: [], // 规则
        rule_cate: [], // 分类
        point: 0, // 积分
        ticket_count: '', // 是否发放奖票
        reviewer_list: []// 审批人
      },
      params: {
        page: 1,
        keyword: '',
        type: 'fast',
        page_size: 10
      },
      isIos: false,
      showReject: false, // 驳回弹窗
      reject_text: ''// 驳回意见
    }
  },
  created () {
    if (window.plus) {
      this.isIos = plus.storage.getItem('iPhone')
    }
    this.get_point_types()
    this.get_list()
  },
  watch: {
    'params.keyword': _debounce(function () {
      this.params.page = 1
      this.get_list()
    })
  },
  methods: {
    // 当选择规则设置积分初始值
    setPoints: function (data) {
      this.$nextTick(function () {
        this.data[data[0].activeIndex].point = data[0].min_point
      })
    },
    // 驳回
    reject () {
      Dialog.confirm({
        title: '提示',
        message: `确定驳回已选的${this.activeCheckedNum}条审批吗？`
      }).then(() => {
        this.showReject = true
      }).catch(() => {

      })
    },
    // 通过
    pass () {
      var obj, is = true, items = []
      var activeChecked = this.data.filter(item => { return item.activeChecked == true })
      if (this.params.type == 'fast') { // 可直接提交
        for (var i = 0; i < activeChecked.length; i++) {
          var item = activeChecked[i]
          obj = {
            review_id: item.id,
            point: item.point,
            rule_id: item.rule_id,
            item_id: item.item_id,
            reviewer_id: item.reviewer_list.length > 0 ? item.reviewer_list[0].id : 0,
            ticket_count: item.ticket_count == true ? 1 : 0,
            action: 'complete',
            pt_id: item.pt_id
          }
          if (obj.point == 0) {
            is = false
            this.showNotify(`${item.employee_name}的“填写积分”不能空或0`)
            break
          }
          items.push(obj)
        }
        if (is) {
          this.save(items)
        }
        // this.showText(items, is)// 提交审批
      } else { // 要选择分类提交
        this.setRuleSave(activeChecked)
      }
    },
    // 选择分类提交审批
    setRuleSave (activeChecked) {
      var obj, is = true, items = [], _this = this
      for (var i = 0; i < activeChecked.length; i++) {
        var item = activeChecked[i]
        obj = {
          review_id: item.id,
          point: item.point,
          pt_id: item.pt_id,
          reviewer_id: item.reviewer_list.length > 0 ? item.reviewer_list[0].id : 0,
          ticket_count: item.ticket_count == true ? 1 : 0,
          action: 'complete'
        }
        if (item.diy2) {
          obj.rule_id = item.items.length > 0 ? item.items[0].rule_id : item.rule_id
          obj.item_id = item.items.length > 0 ? item.items[0].id : item.item_id
          if (obj.item_id == 0) {
            is = false
            _this.showNotify(`${item.employee_name}的审批请选择规则`)
            break
          }
        } else {
          obj.rule_id = item.rule_cate.length > 0 ? item.rule_cate[0].id : item.rule_id
          obj.item_id = 0
          if (obj.rule_id == 0) {
            is = false
            _this.showNotify(`${item.employee_name}的审批请选择分类`)
            break
          }
        }
        if (obj.point == 0) {
          is = false
          _this.showNotify(`${item.employee_name}的“填写积分”不能空或0`)
          break
        }
        items.push(obj)
      }
      if (is) {
        this.save(items)
      }
      // this.showText(items, is)// 提交审批
    },
    // 校验权限分是否够
    isPoint (list) {
      const userInfo = this.$store.getters.user_info
      const pointConfig = userInfo.point_config
      var isError = false
      list.forEach((item, index) => {
        // 当rule_limit_check为0.||为老板||选择了审批人，不用校验积分
        if ((item.item_id != 0 && userInfo.site_config.rule_limit_check == 0) || userInfo.is_creator == 1 || item.reviewer_id != 0) { // 当选择为0时，选择了规则的都不用检验积分够不够,或者是老板
        } else {
          var pointItem = pointConfig.point_limit.filter(o => o.pt_id === item.pt_id)
          // 替换this.data.isError,显示错误信息
          this.data.forEach((dataItem, index2) => {
            if (dataItem.id == item.review_id) {
              if (item.point > pointItem[0].point) {
                dataItem.isError = true
                isError = true
              }
            }
          })
        }
      })
      return isError
    },
    showText (items, is) {
      if (this.isPoint(items)) {
        Dialog.alert({
          message: '部分审批打分权限不足，请选择审批人后再提交!',
          confirmButtonText: '我知道了'
        }).then(() => {
          // on close
        })
      } else {
        if (is) {
          this.save(items)
        }
      }
    },
    showNotify (str) {
      Notify({
        message: str,
        color: '#fff',
        background: '#ff1e1c',
        duration: 3000
      })
    },
    // 校验提交审批
    save (data, done) {
      this.showLoading('提交中...')
      request('POST', '/api/integral/review/multi/verify', {items: data}).then(res => {
        if (res.data.code === 1) {
          var error_list = res.data.data.error_list || []
          var isAudit = true
          error_list.forEach(item => {
            if (item.status != 1) {
              isAudit = false
              this.data.forEach((dataItem, index) => {
                if (dataItem.id == item.review_id) {
                  dataItem.error.item = item.item.msg
                  dataItem.error.point = item.point.msg
                  dataItem.error.review = item.review.msg
                  dataItem.error.reviewer = item.reviewer.msg
                  dataItem.error.rule = item.rule.msg
                }
              })
            } else {
              this.data.forEach((dataItem, index) => {
                if (dataItem.id == item.review_id) {
                  dataItem.error.item = ''
                  dataItem.error.point = ''
                  dataItem.error.review = ''
                  dataItem.error.reviewer = ''
                  dataItem.error.rule = ''
                }
              })
            }
          })
          if (isAudit) {
            this.audit(data)
          } else {
            Dialog.alert({
              message: '提交审批有误，请修正后重新提交!',
              confirmButtonText: '我知道了'
            }).then(() => {
              // on close
            })
          }
        }
      }).finally(() => {
        if (done) { done() }
        this.$toast.clear()
      })
    },
    // 提交审批
    audit (data) {
      request('POST', '/api/integral/review/multi/verify', {items: data}, 'v2').then(res => {
        if (res.data.code === 1) {
          this.$toast('提交成功!')
          this.params.page = 1
          this.get_list()
          this.$keep_alive_update('update_task_message', {})
          // this.onRefresh(function () {})
        }
      }).finally(() => {
        this.reject_text = ''
        this.rightText = ''
        this.showReject = false
      })
    },
    // 加载
    showLoading (str = '加载中...') {
      this.$toast.loading({
        mask: true,
        type: 'spinner',
        message: str
      })
    },
    // 驳回保存
    save_btn (action, done) {
      let self = this
      if (action == 'confirm') {
        if (!self.reject_text) {
          self.$notify({type: 'danger', message: '请填写驳回意见'})
          done(false)
        } else {
          var activeChecked = self.data.filter(item => { return item.activeChecked == true })
          var obj, items = []
          activeChecked.forEach((item, index) => {
            obj = {
              review_id: item.id,
              remark: self.reject_text,
              ticket_count: item.ticket_count == true ? 1 : 0,
              action: 'refuse'
            }
            items.push(obj)
          })
          self.save(items, done)// 驳回
        }
      } else {
        this.reject_text = ''
        done()
      }
    },
    activeChange (index) {
      var activeChecked = this.data.filter(item => {
        return item.activeChecked == true
      })
      this.activeCheckedNum = activeChecked.length
      if (activeChecked.length == 0) {
        this.rightText = ''
      } else if (activeChecked.length > 10) {
        this.$toast('最多只能选择10条!')
        this.data[index].activeChecked = false
      } else {
        this.rightText = `已选择（${activeChecked.length}）`
      }
    },
    get_list (callback = function () {}) {
      request('get', '/api/integral/review/multi/list', this.params).then(res => {
        callback()
        if (res.data.code === 1) {
          var list = this.resetData(res.data.data.list || [])
          if (this.params.page === 1) {
            this.data = list
          } else {
            this.data = this.data.concat(list)
          }
          this.isload = !(list.length < 10)
          this.$refs.scroller.finishInfinite(list.length < this.params.page_size)
        } else {
          this.$refs.scroller.finishInfinite(true)
        }
      })
    },
    // 重置列表数据
    resetData (data) {
      data.forEach((item, index) => {
        item.activeChecked = false// 是否选择中
        item.reviewer_list = []// 审批人
        item.rule_cate = [] // 分类
        item.items = []// 规则
        item.diy = false// 是否指定规则
        item.diy2 = false// 是否指定规则
        item.error = {
          point: '',
          review: '',
          item: '',
          reviewer: '',
          rule: ''
        }// 是否积分权限不足
        item.ticket_count = false// 是否发放奖票
        if (item.item_id > 0 && item.rule_id > 0) {
          item.diy = true
          item.diy2 = true // 用于切换分类与规则
        }
        if (item.rule_id > 0 && item.item_id == 0) { // 当只选择了分类
          item.isRule = true
        } else {
          item.isRule = false
        }
      })
      return data
    },
    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
      }
    },
    activeItem (index) {
      this.params.type = index == 1 ? 'fast' : 'all'
      this.activeIndex = index
      this.params.page = 1
      this.get_list()
      // this.onRefresh(function () {})
      this.onConfirm()
    },
    onConfirm () {
      this.$refs.item.toggle()
    },
    onRefresh (done) {
      this.params.page = 1
      this.get_list(done)
    },
    onInfinite (done) {
      if (this.isload) {
        this.params.page++
        this.get_list(done)
      }
    }
  }
}
</script>

<style scoped="scoped">
  .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: '*';
  }
  .isIos {
    padding-bottom: 0.4rem !important;
  }
  .btns{
    position: fixed;
    bottom: 0rem;
    left: 0;
    right: 0;
    padding: 0.15rem 0.24rem;
    background-color: #fff;
    z-index: 99;
    border-top: 1px solid #ebedf0;
  }
  .remark2{
    overflow : hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    font-size: 0.32rem;
    width: 100%;
  }
  .remark{
    overflow : hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    font-size: 0.32rem;
    color: #909399;
    padding-left: 0.32rem;
    padding-right: 0.32rem;
    margin-top: 0.14rem;
  }
  .title{
    font-size: 0.32rem;
    padding-left: 0.32rem;
  }
.list-item {
  font-size: 0.32rem;
  padding: 0.24rem;
  padding-right: 0rem;
  padding-bottom: 0rem;
  background-color: #fff;
  border-top: 1px solid #ebedf0;
}
.van-icon-success {
  background-color: #26a2ff;
  border-radius: 50%;
  color: #fff;
  width: 0.4rem;
  height: 0.4rem;
  text-align: center;
  font-size: 0.28rem;
  line-height: 0.4rem;
}
.menu::after {
  border: 0 solid #fff;
}
.sx-item {
  padding: 0.3rem;
  font-size: 0.3rem;
  border-bottom: 1px solid #ebedf0;
  line-height: 0.4rem;
}
.body_com {
  height: calc(100% - 2.1rem);
  position: relative;
}
</style>
