<template>
  <div class="all" :class="{ bg_fff: skeletonLoad }">
    <van-nav-bar title="组织考核" left-text="返回" @click-left="goHomePage" :right-text="right_text" @click-right="multi_option" left-arrow></van-nav-bar>
    <van-notice-bar
      left-icon="volume-o"
      text="默认显示每个人的最新考核数据，可选择人员添加考核数据，也可以移除某个人员的考核数据，或点击人员姓名替换某条考核数据"
    />

    <div class="search-box flex-box-ce">
      <div class="flex-1 flex-box-ce flex-center-center fontColorC" @click="openPanel">
        周期选择 <van-icon name="arrow-down" size="12" style="margin-left: 0.2rem;" />
      </div>
      <div class="flex-1 flex-box-ce flex-center-center fontColorC" @click="openPanel2">
        部门选择
        <van-icon name="arrow-down" size="12" style="margin-left: 0.2rem;" />
      </div>
    </div>
    <div class="overall">
      <VanSkeleton :skeLoad="skeletonLoad">
        <scroller>
          <div style="padding-bottom: 1rem;">

            <div class="list-box" v-for="(item, index) in employeeList" :key="item.employeeId">
              <van-checkbox v-if="multi" v-model="item.selected" shape="square" style="margin-bottom: 0.1rem;" />
              <div class="flex-box-ce" style="margin-bottom: 0.2rem;"  @click="chooseExamineInfo(index, item.employeeId)">
                <div class="flex-box-ce">
                  <div>
                    <userImage class="about-me__avatar" :id="item.userInfo.id" :img_url="item.userInfo.img_url"  :user_name="item.userInfo.name"  fontSize="0.24"  width="0.8rem"  height="0.8rem"></userImage>
                  </div>
                  <div class="user-info">
                    <div style="margin-bottom: 0.05rem; color: #000;">{{ item.employeeName }}</div>
                    <template v-if="item.deptList && item.deptList.length > 0">
                      <span v-for="(dept, index) in item.deptList" :key="index">{{ dept }}&nbsp;</span>
                    </template>
                  </div>
                </div>
                <div v-if="item.status == 1" class="examine-item-status" style="background-color: #FF9600;">
                  已结束
                </div>
                <div v-if="item.status == 0" class="examine-item-status" >
                  进行中
                </div>

              </div>

              <div class="examine-info">
                <div class="info-item flex-box-ce">
                  考核周期：&nbsp;&nbsp;&nbsp; <div class="cycle-type">{{ item.cycleType | formatCycleType }}</div>
                </div>
                <div class="info-item">
                  <van-icon name="calendar" />考核时间：&nbsp;&nbsp;&nbsp;{{ item.startTime | formatDate }} 至 {{ item.endTime | formatDate }}
                </div>
                <div class="info-item">
                  考核等级：&nbsp;&nbsp;&nbsp; <span style="color: #ff9600;">{{ item.levelName || '-' }}</span>
                </div>
                <div class="info-item">
                  考核评分：&nbsp;&nbsp;&nbsp; <span style="color: #ff9600;">{{ item.score == undefined  || item.score == null || item.score == '' ? '-' : item.score }}</span>
                </div>
                <div class="info-item">
                  较上次：&nbsp;&nbsp;&nbsp;
                  <span v-if="item.levelChange && item.levelChange > 0" style="color: #67c23a !important;">
                    {{ item.levelChange }}
                  </span>
                  <span v-else-if="item.levelChange && item.levelChange < 0"  style="color: #f56c6c !important;">
                    {{ item.levelChange }}
                  </span>
                  <span v-else class="gray" style="color: #999;">
                    --
                  </span>
                </div>
              </div>

            </div>


          </div>
        </scroller>
      </VanSkeleton>
    </div>

    <footer class="footer">
      <div v-if="multi" class="flex-box-ce" style="justify-content: space-around;">
        <div class="flex-box-ce" style="margin: 0 0.2rem; font-size: 0.28rem;" >
          <van-checkbox v-model="selectAll" shape="square" style="margin-right: 0.2rem;" />
          全选
        </div>
        <div class="btn flex-1 danger" @click="handleDelete()">删除人员</div>
      </div>

      <div v-else class="flex-box-ce" style="justify-content: space-around;">
        <div class="btn" @click="openUserSelector()">添加人员</div>
        <!-- <div class="btn">删除人员</div> -->
        <div class="btn plain" @click="resetData()">重置数据</div>
      </div>
    </footer>


    <!-- 周期选择弹框 -->
    <van-action-sheet v-model="pullonThePanel" :closeable="false">
      <div class="content">
        <van-picker ref="van_picker" show-toolbar :columns="columns" @cancel="pullonThePanel = false" value-key="name" @confirm="onConfirm" confirm-button-text="完成" />
      </div>
    </van-action-sheet>

    <!-- 部门选择 -->
    <!-- <EmployeeSelector
      :max="1"
      :close_clear_data="false"
      :can_select_employee="false"
      :dept_multi="false"
      @confirm="confirmDept"
      :visible.sync="show_dept_selector"
      :selected.sync="selected_data"
      :isShowDepts="true"
    ></EmployeeSelector> -->


    <!-- 人员选择 -->
    <EmployeeSelector title="人员"
      :visible.sync="show_user_selector"
      @confirm="confirmCreator"
      :selected.sync="selected_user_all"
      :can_select_dept="false"
      :dept_multi="false"
      :append_body="true"
      :isShowDepts="false"
      :max='120'
    />

  </div>
