<script setup>
import { ref } from 'vue'

/**权益权限ID
 * 科技-主观(20)-客观(37)
 * 消费-主观(21)-客观(38)
 * 医药-主观(22)-客观(39)
 * 智造-主观(19)-客观(36)
 * 策略(23)
 * 专家(29)
 * 固收(53)
 * 调研(54)
 * 路演服务(30)
 * 研选订阅(31)
 * 研选扣点包(52)
 */
const props = defineProps({
  authList: {
    type: Array,
  },
  /* 页面来源 */
  fromType: {
    type: String,
  },
  /* 表单位置 */
  form: {
    type: Number,
  },
})
const emit = defineEmits(['selectAuthHandle','selectAuthHandle2'])

 
const isMerge = ref(false)
const filterAuth = ref([])//权限表格
const indexArrEquity = ref([])//权益
const spanArrEquity = ref([])
const	posEquity = ref(0)
const authTableRef = ref(null)
function init() {
  /* 处理表格数据格式 */
  filterAuth.value = props.authList.map((item) => {
    return item.Items;
  });
  filterAuth.value = filterAuth.value.flat(Infinity);
  /* 选中的id数组 */
  //查看是否领取但无权限
  let bol_have = props.authList.some((item) => item.CheckList.length);
  let select = props.authList.map((item) => {
    return item.CheckList;
  });
  select = bol_have ? select.flat(Infinity) : [];
  /* 默认勾选中的表格项 */
  let check_Auth = filterAuth.value.filter((item) => {
    return select.includes(item.ChartPermissionId);
  });
  if (props.fromType === 'edit') {
    /* 展示表格选中的key */
    nextTick(() => {
      if (check_Auth.length > 0) {
        check_Auth.forEach((item) => {
          authTableRef.value.toggleRowSelection(item, true);
        });
      }
    });
  }else {
    /* 显示只有权限的数组 */
    filterAuth.value = [];
    check_Auth.map(item =>{
      // 排序 以防合并问题
      if(item.Status === '正式' || item.Status === '试用' || item.Status === '永续'||item.Status=='关闭'){
        if(item.PermissionType==1){
          //主观 找客观
          filterAuth.value.push(item)
          let ob = check_Auth.find(it => it.PermissionName == item.PermissionName && it.PermissionType!=1)
          ob && filterAuth.value.push(ob)
        }else if(item.PermissionType==0){
          filterAuth.value.push(item)
        }else{
          // 客观
          if(!filterAuth.value.find(t => t.ChartPermissionId == item.ChartPermissionId)){
            filterAuth.value.push(item)
          }
        }
      }
    })
    isMerge.value = filterAuth.value.some((item) => !item.IsMerge)
  }
  
  getRowSpan();
}
init()


/* 处理合并数组 */
function getRowSpan() {
  filterAuth.value.map((v, i, s) => {
    if (!v.PermissionTypeName) {
    indexArrEquity.value.push(i);
    }
  });
  for (var i = 0; i < filterAuth.value.length; i++) {
    let element = filterAuth.value[i]
    if (i === 0) {
      spanArrEquity.value.push(1);
      posEquity.value = 0;
    } else {
      // 判断当前元素与上一个元素是否相同（line为标记）
      if (element.PermissionName === filterAuth.value[i - 1].PermissionName) {
        if(element.IsMerge){
          // 主客观都有，需要合并
          spanArrEquity.value[posEquity.value] += 1;
          spanArrEquity.value.push(0);
        }else{
          // 主客观都有 不需要合并，说明是服务期限或者状态不一样
          spanArrEquity.value[posEquity] += 0.5;
          spanArrEquity.value.push(0.5);
        }
      } else {
        spanArrEquity.value.push(1);
        posEquity.value = i;
      }
    }
  }
}

/* 合并行规则 */
function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
  if(!isMerge.value){
    // 产品类型不显示
    const _row = spanArrEquity.value[rowIndex];
    if(_row == 0){
      return {
        rowspan: _row,
        colspan: 0,
      };
    }
  }else{
    //处理行的合并
    if (indexArrEquity.value.includes(rowIndex)) {
      if (columnIndex === 0) {
        return {
          rowspan: 1,
          colspan: 2,
        };
      } else if (columnIndex === 1) {
        return {
          rowspan: 0,
          colspan: 0,
        };
      }
    }
    // 权益行业主客观合并
    const _row = spanArrEquity.value[rowIndex];
    if(_row == 2){
      // 为2 是主客观都有，合并，这时合并行业和产品类型
      if(columnIndex === 0){
        return {
          rowspan: 1,
          colspan: 2,
        };
      }else if(columnIndex === 1){
        return {
          rowspan: 0,
          colspan: 0,
        };
      }
    }else if(_row == 0){
      // 为0 表示不需要这行，被合并掉了
      return {
        rowspan: _row,
        colspan: 0,
      };
    }else if(_row == 1.5){
      // 为1.5 是主客观都有，但不合并，这时合并行业
      if(columnIndex === 0){
        return {
          rowspan: 2,
          colspan: 1,
        };
      }
    }else if(_row == 0.5){
      if(columnIndex === 0){
        return {
          rowspan: 0,
          colspan: 0,
        };
      }
    }
  }
}

/* 勾选权限 */
function handleSelectionChange(val) {
  let selectArr = val.map((item, index) => {
    return item.ChartPermissionId;
  });
  props.form === 1
    ? emit('selectAuthHandle', selectArr)
    : emit('selectAuthHandle2', selectArr);
}

// 是否可选择
function canSelect(row) {
  return row.ChartPermissionId === 1 ? false : true;
}



</script>
<template>
  <el-table
		:data="filterAuth"
		:span-method="objectSpanMethod"
		@selection-change="handleSelectionChange"
		ref="authTableRef"
		border
		style="margin-top: 20px"
	>
		<el-table-column label="行业" align="center" >
			<template #default="scope">{{ scope.row.PermissionName }}</template>
		</el-table-column>
		<el-table-column label="产品类型" align="center" v-if="isMerge" >
			<template #default="scope">{{ scope.row.PermissionTypeName }}</template>
		</el-table-column>
		<el-table-column label="状态" align="center" >
			<template #default="scope">{{ scope.row.Status }}</template>
		</el-table-column>
		<el-table-column label="服务期限" align="center">
			<template #default="scope">{{
				scope.row.StartDate + '—' + scope.row.EndDate
			}}</template>
		</el-table-column>
		<el-table-column label="剩余天数" align="center">
			<template #default="scope">{{ scope.row.ExpireDay }}</template>
		</el-table-column>
            <el-table-column 
            v-if="fromType == 'edit'" 
            type="selection" 
            width="70"
            align="center"
            label-class-name="DisabledSelection"
            :selectable="canSelect">
            </el-table-column>
	</el-table>
</template>
<style scoped lang="scss">
/*表格表头全选*/
:deep(.DisabledSelection .cell::after){
	content:"全选";
	font-size: 12px;
	margin-left: 2px;
}
</style>