<template>
<div class='content'>
  <div class="filterLineBox" v-for="(item,index) in answerList" :key="index">
    <!-- 问题框 -->
    <a-select
      :getPopupContainer="triggerNode=>triggerNode.parentNode"
      class="lineSelect maxSelect custom-select" v-model:value="item.val" placeholder="请选择题目"
      @change="changeRow($event,index)"
    >
      <a-select-option
        v-for="(citem,cindex) in tst" :key="cindex"
        :value="citem.question_index">
        {{citem.title}}
      </a-select-option>
    </a-select>
    <!-- 标签框 -->
    <a-select
      v-if="item?.row?.length>0"
      :getPopupContainer="triggerNode=>triggerNode.parentNode"
      class="lineSelect custom-select"
      placeholder="请选择"
      :maxTagCount="maxTagCount"
      v-model:value="item.value"
      :key="index"
      @change="changeRowTag($event,index)"
    >
      <a-select-option
        v-for="(cItem,cindex) in item?.row" :key="cindex"
        :value="cItem.value">
        {{cItem.label}}
      </a-select-option>
    </a-select>
    <!-- 规则框 -->
    <a-select
      :getPopupContainer="triggerNode=>triggerNode.parentNode"
      class="lineSelect minSelect custom-select" v-model:value="item.operVal"
      :maxTagCount="maxTagCount"
      placeholder="请选择筛选规则"
      @change="changeOp($event,index,item)"
    >
      <a-select-option
        v-for="(cItem,cindex) in item?.operList" :key="cindex"
        :value="cItem.value">
        {{cItem.label}}
      </a-select-option>
    </a-select>
    <!-- 答案框 -->
    <template v-if="true">
      <!-- 级联题cascader -->
      <a-cascader
        v-if="item.answerType=='cascader'"
        :getPopupContainer="triggerNode=>triggerNode.parentNode"
        v-model:value="item.asVal"
        :options="item.answer"
        class="lineSelect"
        placeholder="请选择"
        change-on-select
      />
      <!-- 单选多选题select多选 radio单选 -->
      <a-select
        v-if="item.answerType=='select'||item.answerType=='radio'"
        :getPopupContainer="triggerNode=>triggerNode.parentNode"
        :mode="item.answerType=='select'?'multiple':'combobox'"
        :maxTagCount="maxTagCount"
        :maxTagTextLength="8"
        optionFilterProp="label"
        class="lineSelect custom-select"
        v-model:value="item.asVal"
        :options="item.answer"
        placeholder="请选择"
      >
        <a-select-option
          v-if="item.answerType=='radio'"
          v-for="(cItem,cindex) in item.answer" :key="cindex"
          :value="cItem.value">
          {{cItem.label}}
        </a-select-option>
        <template #dropdownRender="{ menuNode: VNodes }" v-if="item.answerType=='select'">
          <div style="padding: 4px 12px; cursor: pointer">
            <a-button size="small" type="primary" @click="selectAll(item)">全选</a-button>
            <a-button style="margin-left: 6px;" size="small"  @click="cancelSelectAll(item)">清空</a-button>
          </div>
          <a-divider style="margin: 4px 0" />
          <v-nodes :vnodes="VNodes" />
        </template>
      </a-select>
      <!-- 输入题 -->
      <a-input
        v-if="item.answerType=='input'"
        v-model:value="item.asVal"
        class="lineSelect"
        placeholder="请输入"
      />
      <!-- 数字输入题 -->
      <a-input-number
        v-if="item.answerType=='inputNumber'"
        v-model:value="item.asVal"
        class="lineSelect"
        placeholder="请输入"
      />
      <!-- 日期时间题 -->
      <template v-if="!dateRange.includes(item.operVal)">
      <!-- <template v-if="true"> -->
        <!-- 年月日 -->
        <a-date-picker
          v-if="item.answerType=='datetime'&&item.format[0]=='1'"
          :getCalendarContainer="(triggerNode) => triggerNode.parentNode"
          v-model:value="item.dateVal"
          placeholder="请选择日期"
          class="lineSelect"
          valueFormat="YYYY-MM-DD"
        />
        <!-- <template v-if="getDateTimeFlag(item,1)=='1'">
          <span class="betSpan">-</span>
          <a-date-picker
            v-model:value="item.datBeteVal"
            placeholder="请选择日期"
            class="lineSelect"
            valueFormat="YYYY-MM-DD"
          />
        </template> -->
        <a-month-picker
          v-if="item.answerType=='datetime'&&item.format[0]=='2'"
          :getCalendarContainer="(triggerNode) => triggerNode.parentNode"
          v-model:value="item.dateVal"
          placeholder="请选择月份"
          valueFormat="YYYY-MM"
          class="lineSelect"
        />
        <!-- <template v-if="getDateTimeFlag(item,1)=='2'">
          <span class="betSpan">-</span>
          <a-month-picker
            v-model:value="item.datBeteVal"
            placeholder="请选择月份"
            valueFormat="YYYY-MM"
            class="lineSelect"
          />
        </template> -->
        <a-date-picker
          v-if="item.answerType=='datetime'&&item.format[0]=='3'"
          :getCalendarContainer="(triggerNode) => triggerNode.parentNode"
          :mode="'year'"
          :value="item.dateVal"
          format="YYYY"
          placeholder="请选择年"
          class="lineSelect"
          @panelChange="dateChange($event,item,'dateVal')"
        />
        <!-- <template v-if="getDateTimeFlag(item,1)=='3'">
          <span class="betSpan">-</span>
          <a-date-picker
            :mode="'year'"
            :value="item.datBeteVal"
            format="YYYY"
            placeholder="请选择年"
            class="lineSelect"
            @panelChange="dateChange($event,item,'datBeteVal')"
            @change="changYear($event,item,'datBeteVal')"
          />
        </template> -->

        <!-- 时分秒 -->
        <a-time-picker
          v-if="item.answerType=='datetime'&&item.format[2]=='1'"
          :getCalendarContainer="(triggerNode) => triggerNode.parentNode"
          v-model:value="item.timeVal"
          :format="'HH:mm:ss'"
          valueFormat="HH:mm:ss"
          placeholder="请选择时间"
          class="lineSelect"
        />
        <!-- <template v-if="getDateTimeFlag(item,2)=='1'">
          <span class="betSpan">-</span>
          <a-time-picker
            v-model:value="item.timeBetVal"
            :format="'HH:mm:ss'"
            valueFormat="HH:mm:ss"
            placeholder="请选择时间"
            class="lineSelect"
          />
        </template> -->

        <a-time-picker
          v-if="item.answerType=='datetime'&&item.format[2]=='2'"
          :getCalendarContainer="(triggerNode) => triggerNode.parentNode"
          v-model:value="item.timeVal"
          placeholder="请选择时分"
          :format="'HH:mm'"
          valueFormat="HH:mm"
          class="lineSelect"
        />
        <!-- <template v-if="getDateTimeFlag(item,2)=='2'">
          <span class="betSpan">-</span>
          <a-time-picker
            v-model:value="item.timeBetVal"
            :format="'HH:mm'"
            valueFormat="HH:mm"
            placeholder="请选择时分"
            class="lineSelect"
          />
        </template> -->

        <a-time-picker
          v-if="item.answerType=='datetime'&&item.format[2]=='3'"
          :getCalendarContainer="(triggerNode) => triggerNode.parentNode"
          v-model:value="item.timeVal"
          :format="'HH'"
          valueFormat="HH"
          placeholder="请选择时"
          class="lineSelect"
        />
        <!-- <template v-if="getDateTimeFlag(item,2)=='3'">
          <span class="betSpan">-</span>
          <a-time-picker
            v-if="item.answerType=='datetime'&&item.format[2]=='3'"
            v-model:value="item.timeBetVal"
            :format="'HH'"
            valueFormat="HH"
            placeholder="请选择时"
            class="lineSelect"
          />
        </template> -->

      </template>
      <!-- 日期范围时间题 -->
      <template v-if="dateRange.includes(item.operVal)">
      <!-- <template v-if="false"> -->
        <!-- 日期 -->
        <a-range-picker
          class="lineSelect"
          v-if="getRangeFlag(item,1)==1"
          :getCalendarContainer="(triggerNode) => triggerNode.parentNode"
          style="width: 300px"
          v-model:value="item.datBeteVal"
          :placeholder="['开始日期', '结束日期']"
          :mode="getRangeMode(item,1)"
          :format="getRandeFormat(item,1)"
          :valueFormat="getRandeFormat(item,1)"
          @panelChange="getPanelChange($event,item,1)"
        />
        <!-- 时间 -->
        <a-range-picker
          class="lineSelect rangeTime"
          v-if="getRangeFlag(item,2)==2"
          :getCalendarContainer="(triggerNode) => triggerNode.parentNode"
          style="width: 300px"
          v-model:value="item.timeBetVal"
          :placeholder="['开始时间', '结束时间']"
          :mode="getRangeMode(item,2)"
          :show-time="{hideDisabledOptions: true}"
          :disabled-time="()=>disabledRangeTime(item)"
          :format="getRandeFormat(item,2)"
          :valueFormat="getRandeFormat(item,2)"
          @panelChange="getPanelChange($event,item,2)"
        />
      </template>
    </template>
    <!-- <DeleteFilled class="filterDelIcon" @click="delList(index)" /> -->
    <template v-if="listType=='list'">
      <i class="iconfont filterDelIcon" @click.stop="delList(index)">&#xe6c5;</i>
    </template>
    <template v-if="listType=='group'">
      <MinusSquareOutlined @click.stop="delList(index)" class="filterDelIcon filterDelAddIcon" />
      <PlusSquareOutlined v-if="answerList.length-1 == index"  @click="addList" class="filterDelIcon filterAddIcon" />
    </template>
  </div>