</template>

<script>
import Vue from 'vue';
import { NoticeBar } from 'vant';
import VanSkeleton from '@/performance/components/public/VanSkeleton';
import EmployeeSelector from '@/components/EmployeeSelector';
import moment from 'moment';

Vue.use(NoticeBar)
  export default {
    components: {
      VanSkeleton,
      EmployeeSelector
    },

    data() {
      return {
        skeletonLoad: true,
        employeeList: [],
        // 周期类型 0-自定义 1-年度 2-半年度 3-季度 4-月度
        cycleType: '-1',
        right_text: "批量",
        columns: [
          {
            value: "-1",
            name: "全部",
            text: "全部"
          },
          {
            value: "0",
            name: "自定义",
            text: "自定义"
          },
          {
            value: "1",
            name: "年度",
            text: "年度"
          },
          {
            value: "2",
            name: "半年度",
            text: "半年度"
          },
          {
            value: "3",
            name: "季度",
            text: "季度"
          },
          {
            value: "4",
            name: "月度",
            text: "月度"
          }
        ],

        currentValue: '-1', // 选项回显

        pullonThePanel: false,
        dept_id: 0,
        show_dept_selector: false,
        show_user_selector: false,

        selected_data: { dept: [], employee: [] },

        selected_user_all: { dept: [], employee: [] }, //选择人员
        multi: false,
        reviewId: '', // 选择的考核信息ID
        params: {
          deptIds: '',
          employeeIds: '',
          cateId: '',
          pages: 1,
          pageSize: 10
        },
      }
    },

    computed: {
      selectEmployeeIds() {
        let selectEmployeeIds = this.employeeList.map(item => item.employeeId)
        selectEmployeeIds = Array.from(
            new Set(selectEmployeeIds.map(item => JSON.stringify(item)))
        ).map(item => JSON.parse(item));
        return selectEmployeeIds
      },

      selectEmployees() {

        let selectEmployees = this.employeeList.map(item => item.userInfo)
        selectEmployees = Array.from(
            new Set(selectEmployees.map(item => JSON.stringify(item)))
        ).map(item => JSON.parse(item));
        return selectEmployees
      },

      // 全选 / 全不选
      selectAll: {
        get() {
          // 所有都选中 → 全选按钮 true
          return this.employeeList.every(item => item.selected);
        },
        set(val) {
          // 点击全选按钮时，一键同步到所有
          this.employeeList.forEach(item => (item.selected = val));
        }
      }
    },

    filters: {
      filterNodeStatus(v) {
        if (v === 'start') return '开始'
        if (v === 'target_confirm') return '确认目标'
        if (v === 'result_input') return '录入结果值'
        if (v === 'score_self') return '自评'
        if (v === 'score_each_other') return '互评'
        if (v === 'score') return '评分'
        if (v === 'review') return '审批'
        if (v === 'cc') return '抄送'
        if (v === 'end') return '结束'
      },

      formatDate(val) {
        if (val) return moment(val).format('YYYY-MM-DD')
        else return "--"
      },

      formatCycleType(val) {
        if (val == 0) return '自定义'
        if (val == 1) return '年度'
        if (val == 2) return '半年'
        if (val == 3) return '季度'
        if (val == 4) return '月度'
        else return '--'
      },
    },

     watch: {
      // 路由参数变化（浏览器返回/前进、query 变化）也会再次执行
      '$route'(to, from) {
        this.getExamineInfo()
      }
    },

    created() {
      // this.show_dept_selector = true
      this.getList()

    },
    methods: {

      goHomePage() {
        this.$router.push("/home")
      },

      // 批量操作
      multi_option () {
        if (this.multi) {
          this.multi = false
          this.right_text = '批量'
        } else {
          this.multi = true
          this.right_text = '取消'
        }
      },

      // 获取数据
      getList() {
        this.skeletonLoad = true;
        let url = `/performance/statistics/review/last/${this.$userInfo().site_id}`
        let requestdata
        if (this.cycleType == '-1') requestdata = { ...this.params }
        else {
            requestdata = { ...this.params, cycleType: this.cycleType }
        }
        delete requestdata['employeeIds'] // 删除部门字段
        this.$axiosUser('get', url, requestdata).then(res => {
          this.skeletonLoad = false;
          let { data: { data: { list, total }, code } } = res
          if (code == 1) {
              if(list && list.length > 0) {
                list.forEach(item => {
                  item.selected = false
                  item.userInfo = this.$getEmployeeMapItem(item.employeeId);
                })
              }
              this.employeeList = list;
              // this.total = total
            }
        });
      },

      /* 添加的人员请求考核数据 */
      getListByPerson() {
        let url = `/performance/statistics/review/last/${this.$userInfo().site_id}`
        // this.selected_dept_ids = []
        // this.params.deptIds = ''
        // this.params.employeeIds = this.params.employeeIds && this.params.employeeIds.length > 0 ? this.params.employeeIds.toString() : ''

        this.$axiosUser('get', url, this.params).then(res => {
            // this.loading = false;
            let { data: { data: { list, total }, code } } = res
            if (code == 1) {
                let contactList = [...this.employeeList, ...list];
                // 去重
                this.employeeList = Array.from(
                    new Set(contactList.map(item => JSON.stringify(item)))
                ).map(item => JSON.parse(item));
                // this.total = this.tableData.length
                this.employeeList.forEach(item => {
                  item.selected = false
                  item.userInfo = this.$getEmployeeMapItem(item.employeeId);
                })
                this.cycleType = '-1';
            }
        });
      },

      // 获取考核信息
      getExamineInfo() {
        let reviewId = this.$route.query.reviewId
        if(!reviewId) return
        console.log("reviewId")
        console.log(reviewId)
        let url = `/performance/statistics/review/info/${this.$userInfo().site_id}/${reviewId}`
        this.$axiosUser('get', url).then(res => {
            let { data, code } = res.data
            if (code == 1) {
                if (data) {
                    delete data['deptList'] // 删除部门字段
                    let replaceData = {
                        ...this.employeeList[this.currentIndex],
                        ...data
                    }
                    this.employeeList.splice(this.currentIndex, 1, replaceData);
                }
            }
        });
      },


      // 打开周期选择弹框
      openPanel(){
        this.pullonThePanel = true;
        // 等 DOM 渲染完成后设置索引
        this.$nextTick(() => {
          const index = this.columns.findIndex(item => item.value == this.currentValue);
          // 单列只传一个索引
          this.$refs.van_picker.setIndexes([index]);
        });

      },

      openPanel2() {
        this.show_dept_selector = true
        console.log(this.show_dept_selector)
      },

      //  确认周期选择
      onConfirm (data, value) {
        console.log(data)
        console.log(value)
        this.cycleType = data.value
        this.currentValue = data.value
        this.getList()
        this.pullonThePanel = false
      },

      confirmDept(val){
        this.selected_data = val;
        if(val.dept.length > 0){
          this.dept_id = val.dept[0].dept_id;
        }else{
          this.dept_id = 0;
        }
        // this.pullDown();
      },

      openUserSelector() {
        this.selected_user_all.employee = this.selectEmployees
        this.show_user_selector = true
      },

      resetData() {
        let url = `/performance/statistics/review/last/${this.$userInfo().site_id}`
        let requestdata
        this.cycleType = '-1';
        this.params = {
            deptIds: '',
            employeeIds: '',
            cateId: '',
            pages: 1,
            pageSize: 10
        }
        // this.selected_dept_ids = []
        requestdata = { ...this.params }
        if ('deptIds' in requestdata) delete requestdata['deptIds'] // 删除部门字段
        this.$axiosUser('get', url, requestdata).then(res => {
            // this.loading = false;
            let { data: { data: { list, total }, code } } = res
            if (code == 1) {
              if(list && list.length > 0) {
                list.forEach(item => {
                  item.selected = false
                  item.userInfo = this.$getEmployeeMapItem(item.employeeId);
                })
              }
              this.employeeList = list;
            }
        });
      },

      confirmCreator(arr){
        let target_ids = arr.employee.map(item=>{
          return item.id
        }).filter(item => !this.selectEmployeeIds.includes(item)).toString();
        // target_ids = target_ids.filter(target => )
        console.log(target_ids)
        this.params.employeeIds = target_ids;
        this.getListByPerson();
        // let data = {
        //   employeeId: this.$userInfo().id,
        //   targetIds: target_ids
        // }

      },

      handleDelete() {
        this.employeeList = this.employeeList.filter(item => !item.selected)
      },

      chooseExamineInfo(index, employeeId) {
        this.currentIndex = index
        this.$router.push({ path: "/more", query: { employeeId, from: "orgExamine" } })
      }
    }
  }
