
<script setup>

import { ref,reactive,watch } from "vue";

const props = defineProps({
  serviceData: {
    type:Array,
    default:()=>[]
  },
  hasSercive: {
    type:Array,
    default:()=>[]
  },
  canEdit: false,
});
const emits=defineEmits(['handleShowService','serviceClose'])


const tableData=reactive({
  radio: "",
  list: [],
  spanMergeCount:[]
})
const checkList=ref([])
// 有主客观的套餐列表
const selectAllArr=ref([])
// 有主客观的套餐名称列表
const haveChildList=ref([])
// 升级的套餐列表 医药、消费、科技、智造
const upgradeServes=ref([])
const templateData=ref([])

  // watch: {
    // checkList(nval, oval) {
    //   let tag = "";
    //   let temtitle = "";

    //   this.tableData.list.forEach((item) => {
    //     if (item.SelectType === "radio") {
    //       let flag = nval.indexOf(item.Title);
    //       if (flag !== -1) {
    //         tag = item.SelectName;
    //         temtitle = item.Title;
    //       }
    //     }
    //   });

    //   this.tableData.list.forEach((item) => {
    //     if (item.fatherName === this.tableData.radio) {
    //       if (item.SelectName === tag && item.Title !== temtitle) {
    //         item.disable = true;
    //         item.selected = false;
    //       } else {
    //         item.disable = false;
    //       }
    //     }
    //   });
    // },
  // }

//切换radio
const handleRadioChange=(e)=>{
  checkList.value = [];
  for (const it of selectAllArr.value) {
    it.checkAll = false
    it.isIndeterminate = false
  }
  tableData.list.forEach((item) => {
    if (item.grandFatherName !== e) {
      item.disable = true;
      item.selected = false;
    } else {
      item.disable = false;
    }
  });
}
// 全选
const handleCheckAllChange=(row)=>{
  // console.log(row,'row');
  // console.log(checkList.value,'this.checkList');
  let arr = checkList.value.filter(item => item.indexOf(row.fatherName) != -1)
  let rowFather = selectAllArr.value.find((item) => item.name == row.fatherName)
  rowFather.isIndeterminate = false
  if(arr.length<2){
    rowFather.checkAll=true
    checkList.value = [...new Set([...checkList.value,...[`${row.fatherName}（主观）`,`${row.fatherName}（客观）`]])]
  }else{
    checkList.value = checkList.value.filter(item => item.indexOf(row.fatherName) == -1)
    rowFather.checkAll=false
  }
  handleChange(checkList.value,row)
}

//点击选项
const handleChange=(nval,row)=>{
  let rowFather = selectAllArr.value.find((item) => item.name == row.fatherName)
  if(rowFather){
    let arr = nval.filter(item => item.indexOf(row.fatherName) !=-1)
    rowFather.checkAll=arr.length==2
    rowFather.isIndeterminate=arr.length==1
  }
  //一个都没选
  if(!nval.length){
    tableData.radio=""
    tableData.list.forEach(item=>{
      item.disable=false
      item.selected=false
    })
    return
  }

  // 当this.tableData.radio 为空时 
  if(!tableData.radio){
    tableData.list.forEach(item=>{
      if(item.Title===nval[0] || nval[0].indexOf(item.Title)!=-1){
        tableData.radio=item.grandFatherName
        tableData.list.forEach(item2=>{
          if(item2.grandFatherName!==item.grandFatherName){
            item2.selected=false 
            item2.disable=true
          }
        })
      }
    })
  }

  let tag = "";
  let temtitle = "";
  
  tableData.list.forEach((item) => {
    if (item.SelectType === "radio") {
      let flag = nval.indexOf(item.Title);
      if (flag !== -1) {
        tag = item.SelectName;
        temtitle = item.Title;
      }
    }
  });
  tableData.list.forEach((item) => {
    if (item.grandFatherName === tableData.radio) {
      if (item.SelectName === tag && item.Title !== temtitle) {
        item.disable = true;
        item.selected = false;
      } else {
        item.disable = false;
      }
    }
  });
  // 升级套餐与基础套餐 禁用
  // console.log(upgradeServes.value,'this.upgradeServes',tableData.list);
  upgradeServes.value.map(item =>{
    // 取出原始套餐标题
    let serveTitle = item.fatherName.split("（")[0]
    let hasBasicServe=nval.some(item => item.indexOf(serveTitle)!=-1 && item.indexOf('升级')==-1)
    let hasUpgradeServe=nval.some(item => item.indexOf(serveTitle)!=-1 && item.indexOf('升级')!=-1)
    if(hasBasicServe){
      item.disable=true
    }else if(hasUpgradeServe){
      tableData.list.map(it => {
        if(it.fatherName.indexOf(serveTitle)!=-1 && it.fatherName.indexOf('升级')==-1){
          it.disable=true
        }
      })
    }
  })
}