</div>
</template>
<script setup>
import { ref,toRefs,toRaw, reactive,computed,defineProps,onMounted ,watch,nextTick} from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useStore } from 'vuex';
import moment from 'moment';
import { CaretDownFilled ,DeleteFilled ,MinusSquareOutlined,PlusSquareOutlined ,DeleteOutlined} from '@ant-design/icons-vue';
const props = defineProps({
  listType:{
    type:String
  },
  answerList:{
    type:Array
  },
  answerGroupList:{
    type:Array
  },
  questions:{
    type:Array,
    default:()=>[]
  }
})
const emit = defineEmits(['delAnswerList'])
const VNodes=(_, { attrs }) => attrs.vnodes;
// 下拉框tag显示数量
const maxTagCount = 1
// 题目答案
const { answerGroupList,listType ,answerList} = toRefs(props)
const questions = computed(()=>props.questions)
console.log('questions.value',questions.value);

const tst = toRaw(questions)
// 获取是否为时间范围
const dateRange = ['between','notbetween']
const getDateTimeFlag = (el,num)=>{
  // const item = toRaw(el.value)
  const formatArr = ['1','2','3']
  const operArr = ['between','notbetween']
  if(num==1&&el?.format&&formatArr.includes(el.format[0])){
    if(el.answerType=='datetime'&&operArr.includes(el.operVal)){
      return el.format[0]
    }
  }
  if(num==2&&el?.format&&formatArr.includes(el.format[2])){
    console.log(el.format[2]);
    if(el.answerType=='datetime'&&operArr.includes(el.operVal)){
      return el.format[2]
    }
  }
}
//
const getRangeFlag = (item,type)=>{
  console.log(item,type);
  const formatArr = ['1','2','3']
  const operArr = ['between','notbetween']
  if(type==1&&item?.format&&formatArr.includes(item.format[0])){
    return 1
  }
  if(type==2&&item?.format&&formatArr.includes(item.format[2])){
    return 2
  }
}

