<template>
<!-- 定量考核打分 -->
  <div class="dashboard-container">
    <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true" :model="searchInfo">
        
          <el-form-item label="所属部门" prop="title">
            <el-cascader filterable clearable v-model="searchInfo.departmentid" :options="departmentList" :show-all-levels="false" :props="props1"></el-cascader>
                
          </el-form-item>
          <el-form-item label="指标名称">
          <el-input
            placeholder="请输入名称"
            v-model="searchInfo.title"
            clearable>
          </el-input>
        </el-form-item>
         <!-- <el-cascader clearable v-model="searchInfo.departmentid" :options="grouplist" :show-all-levels="false" :props="props"></el-cascader> -->
        
        <el-form-item>
          <el-button size="mini" type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>
          <!-- <el-button size="mini" icon="el-icon-refresh" @click="onReset">重置</el-button> -->
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <!-- <div class="gva-btn-list">
        <el-button size="mini" type="primary" icon="el-icon-plus" @click="showAdd()">新增</el-button>
      </div> -->
      <el-table :data="tableData" border :span-method="objectSpanMethod">
        <el-table-column align="left" label="部门" prop="parentname"/>
        <el-table-column align="left" label="考核指标" prop="targetname"/>
        
        <el-table-column align="left" label="全奖值" prop="unit" width="65">
          <template slot-scope="scope">
            {{scope.row.allprize}}
          </template>
        </el-table-column>
        <el-table-column align="left" label="零奖值" prop="unit" width="65">
          <template slot-scope="scope">
            {{scope.row.zeroprize}}
          </template>
        </el-table-column>
        <el-table-column align="left" label="封顶值" prop="unit" width="65">
          <template slot-scope="scope">
            {{scope.row.cappingcal}}%
          </template>
        </el-table-column>
        <el-table-column align="left" label="考核说明" prop="content"/>
        <el-table-column align="left" label="指标权重分" prop="targetweight" width="100"/>
        <el-table-column align="left" label="实际值" prop="actual">
          <template slot-scope="scope">
            <el-input @input="inputActual(scope.row,scope.$index)" v-model="scope.row.actual" autocomplete="off"/>
          </template>
        </el-table-column>
        <el-table-column align="left" label="得分" prop="actual">
          <template slot-scope="scope">
            <el-input v-if="scope.row.scoringmethod==2" v-model="scope.row.scoringscore" autocomplete="off"/>
            <div v-if="scope.row.scoringmethod==1">{{scope.row.scoringscore}}</div>
            
          </template>
        </el-table-column>
        <el-table-column align="left" label="达成率" prop="reach"/>
        <!-- <el-table-column align="left" label="单位" prop="unit"/>
        <el-table-column align="left" label="分数" prop="score">
          <template slot-scope="scope">
            <el-input v-model.number="scope.row.score" autocomplete="off"/>
          </template>
        </el-table-column> -->
        <el-table-column align="left" label="说明" prop="score">
          <template slot-scope="scope">
            <el-input v-model="scope.row.reason" autocomplete="off"/>
          </template>
        </el-table-column>
        <el-table-column align="left" label="流程" width="100">
          <template #default="scope">
            <el-button
              icon="el-icon-view"
              size="small"
              type="text"
              @click="showProcess(scope.row)"
            >查看流程</el-button>
            <!-- <el-button
              icon="el-icon-remove-outline"
              size="small"
              type="text"
              @click="showJian(scope.row)"
            >减分</el-button> -->
          </template>
        </el-table-column>
        <el-table-column align="left" label="考核周期">
          <template slot-scope="scope">
            <el-date-picker
              style="width:120px"
              v-model="scope.row.month"
              type="month"
              value-format="yyyy-MM"
              placeholder="请选择">
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column align="left" fixed="right" label="操作">
          <template #default="scope">
            <el-button
              icon="el-icon-circle-plus-outline"
              size="small"
              type="text"
              @click="tijiao(scope.row)"
            >提交</el-button>
            <!-- <el-button
              icon="el-icon-remove-outline"
              size="small"
              type="text"
              @click="showJian(scope.row)"
            >减分</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <!-- <el-button size="small" type="primary" @click="tijiao">提  交</el-button> -->
      </div>
      <!-- 新增弹框 -->
      <el-dialog :close-on-click-modal="false" :visible.sync="dialogFormVisible" title="流程详情" width="20%">
        <el-card class="box-card">
          <el-steps direction="vertical" :active="buzhou">
              <el-step v-for="(item,index) in processData" :key="index" :title="item.nodename" icon="el-icon-circle-check" > 
                  <template slot="description">
                      <div style="color: rgb(153,153,153);" v-for="(a,userlistIndex) in item.userlist" :key="userlistIndex">
                        <el-row>
                            <el-col :span="4" v-if="a.log!=null">
                                <el-badge is-dot type="primary ">
                                    <el-avatar style="margin-right: 5px;" shape="square" size="small" :src="a.icon"></el-avatar>
                                </el-badge>
                            </el-col>
                            <el-col :span="4" v-else>
                                <el-avatar style="margin-right: 5px;" shape="square" size="small" :src="a.icon"></el-avatar>
                            </el-col>
                            <el-col :span="20" style="margin-top: -5px;">
                                {{a.workshopname}}-{{a.postname}}-{{a.name}}
                                <el-row>
                                    <div v-for="(i,logIndex) in a.log" :key="logIndex">
                                        <div class="left" v-if="i.state==2">已同意&nbsp·&nbsp</div>
                                        <div class="left" v-if="i.state==1" type="info">未操作&nbsp·&nbsp</div>
                                        <div class="left" v-if="i.state==3" type="danger">驳回&nbsp·&nbsp</div> 
                                        <div class="left">{{i.time}}</div>
                                    </div>
                                </el-row>
                            </el-col>
                        </el-row>
                      </div>
                  </template>
              </el-step>
          </el-steps>
               
            </el-card>
      </el-dialog>
      <!-- 编辑弹框 -->
      <el-dialog :close-on-click-modal="false" :visible.sync="editDialogFormVisible" :before-close="editCloseDialog" title="修改" width="20%">
        <el-form ref="editForm" :model="editAdd" :rules="editRules" label-width="150px">
          <el-form-item label="考核维度名称" prop="title">
            <el-input v-model="editAdd.title" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer"> 
            <el-button size="small" @click="editCloseDialog">取 消</el-button>
            <el-button size="small" type="primary" @click="editEnterDialog">确 定</el-button>
          </div>
        </template>
      </el-dialog>
  </div>
