<template>
    <div class="home">
      <!-- 任务进度条 -->
      <el-card class="task-process">
        <div class="task-item active">
          <div class="task-icon">
            <span class="circle">1</span>
          </div>
          <div class="task-text">任职申请</div>
        </div>
        <div class="line-horizontal"></div>
        <div class="task-item">
          <div class="task-icon">
            <span class="circle">2</span>
          </div>
          <div class="task-text">学习考试</div>
        </div>
        <div class="line-horizontal"></div>
        <div class="task-item">
          <div class="task-icon">
            <span class="circle">3</span>
          </div>
          <div class="task-text">专业回馈</div>
        </div>
        <div class="line-horizontal"></div>
        <div class="task-item">
          <div class="task-icon">
            <span class="circle">4</span>
          </div>
          <div class="task-text">个人行为举证</div>
        </div>
      </el-card>
<!--      <H2 class="page-title">任职申请</H2>-->
      <!-- 任职申请基本信息 -->
      <el-card class="base-info">
        <div class="s-title">
          <i class="el-icon-s-order"></i>
          基本信息
        </div>
        <div >
          <div class="application-item" v-for="(item, index) in baseInfoList" :key="index" :style="{float:'left', width:item.width, marginLeft:'90px',marginBottom:'10px'}">
            <div style="display: inline-block; width: 30%; vertical-align: top;" >
              <label style="color: #000000; margin-right: 20px;border-left: 3px solid orangered;padding-left: 3px;">{{item.label}}</label>
            </div>
            <div style="display: inline-block; width: 70%;">
              <label v-if="item.label !== '专业领域经历' && item.label !== '已获得任职资格序列及等级'" style="color: lightslategray">{{item.value}}</label>
            </div>
            <!-- 现任职资格薛烈等级表格 -->
            <el-table v-if="item.label === '已获得任职资格序列及等级'" :data="sequenceLevel"
                      :cell-style="{ color: 'lightslategray' }" :header-cell-style="{color: '#000000',fontWeight: 'normal' }" border
                      style="margin-top:10px;width: 70%;height: 5%;">
              <el-table-column prop="sequence" label="任职资格序列" min-width="50%"></el-table-column>
              <el-table-column prop="level" label="任职资格等级" min-width="50%"></el-table-column>
              <el-table-column prop="startTime" label="获得时间" min-width="50%">
                <template #default="scope">
                  <span v-if="scope.row.status === '7'"></span>
                  <span v-else>{{scope.row.startTime}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="endTime" label="有效期" min-width="50%">
                <template #default="scope">
                  <span v-if="scope.row.status === '7'"></span>
                  <span v-else>{{scope.row.endTime}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" min-width="50%">
                <template #default="scope">
                  <el-tag v-if="scope.row.status === '7'" type="success">初始化</el-tag>
                  <el-tag v-else-if="scope.row.status !== '7' && scope.row.validTime <=2 " type="success">有效</el-tag>
                  <el-tag v-else type="danger">失效</el-tag>
                </template>
              </el-table-column>
            </el-table>
            <!-- 专业领域经历表格 -->
            <el-table v-if="item.label === '专业领域经历'" :data="experience"
                      :cell-style="{ color: 'lightslategray' }" :header-cell-style="{color: '#000000',fontWeight: 'normal' }" border
                      style="margin-top:10px;width: 70%;height: 5%;">
              <el-table-column prop="time" label="起止时间" min-width="35%"></el-table-column>
              <el-table-column prop="orgName" label="单位" min-width="35%"></el-table-column>
              <el-table-column prop="positionName" label="岗位" min-width="30%"></el-table-column>
            </el-table>
          </div>
        </div>
      </el-card>
      <!-- 任职申请申报任职资格序列+等级 -->
      <el-card class="job-application">
        <div class="s-title">
          <i class="el-icon-s-order"></i>
          任职申请
        </div>
        <div class="application-item" style="float:left;width:45%; margin-left:90px">
          <label style="color: #000000;margin-right: 20px" >申报任职资格序列</label>
          <el-select v-model.trim="sequence" clearable placeholder="请选择" style="width: 40%" @change="changeSequence" @clear="clearSequence">
            <el-option v-for="item in qualificationInfo.sequence" :label="item.name"
                       :value="item.name" :key="item.code">
            </el-option>
          </el-select>
          <el-tooltip class="item" effect="dark" content="点击查看任职资格标准" placement="top-start">
            <i class="el-icon-info" style="margin-left: 10px;color: #999; font-size: 25px;" @click="showStandardFile"></i>
          </el-tooltip>
        </div>
        <div class="application-item" style="float:left;width:45%">
          <label style="color: #000000; margin-right: 20px">申报任职资格等级</label>
          <el-select v-model.trim="level" clearable placeholder="请选择"  style="width: 40%"  @change="changeLevel" @clear="clearLevel">
            <el-option v-for="item in qualificationInfo.level" :label="item.name"
                       :value="item.code" :key="item.code">
            </el-option>
          </el-select>
        </div>
<!--        <div class="application-item" style="width:90%; margin-left:90px">-->
<!--          <label style="color: #000000; width:40%;margin-right: 20px;">任职资格标准</label>-->
<!--          <div style="background-color:red; display: inline-block; width: 70%;height: 500px;">-->
<!--            <Preview style="height: 50px" :parentUrl="'/qualifications-service/internal-informations/downloadQualificationStandard'"-->
<!--                     :params='{"qualificationCriteria":"D:\\upload\\standard\\规划与运营管理L12\\1742532193505_任职资格标准表-党群室人事室-安全与后勤管理.pdf"}'></Preview>-->
<!--          </div>-->
<!--        </div>-->
        <div class="application-item" style="width:90%; margin-left:90px">
          <label style="color: #000000;margin-right: 70px;float: left">课程清单</label>
<!--          <el-input-->
<!--              type="textarea"-->
<!--              :rows="4"-->
<!--              placeholder="请输入内容"-->
<!--              v-model="courseList"-->
<!--              style="width:74%">-->
<!--          </el-input>-->
          <div style="width: 71%; float: left; border: 1px solid #EBEEF5; margin-bottom: 20px" >
            <div style="height:300px;overflow:auto">
            <el-tree
                class="filter-tree"
                :data="courseList"
                :props="defaultProps"
                default-expand-all
                ref="tree">
            </el-tree>
            </div>
          </div>
        </div>
      </el-card>
      <!-- 任职申请规则校验 -->
      <el-card class="application-rule">
        <div class="s-title">
          <i class="el-icon-s-order"></i>
          申请规则校验情况
        </div>
        <div style="margin-left:90px">
          <div class="application-item" v-for="(item, index) in applicationRule" :key="index" style="margin-left: 10%">
              <label style="color: #9BB9F1;">{{item.label}}</label>
              <i v-if="item.isPass === '1'" class="el-icon-success"></i>
              <i v-if="item.isPass === '0'" class="el-icon-error"></i>
          </div>
        </div>
      </el-card>
      <!--提交按钮-->
      <el-button class="submit-btn" type="primary" @click="submitApplication" :disabled="submitDisabled">提交申请</el-button>
      <!--PDF预览-->
      <el-dialog v-if="showStandard"  visible center title="任职资格标准预览" top="5vh" width="600px" :show-close="true" :before-close="closeStandardDialog" :close-on-click-modal="false">
        <Preview style="height: 500px" :parentUrl="'/qualifications-service/internal-informations/downloadQualificationStandard'"
                 :params=standardParams>
        </Preview>
      </el-dialog>
    </div>
</template>
      <script>
      import {
        getQualificationSequenceList, queryBasicInformation, submitQualificationApplication,
        getPerformanceRuleList, getAppCheck, baseUrl, getCourseList
      } from "@/api/userMG";
      import {left} from "core-js/internals/array-reduce";
      import Preview from "@/views/tools/preview.vue";
      import router from "@/router";

      export default {
        // 注册组件
        components: {
          Preview
        },
        data() {
          return {
            showStandard:false,
            baseInfoList: [],
            sequenceLevel:[],
            experience:[],
            orgCode: JSON.parse(localStorage.getItem('userdata')).orgCode,
            qualificationInfo:{
              sequenceBase:[],
              sequence:[
              ],
              level:[
              ]
            },
            applicationRule: [
            ],
            sequence:'',
            level:'',
            preformanceScore:0,
            maxSYear:0,
            maxLevel:'',
            maxLevelYear:0,
            performanceRuleDict:{},
            submitDisabled:true,
            standardParams:{},
            currentSequenceUrl:'',
            isInit:false,
            courseList: [],
            projectId: 0,
            defaultProps: {
              children: 'children',
              label: 'label'
            }
          };
        },
        methods: {
          baseUrl() {
            return baseUrl
          },
          left,
          submitApplication() {
            // 在这里实现提交逻辑
            let params = {
              orgCode:this.orgCode,
              currentDepartment: "现任职部门",
              qualificationStandardsId:this.level,
              userNo:JSON.parse(localStorage.getItem('userdata')).userNo,
              projectId:this.projectId
            }
            // 提交任职申请
            submitQualificationApplication(params).then(res => {
                if (res.code == 200) {
                  this.$message({
                    type: "success",
                    message: "提交成功!"
                  });
                  router.push("/qualification/appliedList")
                }else {
                  this.$message.error(res.msg);
                }
            })

          },
          changeSequence(val) {
            //清空
            this.qualificationInfo.level = []
            this.level = ''
            this.currentSequenceUrl =''
            this.courseList = []
            this.projectId = 0
            let levelList = this.qualificationInfo.sequenceBase.filter(item => item.positionName === val)
            levelList.forEach(item => {
              this.qualificationInfo.level.push({code:item.id,name:item.qualificationLevel})
              if(item.qualificationLevel === 'L1'){
                this.currentSequenceUrl = item.qualificationCriteria
              }
            })
          },
          clearSequence() {
            this.qualificationInfo.level = []
            this.currentSequenceUrl =''
            this.applicationRule =[]
            this.submitDisabled = true
            this.courseList = []
            this.projectId = 0
          },
          changeLevel(val) {
            let level = this.qualificationInfo.level.find(item => item.code === val).name
            let degree = this.baseInfoList.find(item => item.label === '最高学历').value
            this.applicationRule = []
            let eQualification = this.qualificationInfo.sequenceBase.filter(item => item.id === val)
            if(this.isInit){
              let sequence = this.sequenceLevel.filter(item => item.sequence === eQualification[0].positionName)
              if(sequence  === undefined || sequence.length === 0){
                this.applicationRule.push( {label:'初始化阶段只能选择初始化任职资格序列及等级',isPass:'0' })
              }else {
                if(sequence[0].level !== level){
                  this.applicationRule.push( {label:'初始化阶段只能选择初始化任职资格序列及等级',isPass:'0' })
                }else {
                  this.applicationRule.push( {label:'初始化任职资格序列及等级符合规则',isPass:'1' })
                }
              }
              this.submitDisabled = this.applicationRule.find(item => item.isPass === '0')
            }else {
              getAppCheck({level:level,degree:degree}).then(res => {
                let { code, msg, data } = res;
                if (code == 200) {
                  if(data.jx >= 99){
                    this.applicationRule.push( {label:'最高学历不符合申报条件',isPass:'0' })
                  }else {
                    //绩效规则校验
                    if (this.preformanceScore < data.jx) {
                      this.applicationRule.push({label: '近两年绩效未满足要求', isPass: '0'})
                    } else {
                      this.applicationRule.push({label: '近两年绩效满足要求', isPass: '1'})
                    }
                    //跨级申报
                    if(level.substr(1) - this.maxLevel <=1 ){
                      console.log(level.substr(1) - this.maxLevel)
                      //现任职资格校验
                      if(this.maxLevel < level.substr(1)){
                        if (this.maxLevelYear < data.pYear) {
                          this.applicationRule.push({label: '现任职资格等级停留年份不足', isPass: '0'})
                        }else {
                          this.applicationRule.push({label: '现任职资格等级停留年份满足要求', isPass: '1'})
                        }
                      }else {
                        this.applicationRule.push({label: '允许申报低等级或同等级序列', isPass: '1'})
                      }
                      this.applicationRule.push({label: '申请序列等级符合规则', isPass: '1'})
                    } else {
                      this.applicationRule.push({label: '申请序列等级不允许跨等级申报', isPass: '0'})
                    }
                    //专业年限
                    if (this.maxSYear < data.sYear) {
                      this.applicationRule.push({label: '专业年限不足', isPass: '0'})
                    }else {
                      this.applicationRule.push({label: '专业年限满足要求', isPass: '1'})
                    }
                  }
                }else{
                  this.applicationRule =[]
                  this.applicationRule.push({label: '获取任职资格审核规则失败，请联系管理员', isPass: '0'})
                }
                this.submitDisabled = this.applicationRule.find(item => item.isPass === '0')
              })
            }
            //获取课程清单
            let projectName = eQualification[0].positionName+'-'+eQualification[0].qualificationLevel
            getCourseList({"projectName": projectName}).then(res => {
              let { code, msg, data } = res;
              if (code == 200) {
                console.log(data)
                let courseList = []
                if(data !== undefined && data !== null && data.tasks !== undefined && data.tasks !== null){
                  for (let i = 0; i < data.tasks.length; i++) {
                    let courseItem = {}
                    let item = data.tasks[i]
                    courseItem.label = item.name
                    courseItem.children = []
                    if(item.kngs !==undefined && item.kngs !== null){
                      for (let j = 0; j < item.kngs.length; j++) {
                        let kng = item.kngs[j]
                        let kngLabel = kng.kngTitle
                        courseItem.children.push({label:kngLabel})
                      }
                    }
                    courseList.push(courseItem)
                  }
                  this.projectId = data.projectId
                }else {
                  courseList.push({label:'暂无课程信息'})
                }
                this.courseList = [{label:projectName,children:courseList}]
              }else{
                this.$message.error(res.msg);
              }
            })
          },
          clearLevel() {
            this.applicationRule =[]
            this.submitDisabled = true
            this.courseList = []
            this.projectId = 0
          },
          // 获取任职序列列表
          getQualificationSequenceList(){
            getQualificationSequenceList({orgCode:this.orgCode}).then(res => {
              console.log(res);
              if (res.code == 200) {
                let sequence = [];
                this.qualificationInfo.sequenceBase = res.data;
                res.data.forEach(item => {
                  sequence.push(item.positionName);
                })
                //去重
                sequence = Array.from(new Set(sequence));
                sequence.forEach(item => {
                  this.qualificationInfo.sequence.push({code:item,name:item})
                })
              }
            });
          },
          // 获取绩效规则
          getPerformanceRuleList(){
            let params = {}
            getPerformanceRuleList(params).then(res => {
              let { code, msg, data } = res;
              if (code == 200) {
                for (let i = 0; i < data.length; i++) {
                  this.performanceRuleDict[data[i].jxName] = data[i].score
                }
              }
            })
          },
          dealInfo(res){
            let keys= ['userName', 'curDepartment', 'curPosition', 'highestDegree', 'major', 'startWorkTime', 'joinTime', 'performance']
            let labels= ['姓名', '现任部门', '现任岗位', '最高学历', '所学专业', '参加工作时间', '加入中心时间', '近两年绩效']
            let { code, msg, data } = res;
            if (code == 200) {
              this.baseInfoList = []
              for (let i = 0; i < keys.length; i++) {
                let item = {}
                item.width = '40%'
                item.label = labels[i]
                item.value = data[keys[i]]
                this.baseInfoList.push(item)
              }
              //绩效积分计算
              this.calculatePerformance(data.performanceList)

              // 已获得任职资格序列及等级
              let nowDate = new Date((new Date).getTime() + 8*60*60*1000);
              let nowDateStr = nowDate.toJSON().split('T').join(' ').substr(0,19);
              let earliestLevelTime = nowDateStr
              let maxLevel = '1'
              this.baseInfoList.push({label:'已获得任职资格序列及等级',value:'已获得任职资格序列及等级', width:'90%' })
              data.sequenceLevel.forEach(item => {
                this.sequenceLevel.push({sequence:item.sequence,level:item.level, startTime:item.startTime, endTime: item.endTime, status: item.status, validTime: item.validTime})
                if(item.status === '7'){
                  this.isInit = true;
                }
                if(item.level.substr(1) >= maxLevel){
                  if(maxLevel != item.level.substr(1)){
                    earliestLevelTime =  item.time
                  }else {
                    if(item.time < earliestLevelTime){
                      earliestLevelTime =  item.time
                    }
                  }
                  maxLevel = item.level.substr(1)
                }
              });

              // 专业领域经历
              this.baseInfoList.push({label:'专业领域经历',value:'专业领域经历', width:'90%' })
              let earliest =nowDateStr
              data.experience.forEach(item => {
                this.experience.push({time:item.startDate+'至'+item.endDate,orgName:item.orgName,positionName:item.positionName})
                if(earliest > item.startDate){
                  earliest =  item.startDate
                }
              });
              //专业年限年数
              this.maxSYear = this.calculateDiff(earliest, nowDateStr)
              //最高任职资格等级停留年份
              this.maxLevelYear = this.calculateDiff(earliestLevelTime, nowDateStr)
              //最高的任职资格等级
              this.maxLevel = maxLevel
            }
          },
          //获取员工基本信息
          getEmployeeBaseInfo(){
            let userNo = JSON.parse(localStorage.getItem('userdata')).userNo
            if(userNo === '8888888'){
              let res = {"code":"200","msg":"获取任职申请基本信息成功！","data":{"userName":"admin","curDepartment":"无","curPosition":"无","curDeptTime":"无","highestDegree":"大学本科","major":"无","startWorkTime":"2013/07","joinTime":"2024/01/10","performance":"无","qualification":null,"sequenceLevel":[{"sequence":"其他","level":"L3","time":"2022-01-31"}],"experience":[{"startDate":"2024/01/10","endDate":"","orgName":"东风人事共享服务中心","positionName":""}],"performanceList":[{"performanceYear":"","performanceSelf":"C"},{"performanceYear":"","performanceSelf":"C"}]}}
              this.dealInfo(res)
            }else {
              queryBasicInformation({}).then(res => {
                this.dealInfo(res)
              });
            }
          },
          //计算两个时间相差的年数
          calculateDiff(startDateStr, endDateStr){
            const startDate = new Date(startDateStr);
            const endDate = new Date(endDateStr);
            const diffInMilliseconds = endDate - startDate;

            const daysInMonth = (year, month) => {
              const date = new Date(year, month, 0);
              return date.getDate();
            };

            let diffInDays = Math.floor(diffInMilliseconds / (1000 * 60 * 60 * 24));
            let years = 0, months = 0, days = 0;

            while (diffInDays >= 365) {
              const isLeapYear = (startDate.getFullYear() % 4 === 0 && startDate.getFullYear() % 100 !== 0) || startDate.getFullYear() % 400 === 0;
              const daysInYear = isLeapYear ? 366 : 365;
              if (diffInDays >= daysInYear) {
                years++;
                diffInDays -= daysInYear;
                startDate.setFullYear(startDate.getFullYear() + 1);
              } else {
                break;
              }
            }

            while (diffInDays >= daysInMonth(startDate.getFullYear(), startDate.getMonth())) {
              months++;
              diffInDays -= daysInMonth(startDate.getFullYear(), startDate.getMonth());
              startDate.setMonth(startDate.getMonth() + 1);
            }

            days = diffInDays;

            // const formatDiff = (years, months, days) => {
            //   return `${years}年${months}个月${days}天`;
            // };
            //
            // return formatDiff(years, months, days);
            return years
          },
          //计算绩效点数
          calculatePerformance(performanceList){
            this.preformanceScore = 0
            if(performanceList ===undefined || performanceList.length === 0){
              this.preformanceScore = 6
              return
            }else if(performanceList.length === 1){
              this.preformanceScore = 3
            }
            performanceList.forEach(item => {
              let performance = this.performanceRuleDict[item.performanceSelf]
              if(performance === undefined){
                this.preformanceScore += 3
              }else {
                this.preformanceScore += performance
              }
            })
            console.log(this.preformanceScore)
          },
          showStandardFile() {
            if(this.currentSequenceUrl ===''){
              this.$message.warning('请先选择任职资格序列')
              return
            }
            this.standardParams = {"qualificationCriteria":this.currentSequenceUrl}
            this.showStandard = true
          },
          closeStandardDialog(){
            this.showStandard = false
          },
        },
        created() {
          this.getPerformanceRuleList()
          this.getQualificationSequenceList()
          this.getEmployeeBaseInfo()
        }
      };
      </script>
      <style lang="scss" scoped>
      .home {
        margin-left: 2%;
        margin-right: 2%;
        width: 96%;
        //height: 1800px;
      }
      .task-process {
        //width: 100%;
        //display: flex;
        justify-content: space-between;
        margin-top: 20px;
        padding-bottom: 20px;
        padding-left: 15%;
        //height: 65px;
        border-radius: 10px; /* 增加圆角 */
        overflow: hidden; /* 防止圆角处内容溢出 */
        background-color: white;
      }

      .task-item {
        float: left;
        //display: flex;
        flex-direction: column;
        align-items: center;
      }
      .task-icon {
        text-align: center;
        font-size: 30px;
        color: #999;
        margin-bottom: 5px;
      }

      .circle {
        display: inline-block;
        width: 24px;
        height: 24px;
        border-radius: 50%;
        background-color: #FFFFFF;
        color: #999;
        text-align: center;
        line-height: 24px;
      }
      .active .circle {
        background-color: orangered;
        color: #fff;
      }

      .task-text {
        font-size: 14px;
        color: #666;
        width: 90px;
        text-align: center;
      }
      .active .task-icon {
        color: orangered;
      }
      .active .task-text {
        color: orangered;
      }
      .line-horizontal {
        float: left;
        width: 15%;
        height: 1px;
        background-color: #999;
        margin: 20px 0;
        position: relative;
      }
      .line-horizontal::after {
        content: "";
        position: absolute;
        top: -4px;
        right: -10px;
        border: 5px solid transparent;
        border-left-color: #999;
        transform: rotate(0deg);
      }
      .base-info{
        display: flex;
        justify-content: space-between;
        margin-top: 20px;
        //padding-top: 30px;
        background-color: white;
        border-radius: 10px; /* 增加圆角 */
        overflow: hidden; /* 防止圆角处内容溢出 */
      }
      .s-title{
        padding-top: 0;
        margin-bottom: 20px;
        font-weight: bold;
        font-size: 16px;
      }
      .job-application{
        //display: flex;
        justify-content: space-between;
        margin-top: 20px;
        //padding-top: 30px;
        background-color: white;
        border-radius: 10px; /* 增加圆角 */
        overflow: hidden; /* 防止圆角处内容溢出 */
      }
      .application-rule {
        justify-content: space-between;
        margin-top: 20px;
        //padding-top: 30px;
        background-color: white;
        border-radius: 10px; /* 增加圆角 */
        overflow: hidden; /* 防止圆角处内容溢出 */
      }
      .el-icon-success{
        color: green;
      }
      .el-icon-error{
        color: red;
      }
      .application-item{
        padding-bottom: 10px;
      }
      .el-table__header .cell{
        color: #000000;
        font-weight: bold;
      }
      .el-button--primary.is-disabled{
        cursor: not-allowed;
        background-color: indianred;
        border-color: indianred;
      }
      .submit-btn{
        margin-top: 10px;
        margin-left: 45%;
        background-color: orangered;
        border-color: orangered;
      }
      .submit-btn:not(.is-disabled):hover{
        cursor: pointer;
      }
      .el-button--primary {
        color: #FFF;
        background-color: orangered;
        border-color: orangered;
      }
      .el-button--primary.is-plain {
        background: #FFF;
        color: orangered;
        border-color: orangered;
      }
      ::v-deep .el-select-dropdown .el-select-dropdown__item.selected {
        color: orangered !important;
      }
      </style>