// 数据重置
const resetRowInfo = (info,type=0)=>{
  // 每次更换重置
  if(type===0){
    // 标签信息
    info.row = []
    info.value = null
    // 规则
    info.operator = []
  }
  if(type!==2){
    // 规则
    info.operList = []
    info.operVal = null
  }
  // 答案
  info.answer = []
  info.answerType = null
  info.format = null
  info.asVal = null
  info.dateVal = null
  info.datBeteVal = []
  info.timeVal = null
  info.timeBetVal = []
  info.dateRanges = []
  info.mode = ['year','year']
  console.log('reset',info);
}
// 修改题目
const changeRow = (e,i)=>{
  console.log('changeRowchangeRow',answerList.value[i]);
  const info = answerList.value[i]
  resetRowInfo(info)
  questions.value.map(el=>{
    if(el.question_index==info.val){
      info.row = el.row
      info.operator = el.operator
      console.log('el.operator',el.operator);
    }
  })
  if(info.row.length==0){
    info.operList = []
    info.operator.map(el=>{
      el.list.map(cel=>{
        cel.key = el.key
        cel.answer = el.answer
        info.operList.push({...cel})
      })
    })
  }
  console.log('row',info);
}
// 添加条件列表
const addList = ()=>{
  const data = {}
  answerList.value.push(data)
}
// 修改标签
const changeRowTag = (e,i)=>{
  console.log('eeeeeee',e);
  const answerIndex = answerList.value[i]
  let key = null
  resetRowInfo(answerIndex,1)
  answerIndex?.row.map(el=>{
    if(el.value ==e){
      key = el.next_key+''
    }
  })
  answerIndex.operator.map(el=>{
    const keyArr = key.split('')
    if(keyArr.includes((el.key+''))){
      answerIndex.operList = []
      el.list.map(cel=>{
        cel.key = el.key
        cel.answer = el.answer
        answerIndex.operList.push(cel)
      })
    }
  })
}
// 多选框全选
const selectAll = (item)=>{
  const op = item.answer
  item.asVal = []
  op.map(el=>{
    item.asVal.push(el.value)
  })
}
// 多选框取消全选
const cancelSelectAll = (item)=>{
  item.asVal = []
}
// 修改范围
const changeOp = (e,i,el)=>{
  resetRowInfo(el,2)
  el.operList.map(cel=>{
    if(cel.value==e){
      el.answer = cel.answer?.list
      if(cel.answer?.type=='select'){
        el.asVal = []
      }else{
        el.asVal = null
      }
      el.answerType = cel.answer?.type
      el.format = cel.answer?.format
    }
  })
  console.log('changeOp',el);
}
// 时间格式
const dateChange = (value, el,val)=>{
  el[val] = value.format('YYYY')
}
const changYear = (value, el,val)=>{
  el[val] = value
}
// 日期范围格式
const getRandeFormat = (item,type)=>{
  const format = item.format
  const dateInfo = format[0]
  const timeInfo = format[2]
  let rDate = ''
  if(type==1){
    if(dateInfo==1){
      rDate = 'YYYY-MM-DD'
    }
    if(dateInfo==2){
      rDate = 'YYYY-MM'
    }
    if(dateInfo==3){
      rDate = 'YYYY'
    }
  }
  if(type==2){
    if(timeInfo==1){
      rDate = 'HH:mm:ss'
    }
    if(timeInfo==2){
      rDate = 'HH:mm'
    }
    if(timeInfo==3){
      rDate = 'HH'
    }
  }
  return rDate
}
// 修改面板
const getRangeMode = (item,type)=>{
  const format = item.format
  const dateInfo = format[0]
  const timeInfo = format[2]
  let rDate = ''
  if(type==1){
    if(dateInfo==1){
      rDate = ['date','date']
    }
    if(dateInfo==2){
      rDate = ['month','month']
    }
    if(dateInfo==3){
      rDate = ['year','year']
    }
  }
  if(type==2){
    if(timeInfo==1){
    rDate = ['time','time']
    }
    if(timeInfo==2){
      rDate = ['time','time']
    }
    if(timeInfo==3){
      rDate = ['time','time']
    }
  }
  return rDate
}
const getPanelChange = (value,item,type)=>{
  const format = item.format
  const dateInfo = format[0]
  const timeInfo = format[2]
  if(type ==1){
    if(dateInfo==1){
      item.datBeteVal = [value[0].format('YYYY-MM-DD'),value[1].format('YYYY-MM-DD')]
    }
    if(dateInfo==2){
      item.datBeteVal = [value[0].format('YYYY-MM'),value[1].format('YYYY-MM')]
    }
    if(dateInfo==3){
      item.datBeteVal = [value[0].format('YYYY'),value[1].format('YYYY')]
    }
  }
  if(type ==2){
    item.timeBetVal = value;
  }
}
// 修改时间限制
const disabledRangeTime = (item) => {
  const format = item.format
  const timeInfo = format[2]
  let sArr = []
  let mArr = []
  for (let i = 0; i < 60; i++) {
    if(timeInfo==3||timeInfo==2){
      sArr.push(i)
    }
    if(timeInfo==3){
      mArr.push(i)
    }
  }
  return {
    // disabledHours: () => range(0, 60).splice(4, 20),
    disabledMinutes: () => mArr,
    disabledSeconds: () => sArr,
  };
};
// 列表条件删除
const delList =index=>{
  const newList = [...answerGroupList.value,...answerList.value]
  // 普通条件跟集合条件至少剩下一个
  if(newList.length==1){
    if(answerList.value.length==1){
      answerList.value[0] = [{}]
    }
    return
  }
  // 集合情况下剩一条不可删除
  if(listType.value =='group'&&answerList.value.length==1){
    answerList.value[0] = [{}]
    return
  }
  answerList.value.splice(index,1)
}
// 反显操作
const ansQuesAdd = (answerList,questions)=>{
  answerList.value.map((el,index)=>{
    const nAns = questions.value.find(cel=>cel.question_index==el.val)
    if(nAns?.operator){
      nAns.operList = getOper(nAns,el)
    }
    answerList.value[index] = {...el,...nAns}
    answerList.value[index] = {...getAnswer(answerList.value[index])}
  })
}
// 拼装第三个框第四个框
const getOper = (nAns,el)=>{
  const nList = []
  nAns?.operator.map(cel=>{
    // 把key拼装到规则框
    const filterAttr = {
      key:cel.key,
      answer:cel.answer
    }
    if(cel.answer.format){
      filterAttr.format = cel.answer.format
    }
    const noperList =[]
    cel.list.map(nel=>{
      // 判断是否填写过行列框
      if(getKey(nAns.row,el.value)){
        if(getKey(nAns.row,el.value) ===cel.key){
          noperList.push({...filterAttr,...nel})
        }else{
          if(getKey(nAns.row,el.value)>10){
            const strKey = getKey(nAns.row,el.value)+''
            if(strKey[0] ==cel.key||strKey[1] ==cel.key){
              noperList.push({...filterAttr,...nel})
            }
          }
        }
      }else{
        noperList.push({...filterAttr,...nel})
      }
    })
    nList.push(...noperList)
  })
  return nList
}
// 获取需要拼装的key值
const getKey = (row,val)=>{
  for (let i = 0; i < row.length; i++) {
    if(row[i].value ===val)return row[i].next_key
    else null
  }
}
// 拼装答案类型
const getAnswer = (nAns)=>{
  const data = JSON.parse(JSON.stringify(nAns))
  if(data?.operList){
    const retAns={}
    data?.operList.map(cel=>{
      if(cel.value ===data.operVal){
        // 选项拼装
        retAns.answer = cel.answer.list
        // 时间题需要
        retAns.format = cel.format
        if(cel.answer.type){
          // 答案类型
          retAns.answerType =cel.answer.type
          // 下拉框类型的直接干
          if(cel.answer.type=='select'||cel.answer.type=='cascader'){
            if(data?.asVal.join()!=''){
              retAns.asVal =data?.asVal.join().split(',')
            }else{
              retAns.asVal = []
            }
          }else{
            // 输入题需要手动添加
            if(data.asVal){
              retAns.asVal =data?.asVal.join()??null
            }
          }
        }
      }
    })
    return  {...data,...retAns}
  }else{
    return {...data}
  }
}
watch([()=>answerList.value,()=>questions.value],(nval)=>{
  if((answerList?.value.length>0)&&questions.value.length>0){
    console.log('准备完毕',answerList.value,questions.value);
    ansQuesAdd(answerList,questions)
  }
},{immediate:true})
</script>
<style scoped lang='scss'>
.lineSelect{
  width: 200px;
  &:not(:first-child){
    margin-left: 12px;
  }
}
:deep(.lineSelect){
  width: 200px;
  &:not(:first-child){
    margin-left: 12px;
  }
}