</template>

<script>
import { examineflow,qualitativeevalration,getgroupdepartmap,addflowrationlog,departmentlist,quanOperation } from '@/api/api/dutys'
export default {
  name: 'Dashboard',
  data() {
    return {
      month:'',
      fromData:[],
      buzhou:0,
      props1: {
        checkStrictly: true,
        value: "id",
        label: "name",
        children: "children",
        emitPath:false,
      },
      props: {
        value: "id",
        label: "name",
        children: "children",
        emitPath:false,
        multiple: false
      },
      processData:[],
      // 部门列表
      grouplist:[],
      // 查询详情的数据
      editFrom:{},
      // 修改状态提交数据
      switchFrom:{},
      // 删除数据提交
      deleFrom:{},
      // 编辑时数据
      editAdd:{},
      assessList:{},
      // 添加数据
      form:{},
      spanArr:[],
      pos:'',
      // 弹窗变量
      dialogFormVisible:false,
      // 修改弹窗
      editDialogFormVisible:false,
      total: 0,
      tableData:[],
      // 条件查询变量
      searchInfo: {
        groupid:'',
        departmentid:''
      },
      // 部门列表
      departmentList:[],
      // 条件查询变量
      abc:{
        aaa:"111",
        bbb:"222"
      },
      // 添加时验证规则
      rules: {
        title: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      },
      editRules:{
        title: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      }
    }
  },
  async created() {
    console.log(this.$store.state.user.token)
    if (this.$store.state.user.token=='') {
      this.$router.push('/login')
    }
    this.getGrouplist()
    // this.$alert('请选择部门后再操作', '提示', {
    //       confirmButtonText: '确定',
          
    //     });
   this.getChuDataList()
    // this.getDataList()
  },
  // 监听数据
  watch: {
    tableData() {
      this.$nextTick(() => {
        this.spanArr=[],
        this.pos='',
        //此时就可以获取到在created赋值后的dataList了
        this.getSpanArr(this.tableData);
      });
    },
// 　　}
  },
  methods: {
    // 查看流程
    async showProcess(row){
      this.buzhou=0
      const processFrom ={
        id:row.id
      }
      const res = await examineflow(processFrom)
      this.processData=res.data
      this.processData.forEach(element => {
            if (element.state==2) {
                this.buzhou=this.buzhou+1
            }
        });
      this.dialogFormVisible=true
    },
    // 公式换算
		// (实际值—零奖值)/（全奖值-零奖值）*100+‘%’
		inputActual(val,index){
      console.log(val)
      console.log(index)
			var a = val.actual-val.zeroprize
			var b = val.allprize-val.zeroprize
      // var a = 5-2
			// var b = 6-1
      console.log(a/b*100+'%')
      if (a/b*100!=Infinity) {
        var e =a/b*100
				var d
        console.log("e")
        console.log(e)
				if (e>this.tableData[index].cappingcal) {
					d=this.tableData[index].targetweight*this.tableData[index].cappingcal/100
				} else{
					var d =parseFloat(this.tableData[index].targetweight*(a/b)).toFixed(2)
				}
				var c =parseFloat(a/b*100).toFixed(2)
				this.tableData[index].reach=c+'%'
				this.tableData[index].scoringscore=d
        if (c<0) {
          this.tableData[index].reach=0+'%'
        }
        if (d<0) {
          this.tableData[index].scoringscore=0
        }
        // this.tableData[index].reach=a/b*100+'%'
        // this.tableData[index].scoringscore=this.tableData[index].targetweight*a/b
      }
      if (a/b*100==Infinity) {
        this.tableData[index].reach="数据错误/未设置全奖值，零奖值"
        this.tableData[index].scoringscore="数据错误/未设置全奖值，零奖值"
      }
		},
    // 获取部门
    async getGrouplist(){
       const departmentFrom={
        // id:2
    }
    const res = await departmentlist(departmentFrom)
    this.departmentList=res.data

    },
    // 提交
    tijiao(row){
      this.$confirm('批量提交, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          this.fromData=[],
          this.tableData.forEach(ele=>{
        if (ele.parentid==row.parentid) {
          this.fromData.push(ele)
        }
      })
      console.log("提交")
      this.fromData.forEach(ele=>{
        ele.scoringscore=parseFloat(ele.scoringscore)
      })
      console.log(this.fromData)
      console.log(this.fromData[0].month,)
      const from ={
        groupid: '309',
        departmentid: row.parentid.toString(),
        planversionnumber:this.fromData[0].planversionnumber,
        time:this.fromData[0].month,
        list:this.fromData
      }
     
      const res = await quanOperation(from)
      if (res.code === 0) {
            this.$message({
              type: 'success',
              message: res.msg
            })
          }
        })
      
      
    },
    // 部门列合并
    getSpanArr(data) {
        // data就是我们从后台拿到的数据
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr.push(1);
          this.pos = 0;
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].parentid === data[i - 1].parentid) {
            this.spanArr[this.pos] += 1;
            this.spanArr.push(0);
          } else {
            this.spanArr.push(1);
            this.pos = i;
          }
        }
      }
    },
    // 合并行
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0||columnIndex ===12||columnIndex ===13) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        console.log(`rowspan:${_row} colspan:${_col}`);
        return {
          // [0,0] 表示这一行不显示， [2,1]表示行的合并数
          rowspan: _row,
          colspan: _col
        };
      }
    },
    // 删除操作
    //删除操作
    async deleteOperate(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          this.deleFrom.state=3;
          this.deleFrom.outid=row.outId;
          const res = await statedutyclass(this.deleFrom)
          if (res.code === 0) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            
             this.getDataList()
          }
        })
    },
    // 新增按钮
    showAdd(){
      this.dialogFormVisible=true;
      console.log(this.dialogFormVisible)
    },
    // 编辑按钮
    async showEdit(row){
      this.editFrom.outid=row.outId
      const res = await getdutyclassinfo(this.editFrom)
      this.editAdd = res.data
      this.editDialogFormVisible=true;

    },
    // 开关状态监听
   async changeVal(val,id){
       console.log(val)
      this.switchFrom.outid=id
      if (val==1) {
        this.switchFrom.state=1;
        const res = await statedutyclass(this.switchFrom)
                if (res.code === 0) {
                  this.$message({
                    type: 'success',
                    message: '修改状态成功',
                    showClose: true
                  })
                  this.getDataList()
                }
      } else {
        this.switchFrom.state=2;
        const res = await statedutyclass(this.switchFrom)
                if (res.code === 0) {
                  this.$message({
                    type: 'success',
                    message: '修改状态成功',
                    showClose: true
                  })
                  this.getDataList()
                }
      }
    },
    // 重置搜索条件
    onReset() {
      this.searchInfo = {}
    },
    // 条件搜索
    onSubmit() {
      this.getDataList()
    },
    // 日期时间戳转日期格式
    formatDate(nS) {     
      return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/,' ');     
    },
   
    // 提交按钮
    async enterDialog(){
          const res = await adddutyclass(this.form)
          if (res.code === 0) {
                  this.$message({
                    type: 'success',
                    message: '添加成功',
                    showClose: true
                  })
                }
          this.getDataList();
          this.closeDialog();
        
    },

    // 编辑提交按钮
    async editEnterDialog(){
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          const res = await eitedutyclassinfo(this.editAdd)
          if (res.code === 0) {
                  this.$message({
                    type: 'success',
                    message: '编辑成功',
                    showClose: true
                  })
                }
          this.getDataList();
          this.editCloseDialog();
        }
      })
    },
    // 添加框关闭
    closeDialog() {
      console.log("closeDialog")
      this.initForm()
      this.dialogFormVisible = false
    },
    // 修改框关闭
    editCloseDialog() {
      this.editInitForm()
      this.editDialogFormVisible = false
    },
    // 添加重置表单
    initForm() {
      console.log("initForm")
      this.$refs.addForm.resetFields()
      this.form = {}
      console.log(this.form)
    },
    // 修改重置表单
    editInitForm() {
      this.$refs.editForm.resetFields()
      this.editAdd = {}
    },
    // 改变pageSize
    handleSizeChange(val) {
      this.searchInfo.pagesize=val
      this.getDataList(this.searchInfo)
    },
    // 改变page
    handleCurrentChange(val) {
      this.searchInfo.page=val
      this.getDataList(this.searchInfo)
    },
    // 获取初始数据
    async getDataList() {
      const bumen =JSON.parse(JSON.stringify(this.searchInfo.departmentid))

      const from={
        groupid:'309',
        departmentid:'',
        title:''
      }
      console.log(bumen+'')
      from.title=this.searchInfo.title
      from.departmentid=bumen.toString();
      const res = await qualitativeevalration(from)
      this.tableData = res.data
    },
    // 获取初始数据
    async getChuDataList() {
      

      const from={
        groupid:'309',
       
      }
      
      const res = await qualitativeevalration(from)
      this.tableData = res.data
      this.tableData.forEach(ele=>{
        this.$set(ele, 'scoringscore', 0)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
</style>