//显示报价单
const handleShow=(e)=>{
  emits("handleShowService", e);
}

//显示后面的文字
const showText=(e)=>{
  let text=''
  if(e.fatherName == e.Title){
    // 没有主客观的
    text=e.Title
    let flag = checkList.value.indexOf(text);
    if (flag !== -1) {
      return true;
    } else {
      return false;
    }
  }else{
    // 有主客观的 合并了单元格，只会传主观的进来
    text = e.fatherName
    let arr = checkList.value.filter(item => item.indexOf(text)!=-1 && item.indexOf("升级")==-1)
    if(arr.length>0){
      // 主观或者客观
      if(arr.length==1){
        if(arr.find(item => item.indexOf("主观")!=-1)){
          // 主观
          e.showValue = e.Value
          e.showTitle = `${text}（${e.Title}）`
        }else{
          //客观
          e.showValue = tableData.list.find(item => item.fatherName ==text && item.Title == '客观').Value
          e.showTitle = tableData.list.find(item => item.fatherName ==text && item.Title == '客观').showTitle
        }
      }else{
        // 主客观都选 呈现的报价单为总共的那一份
        e.showValue = selectAllArr.value.find(item => item.name == text).value
        e.showTitle = selectAllArr.value.find(item => item.name == text).showTitle
      }
      return true;
    }else{
      return false;
    }
  }

}
//初始化表格数据
const initTableData=()=>{
  // console.log(props.serviceData,props.hasSercive,'this.serviceData,this.hasSercive');
  let arr = [];
  tableData.spanMergeCount=[]
  props.serviceData.forEach((item, num) => {
    let temarr = []
    if (item.Children) {
      // 第二层
      tableData.spanMergeCount.push(item.Children.length)
      item.Children.map((e, index) => {
        if(e.Children){
          // 第三层
          tableData.spanMergeCount[num]=tableData.spanMergeCount[num]-1+e.Children.length
          // 有分主客观的项
          selectAllArr.value.push({
            name:e.Title,
            isIndeterminate:false,
            checkAll:false,
            ServiceTemplateId:e.ServiceTemplateId,
            value:e.Value,
            ChartPermissionId:e.ChartPermissionId,
            showTitle:e.Title
          })
          haveChildList.value.push(e.Title)
          e.Children.map((it,i)=>{
            temarr.push({
              ...it,
              fatherName: e.Title,
              grandFatherName:item.Title,
              text2: "下载报价单",
              text1: e.Detail ? "选择品种" : "查看报价单",
              selected: false,
              disable: false,
              // 预览时的值 选择主观、客观 和主客观都选时展示的不一样
              // 用于预览和展示报价单
              showValue:e.Value,
              showTitle:`${e.Title}(${it.Title})`
            });
          })
        }else{
          temarr.push({
            ...e,
            fatherName: e.Title,
            grandFatherName:item.Title,
            text2: "下载报价单",
            text1: e.Detail ? "选择品种" : "查看报价单",
            selected: false,
            disable: false,
            showValue:e.Value,
            showTitle:e.Title
          });
        }
      });
      arr = [...arr, ...temarr];
    } else {
      arr.push({ 
        ...item, 
        selected: false, 
        disable: false, 
        fatherName: item.Title, 
        grandFatherName: item.Title, 
        text2: "下载报价单", 
        text1: item.Detail ? "选择品种" : "查看报价单" });
    }
  });
  // console.log(arr,'arr');
  
  tableData.list = arr;
  // 升级套餐
  upgradeServes.value = tableData.list.filter(item => item.fatherName.indexOf('升级')!=-1)
  // console.log(selectAllArr.value,'this.selectAllArr',haveChildList.value);
  // 回显（合同详情或者是需要编辑的，如果是合同详情则canEdit=false 则全部禁用）
  // console.log(props.hasSercive,'this.hasSercive');
  // 目前 医药、消费、科技、智造 分为了主客观
  if (props.hasSercive&&props.hasSercive.length !== 0) {
    props.hasSercive.forEach((item) => {
      // 区分主客观的 主客观都有勾选时，只会返回一个基本套餐名称
      let basicItem = selectAllArr.value.find(it => it.ServiceTemplateId==item.ServiceTemplateId)
      if(basicItem){
        checkList.value.push(`${basicItem.name}（主观）`,`${basicItem.name}（客观）`)
        // e.fatherName == item.Title
        arr.filter(e => [item.ServiceTemplateId*2-1,item.ServiceTemplateId*2].includes(e.ServiceTemplateId))
        .map(it => {
          handleChange(checkList.value,it)
        })
        return 
      }

      let serviceRow = arr.find(e => e.ServiceTemplateId==item.ServiceTemplateId)
      if(!serviceRow) return
      if(item.Title.indexOf("主观")!==-1 || item.Title.indexOf("客观")!==-1){
        // 兼容之前合同数据的回显
        checkList.value.push(`${serviceRow.fatherName}（${serviceRow.Title}）`)
      }else{
        checkList.value.push(item.Title)
      }
      handleChange(checkList.value,serviceRow)
    });

    arr.forEach((item) => {
      if (item.grandFatherName !== tableData.radio) {
        item.disable = true;
      }
    });

    // 如果是详情即 canEdit=false 则全部禁用
    if (!props.canEdit) {
      arr.forEach((item) => {
        item.disable = true;
      });
    }
    
    
  } else {
    //不需要回显则是新添合同 则初始化将其全部禁用
    // arr.forEach((item) => {
    //   item.disable = true;
    // });
    //不需要回显则是新添合同 则初始化选择第一个
    // arr.forEach((item, index) => {
    //   if (index === 0) {
    //     item.selected = true;
    //     item.disable = false;
    //     this.checkList.push(item.Title);
    //     this.tableData.radio = item.fatherName;
    //   }
    // });
  }
}

