<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <span style="font-weight:bold">绩效考核表</span>-{{form.name}}
        <dict-tag :options="dict.type.ehr_pm_status" :value="form.status" style="display:inline-block;margin-right:5px;" />
        <el-tag v-if="form.isTwoEvaluation">双向评估</el-tag>
        <div style="float: right; padding: 3px 0; display:flex;justify-content:space-between" type="text">
          <el-button size="mini" plain @click="btnBack">返回</el-button>
          <el-button type="primary" size="mini" @click="btnSubmit" :loading="loading" v-if="this.$store.state.user.name == form.staff && (form.status == '0' || form.status == '3')">提交</el-button>
          <ApproveLogDialog style="margin: 0 10px" :pmId="form.id"></ApproveLogDialog>
          <AdjustlogDialog style="margin: 0 10px" :pmId="form.id"></AdjustlogDialog>
          <el-button size="mini" plain @click="btnPreviou" v-if="ids">上一个</el-button>
          <el-button size="mini" plain @click="btnNext" v-if="ids">下一个</el-button>
        </div>
      </div>
      <div v-loading="loading">
        <el-form size="mini" ref="dataForm" :model="form" :rules="rules">
          <el-descriptions :column="6">
            <el-descriptions-item label="员工编号">{{form.staff}}</el-descriptions-item>
            <el-descriptions-item label="员工姓名">{{form.staffName}}</el-descriptions-item>
            <el-descriptions-item label="入职日期">{{form.dateJoin}}</el-descriptions-item>
            <el-descriptions-item label="转正日期">{{form.probationComplete}}</el-descriptions-item>
            <el-descriptions-item label="部门" span="2">{{form.deptName}}</el-descriptions-item>
            <el-descriptions-item label="职位">{{form.jobName}}</el-descriptions-item>
            <el-descriptions-item label="评估周期">{{form.name}}</el-descriptions-item>
            <el-descriptions-item label="评估人">{{form.evaluatorName}}</el-descriptions-item>
            <el-descriptions-item label="所属分组">
              <div v-for="dict in dict.type.ehr_pm_group" v-if="form.staffDivide == dict.value">
                <div>{{ dict.label }}</div>
              </div>
            </el-descriptions-item>
          </el-descriptions>
          <el-descriptions :column="6 ">
            <el-descriptions-item label="自评分" v-if="form.status > 3">{{form.saMark}}</el-descriptions-item>
            <el-descriptions-item label="上级评分" v-if="form.status > 4">{{form.ldMark}}</el-descriptions-item>
            <el-descriptions-item label="综合得分" v-if="form.status > 4">{{form.mark}}</el-descriptions-item>
          </el-descriptions>
          <el-row style="color: #606266;font-size: 14px;" v-if="form.status > 3">
            <el-col :span="2">
              个人总结：
            </el-col>
            <el-col :span="22">
              <div style="white-space: pre-wrap;text-align: left">{{form.summary}}</div>
            </el-col>
          </el-row>
          <div v-if="this.$store.state.user.name == form.staff && form.status == '3'">
            <el-form-item label="个人总结" prop="summary">
              <el-input type="textarea" placeholder="总结本月工作的亮点和暗点" v-model="form.summary"></el-input>
            </el-form-item>
          </div>
          <el-row style="margin-top:10px;color: #606266;font-size: 14px;" v-if="form.status > 4">
            <el-col :span="2">
              总评语:
            </el-col>
            <el-col :span="22">
              <div v-for="(item,index) in comment" :key="index">{{item[0]}}:{{item[1]}}</div>
            </el-col>
          </el-row>

          <div style="float: right; padding: 3px 0; display:flex;justify-content:space-between">
            <el-button type="primary" size="mini" @click="btnAddRow" v-if="this.$store.state.user.name == form.staff && form.status == '0' && form.performanceItem.length <= 4">增加指标</el-button>
            <CopyItemDialog style="margin: 0 10px" @setItems="setItems" v-if="this.$store.state.user.name == form.staff && form.status == '0'" :id="rowId"></CopyItemDialog>
          </div>
          <el-table size="mini"  :data="form.performanceItem" show-summary :summary-method="getSummaries" border :key="refreshTable">
            <el-table-column type="index" width="50" align="center" label="序号"/>
            <el-table-column width="100" label="评估方面" align="center" prop="aspect">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.ehr_pm_aspect" :value="scope.row.aspect"/>
              </template>
            </el-table-column>
            <el-table-column width="100" label="评估指标" align="center" prop="target" />
            <el-table-column width="80" label="权重(%)" align="center" prop="weight">
              <template slot-scope="scope">
                {{scope.row.asItem ? "+/-" : scope.row.weight}}
              </template>
            </el-table-column>
            <el-table-column label="指标说明" align="center" prop="instructions">
              <template slot-scope="scope">
                <div style="white-space: pre-wrap;text-align: left">{{scope.row.instructions}}</div>
              </template>
            </el-table-column>
            <el-table-column label="评分标准" align="center" prop="standard">
              <template slot-scope="scope">
                <div style="white-space: pre-wrap;text-align: left">{{scope.row.standard}}</div>
              </template>
            </el-table-column>
            <el-table-column width="100" label="数据来源" align="center" prop="source" />

            <el-table-column width="80" label="自评分" align="center" prop="selfScoring" v-if="form.status > 3"/>
            <el-table-column label="自评语" align="center" prop="selfComment" v-if="form.status > 3">
              <template slot-scope="scope">
                <div style="white-space: pre-wrap;text-align: left">{{scope.row.selfComment}}</div>
              </template>
            </el-table-column>

            <el-table-column width="85" label="自评分" align="center" prop="selfScoring" :render-header="addRedStar" v-if="this.$store.state.user.name == form.staff && form.status == '3'">
              <template slot-scope="scope">
                <el-form-item :prop="'performanceItem.'+scope.$index+'.selfScoring'" :rules="{required: true,message: ' ',trigger: 'blur'}">
                  <el-input  v-model="scope.row.selfScoring" v-only-number="{max:saMarkMax,min:0,precision:1}" size="mini" v-if="!form.scored.includes(scope.row.evaluator)"/>
                  <div v-else>{{scope.row.selfScoring}}</div>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="自评语" align="center" prop="selfComment" :render-header="addRedStar" v-if="this.$store.state.user.name == form.staff && form.status == '3'">
              <template slot-scope="scope">
                <el-form-item :prop="'performanceItem.'+scope.$index+'.selfComment'" :rules="{required: true,message: ' ',trigger: 'blur'}">
                  <el-input size="mini" type="textarea" :rows="3" v-model="scope.row.selfComment" v-if="!form.scored.includes(scope.row.evaluator)"/>
                  <div v-else>{{scope.row.selfComment}}</div>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column width="80" label="评估人" align="center" prop="evaluatorName" v-if="form.status > 4 && form.isTwoEvaluation"/>

            <el-table-column width="80" label="上级评分" align="center" prop="leaderScoring" v-if="form.status > 4"/>
            <el-table-column label="评分说明" align="center" prop="leaderComment" v-if="form.status > 4">
              <template slot-scope="scope">
                <div style="white-space: pre-wrap;text-align: left">{{scope.row.leaderComment}}</div>
              </template>
            </el-table-column>

            <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width" v-if="this.$store.state.user.name == form.staff && form.status == '0'">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="btnEdit(scope.row)">修改</el-button>
                <el-button size="mini" type="text" @click="btnDelete(scope.row)">删行</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
    </el-card>

    <el-dialog title="指标明细" :visible.sync="rowDataOpen" width="1000px" :close-on-click-modal="false" :show-close="false">
      <el-form size="mini" label-position="right" ref="rowDataForm" :model="rowData" :rules="rowRules" label-width="80px">
        <el-form-item label="评估方面" prop="aspect">
          <el-select v-model="rowData.aspect" >
            <el-option
              v-for="dict in dict.type.ehr_pm_aspect"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="评估指标" prop="target">
          <el-select v-model="rowData.target" v-if="form.isTwoEvaluation && (form.staff != '000178' && form.staff != '002594')">
            <el-option
              v-for="item in bothwayData[rowData.aspect]"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <el-input v-model="rowData.target" v-else></el-input>
        </el-form-item>
        <el-form-item label="加/减分项" prop="asItem">
          <el-checkbox v-model="rowData.asItem" @change="handleCheckedChange"></el-checkbox>
        </el-form-item>
        <el-form-item label="权重(%)" prop="weight" v-show="!rowData.asItem">
          <el-input  v-model.number="rowData.weight" v-only-number="{max:100,min:0,precision:0}" size="mini">
            <i slot="suffix" style="color: #000;font-style:normal;margin-right: 10px;">%</i>
          </el-input>
        </el-form-item>
        <el-form-item label="指标说明" prop="instructions">
          <el-input type="textarea" v-model="rowData.instructions" :rows="5"></el-input>
        </el-form-item>
        <el-form-item label="评分标准" prop="standard">
          <el-input type="textarea" v-model="rowData.standard" :rows="5"></el-input>
        </el-form-item>
        <el-form-item label="数据来源" prop="source">
          <el-input v-model="rowData.source"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="btnRowClose">取 消</el-button>
        <el-button size="mini" type="primary" @click="btnRowConfirm">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import ApproveLogDialog from './btnApproveLog.vue'
