<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <span style="font-weight:bold">绩效考核表</span>-{{form.name}}
        <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-descriptions v-if="form.status > 3">
            <el-descriptions-item label="个人总结">{{form.summary}}</el-descriptions-item>
          </el-descriptions>
          <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-descriptions v-if="form.status > 4">
            <el-descriptions-item label="总评语">{{form.comment}}</el-descriptions-item>
          </el-descriptions>
          <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>
            <!-- <el-button size="mini" @click="btnUnfold">{{isUnfold == true ? "收起" : "展开"}}</el-button> -->
          </div>
          <el-table size="mini"  :data="form.performanceItem" show-summary :summary-method="getSummaries" border>
            <el-table-column type="index" width="50" align="center" label="序号"/>
            <el-table-column width="100" :show-overflow-tooltip="!isUnfold" 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" :show-overflow-tooltip="!isUnfold" 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 :show-overflow-tooltip="!isUnfold" 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 width="100" label="角色" align="center" prop="role">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.ehr_pm_role" :value="scope.row.role"/>
              </template>
            </el-table-column> -->
            <el-table-column :show-overflow-tooltip="!isUnfold" 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 :show-overflow-tooltip="!isUnfold" label="自评语" align="center" prop="selfComment" v-if="form.status > 3"/>
              
            <el-table-column width="80" 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"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="!isUnfold" 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"></el-input>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column width="80" label="上级评分" align="center" prop="leaderScoring" v-if="form.status > 4"/>
            <el-table-column :show-overflow-tooltip="!isUnfold" label="评分说明" align="center" prop="leaderComment" v-if="form.status > 4"/>
            <!-- <el-table-column width="80" label="加权得分" align="center" prop="weightedScore" v-if="form.status > 4"/> -->
          
            <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-input v-model="rowData.target"></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-if="!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="role">
          <el-select v-model="rowData.role" >
            <el-option
              v-for="dict in dict.type.ehr_pm_role"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </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'],
  props: ['pageStu','rowId',"ids"],
  model: {
    prop: 'isList',
    event: 'jugislist'
  },
  components: {ApproveLogDialog,AdjustlogDialog,CopyItemDialog},
  data() {
    return {
      //id
      id:null,
      //表单
      form:{},
      //提交规则
      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" },
        ],
      },
      //是否展开
      isUnfold:false,
      //明细权重合计值
      weightSum: 0,
      //自评分
      saMark: 0,
    }
  },
  computed: {
    //自评分最大值
    saMarkMax: function () {
      //业务组最高自评分为150；非业务组最高自评分为100；
      return this.form.staffDivide == 'C1' ? 150 : 100
    },
	},
  async created() {
    this.id = this.rowId;
    this.fetchPerformance(this.id);
    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.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.rowDataOpen = false;
    },
    //单行明细确认
    btnRowConfirm(){
      if(this.form.staffDivide == 'C1' && this.rowData.aspect == 0 && this.rowData.weight < 80){
        this.$modal.msgSuccess("业务组的业绩考核权重不能低于80！");
        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);
      }
      console.log("sum",sum);
      console.log("sum + this.rowData.weight",sum + this.rowData.weight);
      if(sum + this.rowData.weight > 100){
        this.$modal.msgSuccess("总权重超过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);
            });
          }
        }
      });
    },
    //展开/收起
    btnUnfold(){
      this.isUnfold = !this.isUnfold;
    },
    //上一个
    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;
      if(this.form.saMark){
        selfScoring = this.form.saMark;
      }else{
        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;
      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){
      this.rowData.weight = 0;
    },
    //必选标识
    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>
