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

const props = defineProps({
  	authList: {
			type: Array,
		},
		/* 页面来源 */
		fromType: {
			type: String,
		},
		/* 表单位置 */
		form: {
			type: Number,
		},
})
const emit = defineEmits(['selectAuthHandle','selectAuthHandle2'])



const authTableRef = ref(null)
const filterAuth = ref([])
const rowSpanArr = ref([])
const position = ref(0)
const isRaiMerge = ref(0)// 权益的主客观是否合并 0不管 1合并 2拆分
/* 处理合并数组 */
function getRowSpan() {
  rowSpanArr.value = [];
  /* [2,0,1] */
  filterAuth.value.forEach((item, index) => {
    if (index === 0) {
      rowSpanArr.value.push(1);
      position.value = 0;
    } else {
      if (
        filterAuth.value[index].ClassifyName ===
        filterAuth.value[index - 1].ClassifyName
      ) {
        rowSpanArr.value[position.value] += 1; //项目名称相同，合并到同一个数组中
        rowSpanArr.value.push(0);
        filterAuth.value[index].ClassifyName = filterAuth.value[
          index - 1
        ].ClassifyName;
      } else {
        rowSpanArr.value.push(1);
        position.value = index;
      }
    }
  });
}


/* 合并行规则 */
function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
  if (columnIndex === 0) {
    const _row = rowSpanArr.value[rowIndex];
    return {
      rowspan: _row,
      colspan: 1,
    };
  }
}

/* 勾选权限 */
function handleSelectionChange(val) {
  let selectArr=[]
  if(isRaiMerge.value==1){
    // 由于合并时客观的那一行隐藏掉了，复选框只会影响主观的选择状态 
    // 但是选择的时候需要主客观的ID都传
    let completeAuth = props.authList.map((item) => {
      return item.Items;
    }).flat(Infinity);
    val.map(item=>{
      // 主观有勾选
      if(item.PermissionType==1){
        // 主观有勾选代表是全选
        let idArr = completeAuth.filter(it => {
          return it.PermissionName == item.PermissionName
        })
        idArr.map(it => {
          selectArr.push(it.ChartPermissionId)
        })
      }else if(item.PermissionType==0){
        // 没有区分主客观的行业
        selectArr.push(item.ChartPermissionId)
      }
    })
  }else{
    selectArr = val.map((item, index) => {
      return item.ChartPermissionId;
    });
  }
  // console.log(selectArr);
  props.form === 1
    ? emit('selectAuthHandle', selectArr)
    : emit('selectAuthHandle2', selectArr);
}

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


function init() {
  	isRaiMerge.value = props.authList[0].RaiMerge
		/* 处理表格数据格式 */
		let tempArr=props.authList.map((item) => {
			return item.Items;
		});
		tempArr = tempArr.flat(Infinity);
		// console.log(tempArr);
		if(!isRaiMerge.value){
			filterAuth.value = tempArr
		}else if(isRaiMerge.value==1){
			// 主客观合并 只取主观的
			filterAuth.value = tempArr.filter(it => {
				return it.PermissionType==1 || it.PermissionType==0
			})
		}else if(isRaiMerge.value==2){
			// 主客观拆分 只取主观的
			tempArr.map(item =>{
				// 排下序 
				if(item.PermissionType==1){
					//主观 找客观
					filterAuth.value.push(item)
					let ob = tempArr.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)
					}
				}
			})
		}
		/* 选中的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);
		});
		console.log(check_Auth,'check_Auth');
		if (props.fromType === 'edit') {
			/* 展示表格选中的key */
			nextTick(() => {
				if (check_Auth.length > 0) {
					check_Auth.forEach((item) => {
						authTableRef.value.toggleRowSelection(item, true);
					});
				}
			});
		}else {
			/* 显示只有权限的数组 */
			filterAuth.value = [];
			filterAuth.value = check_Auth.filter((item) => {
				return item.Status === '正式' || item.Status === '试用' || item.Status === '永续'||item.Status=='关闭'
			});
		}
		
		getRowSpan();
}
init()
</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.ClassifyName }}</template>
		</el-table-column>
		<el-table-column label="品种" align="center" >
			<template #default="scope">
				<!-- 权益在拆分的情况下区分主客观 -->
				{{ isRaiMerge ==2&&scope.row.PermissionTypeName?`${scope.row.PermissionName}（${scope.row.PermissionTypeName}）`:scope.row.PermissionName }}
			</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">
/*表格表头全选*/
.DisabledSelection .cell::after{
	content:"全选";
	font-size: 12px;
	margin-left: 2px;
}
</style>