</script>

<style scoped lang="less">
  .all {
    width: 100%;
    height: 100%;
    position: relative !important;
    background-color: #f5f7fa;
    box-sizing: border-box;
    .search-box {
      width: 100%;
      height: 0.8rem;
      background: #fff;
      font-size: 0.28rem;
    }
    .overall {
      height: calc(100% - 2.52rem) !important;
      position: relative;
      overflow-y: scroll;

      .list-box {
        width: 96%;
        padding: 0.24rem;
        font-size: 0.32rem;
        background-color: #fff;
        border-radius: 5px;
        box-sizing: border-box;
        margin: 0.24rem auto;
        position: relative;
        .examine-item-status {
          position: absolute;
          top: 0.2rem;
          right: 0.1rem;
          padding: 0.01rem 0.1rem;
          color: #fff;
          border-radius: 2px;
          font-size: 0.26rem;
          background-color: #67c23a;
          margin-right: 0.14rem;
        }
        .add-task-title {
          font-weight: 600;
          font-size: 0.32rem;
        }

        .user-info {
          font-size: 0.28rem;
          color: #89919F !important;
          margin: 0 0 0 0.2rem;
        }

        .cycle-type {
          padding: 0.08rem;
          border-radius: 0.1rem;
          color: #26a2ff;
          box-sizing: border-box;
          background-color: #ecf5ff;
        }

        .examine-info {
          font-size: 0.28rem;
          position: relative;

          .tips {
            position: absolute;
            top: 0.1rem;
            right: -0.2rem;
            .tip-item {
              padding: 0.1rem;
              border-top-left-radius: 0.1rem;
              border-bottom-left-radius: 0.1rem;
              color: #26a2ff;
              z-index: 999;
              box-sizing: border-box;
              background-color: #ecf5ff;
              margin-bottom: 0.1rem;
            }
          }
          .info-item {
            margin-bottom: 0.2rem;
            color: #89919F !important;
            .info-item-title {
              width: 1.4rem;
              color: #000;
            }
            .review-node {
              padding: 0.01rem 0.1rem;
              color: #fff;
              border-radius: 2px;
              font-size: 0.26rem;
              background-color: #67c23a;
              margin-left: 0.14rem;
            }
          }

          .line {
            width: 100%;
            margin: 0.5rem auto;
            height: 1px;
            background-color: #f1f1f1;
          }
        }


      }
    }
  }


  .footer {
    width: 100%;
    padding: 0.2rem;
    border-top: 0.02rem solid #f1f1f1;
    background: #fff;
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 999;
    box-shadow: 0px -3px 0.15rem #f7f8fa;
    box-sizing: border-box;
    .btn {
      width: 48%;
      padding: 0.2rem;
      // border: 0.02rem solid #26A2FF;
      color: #fff;
      text-align: center;
      background: #26A2FF;
      font-size: 0.28rem;
      box-sizing: border-box;
    }
    .danger {
      background-color: transparent;
      color: rgb(245, 108, 108);
      border: 1px solid rgb(245, 108, 108);
    }
    .plain {
      background-color: transparent;
      color: #26A2FF;
      border: 1px solid #26A2FF;
    }
  }
</style>
