<template>
<!-- 部门考核录入 -->
  <div class="dashboard-container">
    <!-- <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true" :model="searchInfo">
        <el-form-item label="所属定量考核">
          <span>
            <el-tag v-if="childInfo.title!=''">{{childInfo.title}}</el-tag>
            <projectDialog @checkedInfo="getCheckedInfo"></projectDialog>
          </span>
        </el-form-item>
        <el-form-item label="定性指标名称">
          <el-input
            placeholder="请输入名称"
            v-model="searchInfo.title"
            clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="定性指标状态">
          <el-select v-model="searchInfo.state" clearable placeholder="请选择状态">
            <el-option :value=1 label="正常">正常</el-option>
            <el-option :value=2 label="禁止">禁止</el-option>
          </el-select>
        </el-form-item>
        <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-setting" @click="showDimension()">设置维度权重</el-button>
        <el-button size="mini" type="primary" icon="el-icon-setting" @click="showIndex()">设置指标权重</el-button>
      </div> -->
      <el-table :data="tableData" border :span-method="objectSpanMethod">
        <el-table-column prop="parentname" label="部门"></el-table-column>
        <el-table-column prop="dimensionname" label="考核维度"></el-table-column>
        <el-table-column prop="dimensionweight" label="维度权重"></el-table-column>
        <el-table-column prop="targetname" label="考核指标">
          <template slot-scope="scope">
            <el-link v-if="scope.row.type==1" type="primary" @click="showMethod(scope.row)">{{scope.row.targetname}}</el-link>
            <div v-if="scope.row.type==2">{{scope.row.targetname}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="targetweight" label="指标权重"></el-table-column>
        <el-table-column prop="unit" label="单位"/>
        <el-table-column prop="referencescore" label="分值"/>
        <el-table-column prop="cycle" label="周期">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.cycle==1">班</el-tag>
            <el-tag v-if="scope.row.cycle==2">天</el-tag>
            <el-tag v-if="scope.row.cycle==3">周</el-tag>
            <el-tag v-if="scope.row.cycle==4">月</el-tag>
            <el-tag v-if="scope.row.cycle==5">季度</el-tag>
            <el-tag v-if="scope.row.cycle==6">年</el-tag>
          </template>
        </el-table-column>
         <el-table-column prop="cycleattr" label="频次">
          <template slot-scope="scope">
            <div v-if="scope.row.cycle==1">每班{{scope.row.cycleattr}}次</div>
            <div v-if="scope.row.cycle==2">每天{{scope.row.cycleattr}}次</div>
            <div v-if="scope.row.cycle==3">每周{{scope.row.cycleattr}}次</div>
            <div v-if="scope.row.cycle==4">每月{{scope.row.cycleattr}}次</div>
            <div v-if="scope.row.cycle==5">每季度{{scope.row.cycleattr}}次</div>
            <div v-if="scope.row.cycle==6">每年{{scope.row.cycleattr}}次</div>
          </template>
        </el-table-column>
        <el-table-column prop="userlist" label="执行人">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-view"
              size="small"
              type="text"
              @click="showUserList(scope.row)"
            >查看</el-button>
          </template>
        </el-table-column>
       </el-table>
      </div>
      <!-- 新增弹框 -->
      <el-dialog :visible.sync="dialogFormVisible" :before-close="closeDialog" title="新增" width="100%">
        
        <el-form ref="addForm" :model="form" :rules="rules" label-width="150px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="所属公司" prop="title">
                <el-select v-model="form.group" clearable placeholder="请选择" @change="selectGroup">
                  <el-option
                    v-for="item in companyList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属部门" prop="title" v-if="form.group!=''">
                <el-select multiple v-model="form.parentid" clearable placeholder="请选择" @change="selectDepartment">
                  <el-option
                    v-for="item in departmentList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="考核维度">
                <el-select v-model="form.dimension" clearable placeholder="请选择状态">
                  <el-option
                    v-for="item in dutyclasslist"
                    :key="item.outId"
                    :label="item.title"
                    :value="item.outId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属部门" prop="title" v-if="form.group!=''">
                <el-select multiple v-model="form.parentid" clearable placeholder="请选择" @change="selectDepartment">
                  <el-option
                    v-for="item in departmentList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        <el-form-item v-if="form.parentid!=''">
          <!-- 表格表单提交 -->
            <el-table
                :data="indexList"
                style="width: 100%">
                
                <el-table-column
                    label="名称"
                    align="center"
                    prop="title"
                    >
                </el-table-column>
                <el-table-column
                    label="考核周期"
                    align="center">
                    <template slot-scope="scope">
                       <el-select v-model="scope.row.cycle" placeholder="请选择考核周期">
                        <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                      </el-select>
                    </template>
                </el-table-column>
                <el-table-column
                    label="辅助计数"
                    align="center">
                    <template slot-scope="scope">
                       <el-input v-model="scope.row.cycleattr" autocomplete="off" />
                    </template>
                </el-table-column>
                <el-table-column
                    label="单位"
                    align="center">
                    <template slot-scope="scope">
                       <el-input v-model="scope.row.unites"></el-input>
                    </template>
                </el-table-column>
                <!-- <el-table-column
                    label="分值"
                    align="center">
                    <template slot-scope="scope">
                       <el-input v-model.number="scope.row.referencescore"></el-input>
                    </template>
                </el-table-column> -->
                <el-table-column
                    label="数据提报"
                    align="center">
                    <template slot-scope="scope">
                          <el-cascader clearable v-model="scope.row.reportlist" :options="grouplistBackup" :show-all-levels="false" :props="userProps"></el-cascader>
                    </template>
                </el-table-column>
                <el-table-column align="left" fixed="right" label="操作">
                  <template #default="scope">
                    <el-button
                      icon="el-icon-delete"
                      size="small"
                      type="text"
                      @click="deleteRow(scope)"
                    >删除</el-button>
                  </template>
                </el-table-column>
            </el-table>
        </el-form-item>
         
        </el-form>
        <template #footer>
          <div class="dialog-footer"> 
            <el-button size="small" @click="closeDialog">取 消</el-button>
            <el-button size="small" type="primary" @click="enterDialog">确 定</el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 人员弹框 -->
      <el-dialog :visible.sync="showUser" title="执行人" width="30%">
        <el-descriptions class="margin-top" :column="3" size="medium" border>
          <el-descriptions-item v-for="item in userlistary" :key="item.key">
            <template slot="label">
              <i class="el-icon-user"></i>
              姓名
            </template>
            {{item.name}}
          </el-descriptions-item>
        </el-descriptions>
      </el-dialog>
      <!-- 编辑弹框 -->
      <el-dialog :visible.sync="editDialogFormVisible" :before-close="editCloseDialog" title="修改" width="20%">
        <el-form ref="editForm" :model="editAdd" :rules="editRules" label-width="150px">
          <el-form-item label="所属考核项目">
          <span>
            <el-tag v-if="editChildInfo.title!=''">{{editChildInfo.title}}</el-tag>
            <projectDialog @checkedInfo="getEditCheckedfrom"></projectDialog>
          </span>
        </el-form-item>
        <el-form-item label="定性指标名称" prop="title">
                <el-input v-model="editAdd.title" autocomplete="off" />
            </el-form-item>
        <el-form-item label="定性指标说明" prop="content">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4}"
            placeholder="请输入内容"
            v-model="editAdd.content">
          </el-input>
        </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>
      <!-- 考核办法弹框 -->
      <el-dialog :visible.sync="methodShow" title="考核办法" width="60%">
        <el-table :data="methodList" border :span-method="methodSpanMethod">
          <el-table-column prop="targetsunname" label="考核项目"></el-table-column>
          <!-- <el-table-column prop="targetsunname" label="权重"></el-table-column> -->
          <el-table-column prop="detailedtargetname" label="考核标准"></el-table-column>
          <el-table-column prop="content" label="考核办法"></el-table-column>
          <!-- <el-table-column prop="unit" label="单位"/> -->
          <el-table-column prop="referencescore" label="标准分"/>
          
        </el-table>
      </el-dialog>
  </div>
