<template>
  <div style="padding: 0 20px">
    <div ref="lxHeader">
      <lx-header icon="md-apps" text="履责管理" style="margin-bottom: 10px; border: 0px; margin-top: 15px">
        <slot>
          <div>
            <div style="margin-bottom:15px;margin-top:15px;">
              <span style="margin-right:15px;display: inline-block;width:45px;vertical-align: top;">年度: </span>
              <el-radio-group style="width:90%" v-model="select.year" @change="changeYear">
                <el-radio style="margin-right:5px;margin-bottom:5px;margin-left:0" v-for="item in yearList" border
                  :label="item">{{item}}</el-radio>
              </el-radio-group>
            </div>
            <div style="margin-bottom:15px;margin-top:15px;">
              <span style="margin-right:15px;display: inline-block;width:45px;vertical-align: top;">模块: </span>
              <el-radio-group style="width:90%" @change="changeCategoryType" v-model="select.menu">
                <el-radio style="margin-right:5px;margin-bottom:5px;margin-left:0" v-for="item in menuList"
                  border :label="item.value">{{item.value}}</el-radio>
              </el-radio-group>
            </div>
            <div>
              <Button type="primary" style="margin-left: 10px;"
                @click="editorCategory('','add')">新增{{select.year}}{{select.menu}}履责填报</Button>

            </div>

            <!-- <Button type="primary" @click="getList">查询</Button>
            <Button type="primary" style="margin-left: 10px;" @click="editorCategory('','add')">添加</Button>
            <Button type="primary" style='margin-left: 10px;'
              @click="chooseEditorCategory()">编辑</Button> -->
          </div>
        </slot>
      </lx-header>
    </div>

    <!-- @cell-click="cellClicks" -->
    <xy-table :list="list" :show-summary="true" :summary-method="getSummaries" :showIndex="false" :table-item="table" :isPage="false" :defaultExpandAll="false">
      <template v-slot:btns>
        <el-table-column align='left' label="操作" width="200" header-align="center">
          <template slot-scope="scope">
              <Button type="primary" style='margin-right:5px;margin-bottom:5px;' size="small"
                @click="editorCategory(scope.row.id,'child')">子项目</Button>
              <Button type="primary" style='margin-right:5px;margin-bottom:5px;' size="small"
                @click="editorCategory(scope.row.id,'editor')">编辑</Button>

            <Poptip transfer confirm title="确认要删除吗？" @on-ok="deleteList(scope.row.id)">
               <Button type="primary" style="margin-right:5px;margin-bottom:5px;" size="small" >删除</Button>
            </Poptip>
            <Button v-if="!scope.row.children" type="primary" style='margin-right:5px;margin-bottom:5px;' size="small"
                @click="showCategory(scope.row.id)">填报</Button>
            <Button v-if="!scope.row.children" type="primary" style='margin-right:5px;margin-bottom:5px;' size="small"
              @click="showInfo(scope.row.id)">查看</Button>
           <!-- <div>
              <Button type="primary" style='margin-right:5px;margin-bottom:5px;' size="small"
                @click="editorCategory(scope.row.id,'editor')">编辑</Button>
            </div> -->
            <!-- <Button type="primary" style='margin-right:5px;margin-bottom:5px;' size="small"
              @click="editorUnit('add',scope.row.id)">发起任务</Button> -->
          </template>
        </el-table-column>
      </template>
    </xy-table>
    <create ref="create" @refresh="getList"></create>
    <showCategory ref="showCategory"></showCategory>
    <formshow ref="show"></formshow>
  </div>
</template>