//合并单元格
const objectSpanMethod=({ row, column, rowIndex, columnIndex  })=>{
  if(columnIndex === 0){
    if(rowIndex == 0){
      // 权益大套餐
      return [tableData.spanMergeCount[0],1]
    }else if(rowIndex == tableData.spanMergeCount[0]){
      // 行业套餐
      return [tableData.spanMergeCount[1],1]
    }else{
      return [0,0]
    }
  }
  // 45万 70万 医药、消费、科技、智造的升级
  if([5,6,23,24,25,26,12].includes(row.ServiceTemplateId)){
    if(columnIndex==1){
      return [1,2]
    }else if(columnIndex==2){
      return [0,0]
    }
  }
  if([1,3,4].includes(columnIndex)){
    if([15,17,19,21].includes(row.ServiceTemplateId)){
      // 医药、消费、科技、智造的主观
      return [2,1]
    }else if([16,18,20,22].includes(row.ServiceTemplateId)){
      // 医药、消费、科技、智造的客观
      return [0,0]
    }
  }
}

defineExpose({
  selectAllArr,
  checkList,
  tableData
})

//   初始化数据
watch(()=>props.serviceData,()=>{
  initTableData();
},
{immediate:true})

</script>

<template>
  <el-table border :data="tableData.list" style="width: 1000px" :span-method="objectSpanMethod">
    <el-table-column label="套餐类型" width="200" align="center">
      <template #default="scope">
        <el-radio :disabled="!canEdit" v-model="tableData.radio" :label="scope.row.grandFatherName" @change="handleRadioChange" style="width: 100%; text-align: left; padding-left: 50px">{{
          scope.row.grandFatherName
        }}</el-radio>
      </template>
    </el-table-column>

    <el-table-column>
      <template #default="scope">
        <el-checkbox :disabled="scope.row.disable" style="width: 100%; text-align: left; padding-left: 50px" 
        v-model="selectAllArr.find(item => item.name == scope.row.fatherName).checkAll" 
        :indeterminate="selectAllArr.find(item => item.name == scope.row.fatherName).isIndeterminate"
          v-if="haveChildList.includes(scope.row.fatherName)"  @change="handleCheckAllChange(scope.row)">
          {{scope.row.fatherName}}
        </el-checkbox>
        <el-checkbox-group v-model="checkList" @change="handleChange($event,scope.row)"  v-else>
          <el-checkbox :label="scope.row.fatherName" :disabled="scope.row.disable" style="width: 100%; text-align: left; padding-left: 50px"></el-checkbox>
        </el-checkbox-group>
      </template>
    </el-table-column>
    <el-table-column>
      <template #default="scope">
        <el-checkbox-group v-model="checkList" @change="handleChange($event,scope.row)">
          <el-checkbox :label="scope.row.fatherName+'（'+scope.row.Title+'）'" 
           :disabled="scope.row.disable" style="width: 100%; text-align: left; padding-left: 50px">
            {{scope.row.Title}}
          </el-checkbox>
        </el-checkbox-group>
      </template>
    </el-table-column>
    <el-table-column width="200">
      <template #default="scope">
        <span style="cursor: pointer; color: #409eff; padding-left: 50px" v-if="showText(scope.row)" @click="handleShow(scope.row)">{{ scope.row.text1 }}</span>
      </template>
    </el-table-column>
    <el-table-column width="200" align="center">
      <template #default="scope">
        <a :href="scope.row.showValue + '?response-content-type=application/octet-stream'" download style="cursor: pointer; color: #409eff" v-if="showText(scope.row)">{{
          scope.row.text2
        }}</a>
      </template>
    </el-table-column>
  </el-table>
</template>

<style lang="scss" scoped></style>
