<template>
  <div style="padding: 0 20px;">
    <lx-header icon="md-apps" style="margin-bottom: 10px; border: 0px; margin-top: 15px" text="绩效指标">
      <div slot="content"></div>
      <slot>
        <div class="selects">

          <div>
            <span style="padding: 0 6px;word-break: keep-all;">
              关键字
            </span>
            <Input v-model="select.keyword" placeholder="请输入关键字" style="width: 180px"></Input>
          </div>

          <Button style="margin-left: 10px" type="primary"
                  @click="resetSelect(select)">重置
          </Button>
          <Button style="margin-left: 10px" type="primary" @click="select.page = 1,total = 0,getList()">查询</Button>
          <Button style="margin-left: 10px" type="primary" @click="$refs['addPoint'].type = 'add',$refs['addPoint'].show()">新增</Button>
        </div>
      </slot>
    </lx-header>

    <xy-table :list="list"
              ref="table"
              :table-item="table"
              :object-span-method="spanMethod"
              @editor="row => {
                $refs['addPoint'].id = row.id;
                $refs['addPoint'].type = 'editor';
                $refs['addPoint'].show();
              }"
              @delete="destroy">
      <template #btns> </template>
    </xy-table>

    <div style="display: flex;justify-content: flex-end;">
      <Page :total="total"
            @on-change="e => {
              select.page = e;
              getList();
            }"
            show-elevator
            show-sizer
            @on-page-size-change="e => {
              select.page_size = e;
              select.page = 1;
              getList();
            }" />
    </div>

    <addPoint ref="addPoint" :target_types="types" :symbol_ids="symbols" :unit_ids="units" @refresh="getList"></addPoint>
  </div>
</template>

<script>
import { index,destroy } from "@/api/achievements/points";
import { index as typesIndex } from "@/api/achievements/types";
import { getparameter } from "@/api/system/dictionary"
import { resetSelect } from "@/utils/index"

import addPoint from '@/views/achievements/components/addPoint.vue'
export default {
  components:{
    addPoint
  },
  data() {
    return {
      select:{
        keyword: "",
        page: 1,
        page_size: 10
      },
      total: 0,
      spanArr: [],
      spanArr1: [],
      pos1: 0,
      pos: 0,
      table: [

        {
          label: "一级指标名称",
          prop: "target_type_detail.name",
          width: 200
        },
        {
          label: "二级指标名称",
          prop: "target_type2_detail.name",
          width: 200
        },
        {
          label: "三级指标名称",
          prop: "name",
          width: 200
        },
        {
          label: "计算符号",
          prop: "symbol_detail.value",
          width: 120
        },
        {
          label: "半年（程）指标值",
          prop: "half_target",
          width: 180
        },
        {
          label: "全年（程）指标值",
          prop: "year_target",
          width: 180
        },
        {
          label: "单位",
          prop: "unit_detail.value",
          width: 120
        },
        {
          label: "分值",
          prop: "score",
          width: 100
        },
        {
          label: "年份",
          prop: "year",
          width: 200
        },
        {
          label: "操作",
          align: "left",
          width: 160,
          customFn: row => {
            return (
              <div>
                <Button ghost={true}
                        type="error"
                        size="small"
                        on={{
                          ['click']: _ => {
                            this.$confirm('确定删除该指标吗？').then(() => this.destroy(row))
                          }
                        }}>删除</Button>
                <Button ghost={true}
                        style="margin-left: 6px;"
                        type="primary"
                        size="small"
                        on={{
                          ['click']:_ => {
                            this.$refs['addPoint'].id = row.id;
                            this.$refs['addPoint'].type = 'editor';
                            this.$refs['addPoint'].show();
                          }
                        }}>编辑</Button>
              </div>
            )
          }
        }
      ],
      list: [],

      types: [],
      symbols: [],
      units: [],
    }
  },
  methods: {
    resetSelect,
    async getTypes() {
      const res = await typesIndex({ show_tree:1 })
      this.types = res || []
    },
    async getSymbols() {
      const res = await getparameter( { number: "symbol" })
      this.symbols = res.detail
    },
    async getUnits() {
      const res = await getparameter({ number: "unit" })
      this.units = res.detail
    },

    destroy(row){
      destroy({ id: row.id }).then(res => {
        this.$message({
          type: "success",
          message: "删除成功"
        })
        this.getList()
      })
    },

    async getList() {
      this.list = [];
      this.pos = this.pos1 = 0;
      this.spanArr = [];
      this.spanArr1 = [];
      const res = await index(this.select)
      this.total = res.total
      let temp = res.data

      for(let i in temp){
        if(i === 0){
          this.spanArr.push(1);
          this.pos = 0;
          this.spanArr1.push(1);
          this.pos1 = 0;
        }else{
          if(temp[i]?.target_type_detail?.name === temp[i-1]?.target_type_detail?.name){
            this.spanArr[this.pos] += 1;
            this.spanArr.push(0)
          }else{
            this.spanArr.push(1);
            this.pos = i;
          }

          if(temp[i]?.target_type2_detail?.name === temp[i-1]?.target_type2_detail?.name){
            this.spanArr1[this.pos1] += 1;
            this.spanArr1.push(0)
          }else{
            this.spanArr1.push(1);
            this.pos1 = i;
          }
        }
      }
      this.list = temp;
      // let arr = [];
      // let getProp = (data,name) => {
      //   if(!name || !data){
      //     return false
      //   }
      //   let curProp = name.split('.')
      //   if(curProp.length === 1){
      //     return data[name]
      //   }else{
      //     let res = data
      //     for(let i = 0;i < curProp.length;i++){
      //       res = res[curProp[i]]
      //     }
      //     return res
      //   }
      // }
      // let x = 0;
      // let y = 0;
      // for(let i = 0;i < this.list.length;i++){
      //   arr[i] = []
      //   for(let j = 0;j < this.table.length;j++){
      //     if(!arr[i][j]){
      //       arr[i][j] = {
      //         rowspan: 1,
      //         colspan: 1
      //       }
      //     }
      //     if(getProp(this.list[i],this.table[j].prop) === getProp(this.list[i+1],this.table[j].prop)){
      //       arr[x][y].rowspan++
      //       arr[x][y+1] = {
      //         rowspan: 0,
      //         colspan: 0
      //       }
      //     }else{
      //       x = i
      //       y = j
      //     }
      //   }
      // }
      // this.spanArr = arr
      // console.log(arr)

      this.$nextTick(() => {
        setTimeout(() => this.$refs['table'].doLayout(),500)
      })
    },

    spanMethod({ row, column, rowIndex, columnIndex }) {
      if (column.property === "target_type_detail.name") {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        }
      }
      if (column.property === "target_type2_detail.name") {
        const _row = this.spanArr1[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    }
  },
  computed: {},
  created() {
    this.getTypes();
    this.getSymbols();
    this.getUnits();
    this.getList();
  }
}
</script>

<style scoped lang="scss">
.selects{
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
</style>