.listSettingBtnR{
  display: flex;
  >.lineSelect{
    width: 190px;
    &:not(:first-child){
      margin-left: 12px;
    }
  }
}
.lineSelect.minSelect{
  width: 140px !important;
  flex-shrink: 0;
}
.lineSelect.maxSelect{
  width: 240px;
  flex-shrink: 0;
}
.suffix-icon{
  position: relative;
  width: 100%;
  z-index: 2;
}
.filterDelIcon{
  cursor: pointer;
  color: #dadada;
  margin-left: 16px;
  font-size: 22px;
  transition: all .3s ease-in-out;
  &:hover{
    color: #70b936;
  }
}
.filterDelAddIcon{
  font-size: 18px;
  color: #bfbfbf;
  &:hover{
    color: #434343;
  }
}
.filterAddIcon{
  font-size: 18px;
  color: #bfbfbf;
  &:hover{
    color: #434343;
  }
}
.filterLineBox{
  display: flex;
  max-width: 950px;
  width: 100%;
  align-items: center;
  margin-bottom: 10px;
}
.betSpan{
  margin-left: 6px;
  margin-right: -6px;
}
:deep(.ant-select-dropdown){
  top:35px !important;
}
:deep(.ant-calendar-footer){
  display: none;
}
.rangeTime{
  &:deep(.ant-calendar-footer){
  display: none;
  }
  &:deep(.ant-calendar-time-picker-inner){
    padding-top: 0;
  }
}
</style>