import AdjustlogDialog from './btnAjMarkLog.vue'
import CopyItemDialog from './btnCopyItem.vue'
import { getPerformance,fillinFinish,selfestimate,copyItem} from "@/api/business/ehr/pm/performance";
import { getPerformanceItem,addPerformanceItem,updatePerformanceItem,delPerformanceItem} from "@/api/business/ehr/pm/performanceitem";

export default {
  name: 'detail',
  dicts: ['ehr_pm_aspect','ehr_pm_role','ehr_pm_group','ehr_pm_status'],
  props: ['pageStu','rowId',"ids"],
  model: {
    prop: 'isList',
    event: 'jugislist'
  },
  components: {ApproveLogDialog,AdjustlogDialog,CopyItemDialog},
  data() {
    return {
      //id
      id:null,
      //刷新表格标记
      refreshTable:0,
      //表单
      form:{
        performanceItem:[]
      },
      //提交规则
      rules:{
        summary: [
          { required: true, message: " ", trigger: "blur" },
        ],
      },
      //遮罩
      loading: false,
      //单行明细
      rowData:{},
      //是否显示行明细弹出层
      rowDataOpen:false,
      //当行明细校验规则
      rowRules:{
        aspect: [
          { required: true, message: "评估方面不能为空", trigger: "blur" },
        ],
        target: [
          { required: true, message: "评估指标不能为空", trigger: "blur" },
        ],
        instructions: [
          { required: true, message: "评估说明不能为空", trigger: "blur" },
        ],
        role: [
          { required: true, message: "角色不能为空", trigger: "blur" },
        ],
        weight: [
          { required: true, message: "权重不能为空", trigger: "blur" },
        ],
        standard: [
          { required: true, message: "绩效标准不能为空", trigger: "blur" },
        ],
        source: [
          { required: true, message: "数据来源不能为空", trigger: "blur" },
        ],
      },
      //明细权重合计值
      weightSum: 0,
      //自评分
      saMark: 0,
      //双向评估评估方面选项
      bothwayData:{
        "5":[
          {
            value: '销售',
            label: '销售'
          },
          {
            value: '利润',
            label: '利润'
          },
          {
            value: '回款',
            label: '回款'
          },
          {
            value: '库存管理',
            label: '库存管理'
          },
          {
            value: '信息收集',
            label: '信息收集'
          },
        ],
        "6":[
          {
            value: '重点事项',
            label: '重点事项'
          },
        ],
      }
    }
  },
  computed: {
    //自评分最大值
    saMarkMax: function () {
      //业务组最高自评分为150；非业务组最高自评分为100；
      return this.form.staffDivide == 'C1' ? 150 : 100
    },
    comment() {
      if(this.form.comment){
        let obj = JSON.parse(this.form.comment);
        let arr = Object.entries(obj)
        return arr;
      }else{
        return [];
      }
    }
	},
  async created() {
    this.id = this.rowId;
    await this.fetchPerformance(this.id);
    if(this.form.isTwoEvaluation){
      this.dict.type.ehr_pm_aspect = this.dict.type.ehr_pm_aspect.filter(o => o.value == '5' || o.value == '6');
    }else{
      this.dict.type.ehr_pm_aspect = this.dict.type.ehr_pm_aspect.filter(o => !(o.value == '5' || o.value == '6'));
    }
    if(this.pageStu == 'add'){
    }
    if(this.pageStu == 'edit' || this.pageStu == 'see') {
    }
  },
  watch: {
  },
  methods: {
    //返回
    btnBack(){
      this.$emit('jugislist', true)
      this.$emit('refresh')
    },
    //查询详情
    async fetchPerformance(id){
      this.loading = true;
      await getPerformance(id).then(res => {
        if (res.code === 200) {
          this.form = res.data;
          this.id = res.data.id;
          this.refreshTable++;
         }
         this.loading = false;
      })
    },
    //增行
    btnAddRow(){
      this.rowData = {};
      this.rowData.assessId = this.form.id;
      this.rowDataOpen = true;
    },
    //修改
    async btnEdit(row){
      this.rowData = {};
      await getPerformanceItem(row.id).then(res => {
        if (res.code === 200) {
          this.rowData = res.data
          this.rowDataOpen = true;
         }
      })
    },
    //删行
    btnDelete(row){
      this.$modal.confirm('是否确认删除第"' + row.aspect + '"行数据？').then(function() {
        return delPerformanceItem(row.id);
      }).then(() => {
        this.fetchPerformance(this.id);
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    //单行明细取消
    btnRowClose(){
      this.rowData = {};
      this.$refs["rowDataForm"].resetFields();
      this.rowDataOpen = false;
    },
    //单行明细确认
    btnRowConfirm(){
      this.rowData.asItem = this.rowData.asItem ? true : false;
      if(this.rowData.asItem){
        this.rowData.weight = 0;
      }
      if(this.rowData.asItem && this.rowData.weight > 0){
        this.$modal.msgWarning("已勾选加减分项，不允许有权重！");
        return;
      }
      let sum = 100;
      if(this.rowData.id){
        let arr = this.form.performanceItem.filter(ele => ele.id != this.rowData.id);
        sum = arr.reduce((sum, e) => sum + Number(e.weight || 0), 0);
      }else{
        sum = this.form.performanceItem.reduce((sum, e) => sum + Number(e.weight || 0), 0);
      }
      if(sum + this.rowData.weight > 100){
        this.$modal.msgWarning("总权重超过100，剩余权重比为" + (100 - sum));
        return;
      }
      this.$refs["rowDataForm"].validate(valid => {
        if (valid) {
          if (this.rowData.id != undefined) {
            updatePerformanceItem(this.rowData).then(response => {
              this.$modal.msgSuccess("保存成功");
              this.rowDataOpen = false;
              this.fetchPerformance(this.id);
            });
          } else {
            addPerformanceItem(this.rowData).then(response => {
              this.$modal.msgSuccess("保存成功");
              this.rowDataOpen = false;
              this.fetchPerformance(this.id);
            });
          }
        }
      });
    },
    //上一个
    btnPreviou(){
      let i = this.ids.indexOf(this.id) - 1;
      if(i > -1){
        let id = this.ids[i];
        this.fetchPerformance(id);
      }else{
        this.$modal.msgSuccess("已经是当前页第一条了！");
      }
    },
    //下一个
    btnNext(){
      let i = this.ids.indexOf(this.id) + 1;
      if(i < this.ids.length){
        let id = this.ids[i];
        this.fetchPerformance(id);
      }else{
        this.$modal.msgSuccess("已经是当前页最后一条了！");
      }

    },
    //合计
    getSummaries(param){
      const { columns, data } = param;
      let weight = data.reduce((sum, e) => sum + Number(e.weight || 0), 0);
      this.weightSum = weight;
      let selfScoring = 0;
      selfScoring = data.reduce((sum, e) => sum + (e.asItem ? Number(e.selfScoring || 0) :  Number(e.selfScoring || 0) * (Number(e.weight || 0) / 100)), 0);
      selfScoring = selfScoring.toFixed(1);
      this.saMark = selfScoring;
      if(this.form.isTwoEvaluation){
        if(this.form.status == 0){
          return ['合计','','',weight,'','','',''];
        }else{
          return ['合计','','',weight,'','','',selfScoring,'','',this.form.ldMark];
        }
      }else{
        return ['合计','','',weight,'','','',selfScoring,'',this.form.ldMark];
      }
    },
    //提交
    btnSubmit(){
      if(this.form.status == '0'){
        if(this.weightSum != 100){
          this.$modal.msgWarning("权重不为100%无法提交！");
          return;
        }
        let that = this;
        this.$modal.confirm('确认提交吗？').then(async function() {
          that.loading = true;
          return await fillinFinish(that.form);
        }).then(() => {
          that.fetchPerformance(that.id);
          that.$modal.msgSuccess("提交成功");
          that.loading = false;
        }).catch(() => {
          that.loading = false;
        });
      }
      if(this.form.status == '3'){
        if(this.form.staffDivide == 'C1' && this.saMark > 150){
          this.$modal.msgWarning("业务组自评总分不能超过150！");
          return;
        }
        if(this.form.staffDivide == 'C2' && this.saMark > 100){
          this.$modal.msgWarning("非务组自评总分不能超过100！");
          return;
        }
        this.$refs["dataForm"].validate(async valid => {
          if (valid) {
            let that = this;
              this.$modal.confirm('确认提交吗？').then(async function() {
                that.loading = true;
                return await selfestimate(that.form);
              }).then(() => {
                that.fetchPerformance(that.id);
                that.$modal.msgSuccess("提交成功");
                that.loading = false;
              }).catch(() => {
                that.loading = false;
              });
          }else{
            this.$modal.msgWarning("评分或评语不能为空！");
            return false;
          }
        });
      }
    },
    //设置明细
    async setItems(cId){
      let params = {
        id : this.id,
        cId : cId
      }
      let res = await copyItem(params);
      if("200" == res.code){
        this.$modal.msgSuccess("复制成功");
        this.fetchPerformance(this.id);
      }
    },
    //选择加减分项后
    handleCheckedChange(value){
    },
    //必选标识
    addRedStar(h, { column }) {
      return [
        h('span', { style: 'color: #F56C6C' }, '*'),
        h('span', ' ' + column.label)
      ];
    },
  }
}
</script>

<style lang="scss" scoped>

.btn_group {
  z-index: 500;
  position: fixed;
  bottom: 0;
  width: 100%;
  line-height: var(--footer-height);
  color: #fff;
}
</style>