<script>
  import {
    index,
    show,
    destroy
  } from '@/api/task/newplan.js'
  import create from '../objective/components/create.vue'
  import showCategory from '../objective/components/showCategory.vue'
  import formshow from "../objective/components/formshow.vue";
  import {
    getparameteritem
  } from "@/api/system/dictionary.js";
  export default {
    components: {
      create,
      showCategory,
      formshow
    },
    data() {
      return {
        yearList: [],
        menuList: [],
        levelList: [],
        select: {
          keyword: '',
          table_name: 'new_scores',
          page: 1,
          page_size: 99999,
          year:'',
          menu:'',
          pname:'',
          sort_name: 'created_at',
          sort_type: 'ASC'
        },

        table: [
          // {
          //   label: "名称",
          //   prop: 'name',
          // },
          // {
          //   label: "年份",
          //   prop: 'year',
          // },
          {
            label: "评价项目",
            prop: 'menu',
            align:'left',
            formatter:(cell,data,value,index)=>{
              if(cell.total_score){
                return `${value}(${cell.total_score}分)`
              }else{
                return value
              }
              // return value?(value.length===0?'--':value.length):'--'
            }
          },
          // {
          //   label: "总分",
          //   prop: 'total_score',
          //   width:80,
          // },
          // {
          //   label: "二级评价项目",
          //   prop: 'level',
          // }, {
          //   label: "三级级评价项目",
          //   prop: 'third_level'
          // },
          {
            label: "标准分值",
            prop: 'normal_score',
                        width:80,

          }, {
            label: "评价方法及评分标准",
            prop: 'methods',
            align:'left'
          },
          {
            label: "评价描述",
            prop: 'content',
            align:'left'
          },
          {
            label: "实际得分",
            prop: 'true_score',
                        width:80,
          }
        ],
        list: [],
      }
    },
    created() {
      // this.getUserId()
      this.yearList = this.getYearList()
      // this.getList()
      this.getCategory()

    },
    methods: {

      async getList() {
        const res = await index({
          ...this.select,
          filter:[{
            'key':'pname',
            'op':'eq',
            'value':this.select.menu
          },{
            'key':'year',
            'op':'eq',
            'value':this.select.year
          }]


        })
        let data = this.buildTree(res.data,0)
        this.list = data
        console.log("list",this.list)
      },
      buildTree(data, pid) {
        const result = [];

        data.forEach(item => {
          if (item.pid === pid) {
            const children = this.buildTree(data, item.id);
            if (children.length > 0) {
              item.children = children;
            }
            result.push(item);
          }
        });

        return result;
      },
      getYearList() {
        const currentYear = new Date().getFullYear() ;
        this.select.year = new Date().getFullYear()
        // 创建一个包含当前年份及前5年的数组
        const yearsArray = [];
        for (let i = 0; i <= 3; i++) {
          yearsArray.push(currentYear - i);
        }
        return yearsArray
      },

      changeYear(e) {
        this.select.year = e
      },

      async getCategory() {
        const res = await getparameteritem('main_level')
        this.menuList = res.detail
        this.select.menu = this.menuList[0].value
        this.getList()

      },
      changeCategoryType(e) {
        this.menuList.map(item => {
          if (e === item.value) {
            this.select.menu = item.value
            this.levelList = []
            this.levelList = item.remark.split("、")
            this.getList()
          }
        })
      },
      editorCategory(id, type) {
        this.$refs['create'].setName(`${this.select.year}年安全生产标准化自查打分表`)
        this.$refs['create'].setYear(this.select.year)
        if(type==='child'){
          console.log(type,id)
          this.$refs['create'].setPid(id)
        }
        // this.$refs['create'].menuList = this.menuList
        if(this.select.menu){
          this.$refs['create'].setMenu(this.select.menu)
        }
        if(type==='editor'){
          this.$refs['create'].id = id
        }
        this.$refs['create'].type = type
        this.$refs['create'].isShow = true
      },
      showCategory(id) {
        this.$refs['showCategory'].id = id
        this.$refs['showCategory'].isShow = true
      },
      showInfo(id){
        this.$refs['show'].setId(id)
        this.$refs['show'].show()
      },
      deleteList(id) {
        var that = this;
        if (id) {
          destroy({
            id:id,
            table_name:this.select.table_name
          }).then(response => {
            this.$Message.success('操作成功');
            that.getList();
          }).catch(error => {
            console.log(error)
            reject(error)
          })
        }
      },
      getSum (tree, idx, sums, index) {
            if (tree && tree.length > 0) {
              tree.map(item => {
                this.getSum(item.children, idx, sums, index)
                sums[index] += Number(item[idx])
              })
            }
          },
          getSummaries (param) {
            const { columns, data } = param
            const sums = []
            columns.forEach((column, index) => {
              if (index === 0) {
                sums[index] = '总分'
                return
              }else if(index===3){
                sums[index] = '得分小计'
                return
              }else if(index===1||index===4){
                sums[index] = 0
                this.getSum(data, column.property, sums, index)
              }else{
                sums[index] = ''
                return
              }
              // 初始化合计行
              // 递归求和

              // 如果求和得到的结果是非数字,则显示--
              if (isNaN(sums[index])) {
                sums[index] = '--'
              }
            })
            return sums
          }

    },
    watch: {}
  }
</script>

<style scoped>
  /deep/ .el-icon-circle-close {
    color: #fff
  }
  /deep/ .el-table .cell.el-tooltip{
    white-space: normal!important;
  }
  .expandrow {
    display: flex;
    font-size: 16px;
    padding-left: 50px;
    padding-bottom: 9px;
    flex-wrap: wrap;
  }

  .expandrow p {
    margin-right: 20px;
  }

  .expandrow p span:first-child {
    font-weight: 300;

  }

  /*  /deep/ .el-table__body tr.el-table__row--striped td {
    background-color: #C0C4CC!important;
  } */
</style>
