<template>
  <el-table border :data="tableData.list" style="width: 1000px" :span-method="objectSpanMethod">
    <el-table-column label="套餐类型" width="200" align="center">
      <template slot-scope="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 slot-scope="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 slot-scope="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 slot-scope="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 slot-scope="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>

<script>
export default {
  name: "QyServiceTable",
  props: {
    serviceData: [],
    hasSercive: [],
    canEdit: false,
  },
  data() {
    return {
      tableData: {
        radio: "",
        list: [],
        spanMergeCount:[]
      },
      checkList: [],
      // 有主客观的套餐列表
      selectAllArr:[],
      // 有主客观的套餐名称列表
      haveChildList:[],
      // 升级的套餐列表 医药、消费、科技、智造
      upgradeServes:[],
      templateData: [],
    };
  },
  watch: {
    //   初始化数据
    serviceData: {
      handler() {
        this.initTableData();
      },
      immediate: true,
    },

    // 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;
    //       }
    //     }
    //   });
    // },
  },

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

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

      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.grandFatherName === this.tableData.radio) {
          if (item.SelectName === tag && item.Title !== temtitle) {
            item.disable = true;
            item.selected = false;
          } else {
            item.disable = false;
          }
        }
      });
      // 升级套餐与基础套餐 禁用
      // console.log(this.upgradeServes,'this.upgradeServes',this.tableData.list);
      this.upgradeServes.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){
          this.tableData.list.map(it => {
            if(it.fatherName.indexOf(serveTitle)!=-1 && it.fatherName.indexOf('升级')==-1){
              it.disable=true
            }
          })
        }
      })
    },

    //显示报价单
    handleShow(e) {
      this.$emit("handleShowService", e);
    },

    //显示后面的文字
    showText(e) {
      let text=''
      if(e.fatherName == e.Title){
        // 没有主客观的
        text=e.Title
        let flag = this.checkList.indexOf(text);
        if (flag !== -1) {
          return true;
        } else {
          return false;
        }
      }else{
        // 有主客观的 合并了单元格，只会传主观的进来
        text = e.fatherName
        let arr = this.checkList.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 = this.tableData.list.find(item => item.fatherName ==text && item.Title == '客观').Value
              e.showTitle = this.tableData.list.find(item => item.fatherName ==text && item.Title == '客观').showTitle
            }
          }else{
            // 主客观都选 呈现的报价单为总共的那一份
            e.showValue = this.selectAllArr.find(item => item.name == text).value
            e.showTitle = this.selectAllArr.find(item => item.name == text).showTitle
          }
          return true;
        }else{
          return false;
        }
      }

    },
    //初始化表格数据
    initTableData() {
      // console.log(this.serviceData,this.hasSercive,'this.serviceData,this.hasSercive');
      let arr = [];
      this.tableData.spanMergeCount=[]
      this.serviceData.forEach((item, num) => {
        let temarr = []
        if (item.Children) {
          // 第二层
          this.tableData.spanMergeCount.push(item.Children.length)
          item.Children.map((e, index) => {
            if(e.Children){
              // 第三层
              this.tableData.spanMergeCount[num]=this.tableData.spanMergeCount[num]-1+e.Children.length
              // 有分主客观的项
              this.selectAllArr.push({
                name:e.Title,
                isIndeterminate:false,
                checkAll:false,
                ServiceTemplateId:e.ServiceTemplateId,
                value:e.Value,
                ChartPermissionId:e.ChartPermissionId,
                showTitle:e.Title
              })
              this.haveChildList.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');
      
      this.tableData.list = arr;
      // 升级套餐
      this.upgradeServes = this.tableData.list.filter(item => item.fatherName.indexOf('升级')!=-1)
      // console.log(this.selectAllArr,'this.selectAllArr',this.haveChildList);
      // 回显（合同详情或者是需要编辑的，如果是合同详情则canEdit=false 则全部禁用）
      // console.log(this.hasSercive,'this.hasSercive');
      // 目前 医药、消费、科技、智造 分为了主客观
      if (this.hasSercive&&this.hasSercive.length !== 0) {
        this.hasSercive.forEach((item) => {
          // 区分主客观的 主客观都有勾选时，只会返回一个基本套餐名称
          let basicItem = this.selectAllArr.find(it => it.ServiceTemplateId==item.ServiceTemplateId)
          if(basicItem){
            this.checkList.push(`${basicItem.name}（主观）`,`${basicItem.name}（客观）`)
            // e.fatherName == item.Title
            arr.filter(e => [item.ServiceTemplateId*2-1,item.ServiceTemplateId*2].includes(e.ServiceTemplateId))
            .map(it => {
              this.handleChange(this.checkList,it)
            })
            return 
          }

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

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

        // 如果是详情即 canEdit=false 则全部禁用
        if (!this.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;
        //   }
        // });
      }
    },

    //合并单元格
    objectSpanMethod({ row, column, rowIndex, columnIndex  }) {
      if(columnIndex === 0){
        if(rowIndex == 0){
          // 权益大套餐
          return [this.tableData.spanMergeCount[0],1]
        }else if(rowIndex == this.tableData.spanMergeCount[0]){
          // 行业套餐
          return [this.tableData.spanMergeCount[1],1]
        }else{
          return [0,0]
        }
      }
      // 45万 70万 医药、消费、科技、智造的升级
      if([5,6,23,24,25,26,12,27].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]
        }
      }
    },
  },
};
</script>

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