</template>

<script>
import { dutyclasslist } from '@/api/duty/dimension'
import { gettasktarget,gettasktargetsun,gettasktargetcontary,addqualeval,addration,departmenttasklist } from '@/api/duty/duty'
import projectDialog from '@/components/projectDialog/index.vue'
import { dutylist,getdutyinfo,eitedutyinfo,eitedutystate } from '@/api/duty/quantitativeIndicators'
import {
  grouplist,
  departmentlist,
  getgroupdepartmap,
  getgroupuser
} from '@/api/duty/group'
export default {
  name: 'Dashboard',
  components: {
    projectDialog
  },
  data() {
    return {
      // 执行人列表
      userlistary:[],
      // 执行人列表弹窗
      showUser:false,
      // 选择员工配置项
      userProps: {
        value: "id",
        label: "name",
        children: "groupUser",
        emitPath:false,
        multiple: true
      },
      // 员工列表
      grouplistBackup:[],
      // 周期列表
      options: [{
            value: 1,
            label: '班'
        }, {
            value: 2,
            label: '天'
        }, {
            value: 3,
            label: '周'
        }, {
            value: 4,
            label: '月'
        }, {
            value: 5,
            label: '季度'
        }, {
            value: 6,
            label: '年'
        }],
      // 考核细则表格显示
      tableShow:false,
      // 子栏目列表
      targetsunList:[],
      // 细则列表
      rulesList:[],
      // 细则拷贝
      rulesCopyList:[],
      // 考核指标列表
      indexList:[],
      // 考核纬度列表
      dutyclasslist:[],
      // 考核纬度请求值
      dutyClassFrom:{
        page: 1, //分页页码，数字类型
        pagesize: 100000,
        state: 1 //状态（查询用）
      },
      // 部门列表
      departmentList:[],
      // 公司列表
      companyList:[],
      editChildInfo:{},
      grouplist:[],
      props: {
        value: "id",
        label: "name",
        children: "children",
        emitPath:false
      },
      addChildInfo:{
        title:''
      },
      childInfo:{
        title:''
      },
      // 查询详情的数据
      editFrom:{},
      // 修改状态提交数据
      switchFrom:{},
      // 删除数据提交
      deleFrom:{},
      // 编辑时数据
      editAdd:{
        parentId:''
      },
      assessList:{},
      // 添加数据
      form:{
        type:1,
        group:'',
        parentid:'',
        target:'',
        targetsun:'',
        rationlist:[],
      },
      // 弹窗变量
      dialogFormVisible:false,
      // 修改弹窗
      editDialogFormVisible:false,
      total: 0,
      tableData:[],
      pos:'',
      pos1:'',
      pos2:'',
      spanArr:[],
      spanArr1:[],
      spanArr2:[],
      methodSpanArr:[],
      methodList:[],
      methodPos:'',
      methodShow:false,
      // 条件查询变量
      searchInfo: {
        group: "3",
      },
      // 条件查询变量
      abc:{
        aaa:"111",
        bbb:"222"
      },
      // 添加时验证规则
      rules: {
        // title: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      },
      editRules:{
        title: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      }
    }
  },
  created() {
    console.log(this.$store.state.user.token)
    if (this.$store.state.user.token=='') {
      this.$router.push('/login')
    }
    // 页面渲染时获取初始数据
    this.getDataList()
    this.getGrouplist()
    this.getDutyclasslist()
    this.getSystemadminlist()
  },
  // 监听数据
  watch: {
    methodList() {
      this.$nextTick(() => {
        this.methodSpanArr=[],
        this.methodPos='',
        //此时就可以获取到在created赋值后的dataList了
      this.getMethodSpanArr(this.methodList);
      });
    },
    tableData() {
      this.$nextTick(() => {
        this.spanArr=[],
        this.spanArr1=[],
        this.spanArr2=[],
        this.pos2='',
        this.pos='',
        this.pos1='',
        
        //此时就可以获取到在created赋值后的dataList了
        this.getSpanArr(this.tableData);
        this.getSpanArr1(this.tableData);
        this.getSpanArr2(this.tableData);
      });
    },
  },
  methods: {
    // 考核办法列表合并行
    methodSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        const _row = this.methodSpanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          // [0,0] 表示这一行不显示， [2,1]表示行的合并数
          rowspan: _row,
          colspan: _col
        };
      }
    },
    getMethodSpanArr(data) {
      
        // data就是我们从后台拿到的数据
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.methodSpanArr.push(1);
          this.methodPos = 0;
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].targetsun === data[i - 1].targetsun) {
            this.methodSpanArr[this.methodPos] += 1;
            this.methodSpanArr.push(0);
          } else {
            this.methodSpanArr.push(1);
            this.methodPos = i;
          }
        }
      }
    },
    // 查看考核办法
    async showMethod(row){
      const methodData={
        type: 1, //1：定性考核；2：定量考核
        group: row.group, //归属集团
        departmentid: row.parentid, //被考核部门
        dimension: row.dimension, //维度
        target: row.target, //考核指标
      }
      const res = await departmenttasklist(methodData)
      if (res.code==0) {
        this.methodList=res.data
        this.methodShow=true
      }
    },
    // 指标合并
    getSpanArr2(data) {
        // data就是我们从后台拿到的数据
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr2.push(1);
          this.pos2 = 0;
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].target === data[i - 1].target) {
            this.spanArr2[this.pos2] += 1;
            this.spanArr2.push(0);
          } else {
            this.spanArr2.push(1);
            this.pos2 = i;
          }
        }
      }
    },
    // 点击查看人员列表
    showUserList(row){
      this.showUser=true
      this.userlistary=row.userlistary
    },
    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;
          }
        }
      }
    },
    getSpanArr1(data) {
        // data就是我们从后台拿到的数据
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr1.push(1);
          this.pos1 = 0;
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].dimension === data[i - 1].dimension) {
            this.spanArr1[this.pos1] += 1;
            this.spanArr1.push(0);
          } else {
            this.spanArr1.push(1);
            this.pos1 = i;
          }
        }
      }
    },
    // 合并行
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          // [0,0] 表示这一行不显示， [2,1]表示行的合并数
          rowspan: _row,
          colspan: _col
        };
      }
      if (columnIndex === 1||columnIndex === 2) {
        const _row = this.spanArr1[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          // [0,0] 表示这一行不显示， [2,1]表示行的合并数
          rowspan: _row,
          colspan: _col
        };
      }
      if (columnIndex === 3||columnIndex === 4||columnIndex === 5||columnIndex === 6||columnIndex === 7||columnIndex === 8||columnIndex === 9) {
        const _row = this.spanArr2[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          // [0,0] 表示这一行不显示， [2,1]表示行的合并数
          rowspan: _row,
          colspan: _col
        };
      }
    },
    // 删除行
    deleteRow(row){
      this.rulesCopyList.splice(row.$index,1);
    },
    // 选中指标后获取子栏目
    async selectIndex(val){
      if (val!='') {
      const from={
        id:val
      }
      const res = await gettasktargetsun(from)
      this.targetsunList=res.data
      }
    },
    // 选中子栏目后获取对应的考核细则
    async selectTargetsun(val){
      if (val!='') {
      const from={
        type: 1, //1：定性考核；2：定量考核
        targetid: this.form.target.toString(), //指标
        targetsunid: val.toString() //子栏目

      }
      const res = await gettasktargetcontary(from)
      this.rulesList=JSON.parse(JSON.stringify(res.data))
      this.rulesCopyList=JSON.parse(JSON.stringify(res.data))
      this.tableShow=true
      }
    },
    // 选中部门后获取指定的指标列表
    async selectDepartment(val){
      if (val!='') {
      const indexFrom={
        type:2,
        group:this.form.group.toString(),
        parentid:val.map(String),
      }
      const res = await gettasktarget(indexFrom)
      this.indexList=res.data
      }
    },
    // 获取考核纬度列表
    async getDutyclasslist(){
       const res = await dutyclasslist(this.dutyClassFrom)
       this.dutyclasslist=res.data.list
    },
    // 选中的公司值
    async selectGroup(val){
      if (val!='') {
      const departmentFrom={
        id:val
      }
      const res = await departmentlist(departmentFrom)
      this.departmentList=res.data
      }
      
    },
    // 编辑获取选中组件值
    getEditCheckedfrom(data){
      this.editChildInfo=data
      this.editAdd.parentId=this.editChildInfo.outId
    },
    // 获取员工列表
    async getSystemadminlist(){
      const res = await getgroupuser()
      this.grouplistBackup=res.data.list
    },
    // 获取公司
    async getGrouplist(){
      const res = await getgroupdepartmap()
      this.companyList=res.data.list

    },
    // 添加获取选中组件值
    getCheckedfrom(data){
      this.addChildInfo=data
    },
    // 获取选中组件值
    getCheckedInfo(data){
      this.childInfo=data
    },
    //删除操作
    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;
    },
    // 编辑按钮
    async showEdit(row){
      this.editFrom.outid=row.outId
      const res = await getdutyinfo(this.editFrom)
      this.editAdd = res.data
      this.editAdd.parentId=res.data.parentIdStr
      this.editChildInfo.title=res.data.parentTitle
      this.editDialogFormVisible=true;

    },
    // 开关状态监听
   async changeVal(val,id){
       console.log(val)
      this.switchFrom.outid=id
      if (val==1) {
        this.switchFrom.state=1;
        const res = await eitedutystate(this.switchFrom)
                if (res.code === 0) {
                  this.$message({
                    type: 'success',
                    message: '修改状态成功',
                    showClose: true
                  })
                  this.getDataList()
                }
      } else {
        this.switchFrom.state=2;
        const res = await eitedutystate(this.switchFrom)
                if (res.code === 0) {
                  this.$message({
                    type: 'success',
                    message: '修改状态成功',
                    showClose: true
                  })
                  this.getDataList()
                }
      }
    },
    // 重置搜索条件
    onReset() {
      this.searchInfo = {
        assesstype:2,
        page: 1,
        pagesize: 10
      }
      this.childInfo={
        title:''
      }
    },
    // 条件搜索
    onSubmit() {
      this.page = 1
      this.pageSize = 10
      this.searchInfo.parentId=this.childInfo.outId
      this.getDataList()
    },
    // 日期时间戳转日期格式
    formatDate(nS) {     
      return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/,' ');     
    },
   
    // 提交按钮
    async enterDialog(){
      console.log("this.rulesCopyList")
      console.log(this.rulesCopyList)
      
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          const that=this
          this.indexList.forEach(function(item, index) {
            //item 就是当日按循环到的对象
            //index是循环的索引，从0开始
            that.form.rationlist.push({id:item.id.toString(),unit:item.unites,cycle:item.cycle,cycleattr:item.cycleattr,userlist:item.reportlist})
          })
          this.form.group=this.form.group.toString();
          this.form.parentid=this.form.parentid.map(String);
          const res = await addration(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 eitedutyinfo(this.editAdd)
          if (res.code === 0) {
                  this.$message({
                    type: 'success',
                    message: '编辑成功',
                    showClose: true
                  })
                }
          this.getDataList();
          this.editCloseDialog();
        }
      })
    },
    // 添加框关闭
    closeDialog() {
      this.initForm()
      this.dialogFormVisible = false
    },
    // 修改框关闭
    editCloseDialog() {
      this.editInitForm()
      this.editDialogFormVisible = false
    },
    // 添加重置表单
    initForm() {
      this.$refs.addForm.resetFields()
      this.form={
        type:2
      }
    },
    // 修改重置表单
    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 res = await departmenttasklist(this.searchInfo)
      this.tableData = res.data
    }
  }
}
</script>

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