<script setup>
import {watch,ref, reactive, computed} from 'vue'
import apiDataEDB from '@/api/dataEDB'
import {edbFrequencyOpts,edbUnitOpts} from '../util/config'
import {deleteClassifyItemEmpty,findItemWithIdAndParents} from '../util/util'
import { showToast } from 'vant'

const props=defineProps({
    modelValue:{
        type:Boolean,
        default:false
    },
    dateSequenceEdbList:{
        type:Array,
        default:() => []
    },
})
const emits=defineEmits(['update:modelValue','addDateSequenceSuccess'])

const BatchList=ref([])
const edbIndex=ref(0)
const edbsLength=ref(1)

watch(
  ()=>props.modelValue,
  ()=>{
    if(props.modelValue){
      edbIndex.value = 0
      edbsLength.value = props.dateSequenceEdbList.length
      BatchList.value=[]
      props.dateSequenceEdbList.map(edb =>{
        BatchList.value.push({
          Source:edb.Source,
          ClassifyId:0,
          Unit:'',
          Frequency:'日度',
          EdbName:edb.EdbName,
          EdbCode:edb.EdbCode,
          StockCode:edb.StockCode
        })
      })
      getEdbClassifyList()
    }
  }
)

function handleClose(){
    emits('update:modelValue',false)
}

// 获取指标库分类
const edbClassifyList=ref([])
function getEdbClassifyList(){
  apiDataEDB.edbClassifyList().then(res=>{
    if(res.Ret===200){
      deleteClassifyItemEmpty(res.Data.AllNodes||[])
      edbClassifyList.value=res.Data.AllNodes||[]
    }
  })
}
const showSelectClassify=ref(false)

const selectClassifyNameStr=computed(()=>{
    if(!BatchList.value[edbIndex.value].ClassifyId) return ''

    let arr=[]
    arr=findItemWithIdAndParents(edbClassifyList.value,BatchList.value[edbIndex.value].ClassifyId)
    if(arr?.length){
        const textArr=arr.map(item=>item.ClassifyName)
        return `${textArr.join('/')}`
    }
})

// 选择频率
const showSelectFrequency=ref(false)
const frequencyOpts=edbFrequencyOpts.map(item=>{
    return {
        text:item,
        value:item
    }
})
function onConfirmSelectFrequency(e){
  BatchList.value[edbIndex.value].Frequency=e.selectedValues[0]
  showSelectFrequency.value=false
}

// 选择单位
const showSelectUnit=ref(false)
const unitOpts=edbUnitOpts.map(item=>{return{text:item,value:item}})
function onConfirmSelectUnit(e){
  BatchList.value[edbIndex.value].Unit=e.selectedValues[0]
  showSelectUnit.value=false
}
// 切换上一个
const lastToggle=()=>{
  if(!(edbIndex.value > 0)) return 
  edbIndex.value--
}

// 保存
async function handleSave(){

    let item = BatchList.value[edbIndex.value]
    if(!item.ClassifyId){
      showToast('所属目录不能为空')
      return
    }
    if(!item.Frequency){
      showToast('频度不能为空')
      return
    }
    if(!item.Unit){
      showToast('单位不能为空')
      return
    }
    if(!item.EdbName){
      showToast('指标名称不能为空')
      return
    }

    if(edbIndex.value+1 < edbsLength.value){
      edbIndex.value++
    }else{
      const res=await apiDataEDB.addBatchEDB({BatchList:BatchList.value})
      if(res.Ret===200){
        showToast('新增指标成功！')
        emits('addDateSequenceSuccess')
      }else if(res.Ret == 403){
        let repetitiveText=res.Data?res.Data.ExistEdbName[0] || '':''
        let repetitiveIndex = BatchList.value.findIndex(it => it.EdbName == repetitiveText)
        if(repetitiveIndex!=-1){
          edbIndex.value = repetitiveIndex
        }
      }
    }

}
</script>
  
<template>
  <van-popup 
    :show="props.modelValue"
    position="bottom"
    style="width:100%;height:100%"
  >
    <div class="add-dateSequence-EDB">
        <van-field 
          :modelValue="selectClassifyNameStr"
          readonly
          label="所属目录" 
          placeholder="请选择所属目录"
          input-align="right"
          right-icon="arrow"
          @click-input="showSelectClassify=true"
        />
        <van-field 
          :modelValue="BatchList[edbIndex].Unit"
          readonly
          label="单位" 
          placeholder="请选择单位"
          input-align="right"
          right-icon="arrow"
          @click-input="showSelectUnit=true"
        />
        <van-field 
          :modelValue="BatchList[edbIndex].Frequency"
          readonly
          label="频度" 
          placeholder="请选择频度"
          input-align="right"
          right-icon="arrow"
          @click-input="showSelectFrequency=true"
        />
        <van-field 
          v-model="BatchList[edbIndex].EdbName" 
          label="指标名称" 
          placeholder="请输入指标名称"
          input-align="right"
        >
        </van-field>
        <van-field 
          v-model="BatchList[edbIndex].EdbCode" 
          label="证券代码" 
          input-align="right"
          readonly
        >
        </van-field>
        <van-field 
          v-model="BatchList[edbIndex].StockCode" 
          label="指标代码" 
          input-align="right"
          readonly
        >
        </van-field>
        <div class="separation"></div>
        <ul class="data-value-wrap">
          <li class="item" style="font-weight:bold">时间</li>
          <li class="item" style="font-weight:bold">值</li>
          <template v-if="props.dateSequenceEdbList[edbIndex].DataList && props.dateSequenceEdbList[edbIndex].DataList.length>0">
            <template v-for="(item,index) in props.dateSequenceEdbList[edbIndex].DataList" :key="index">
              <li class="item">{{item.DataTime}}</li>
              <li class="item"><span class="val-box">{{item.Value}}</span></li>
            </template>
          </template>
          <div class="data-empty" v-else>
              <img src="https://hzstatic.hzinsights.com/static/ETA_mobile/empty_img.png" alt="">
              <p>暂无对应的数据</p>
          </div>
        </ul>
        <div class="edb-toggle-zone">
          <div class="edb-toggle-progress">
            <van-progress :show-pivot="false" style="border-radius: 0;flex-grow: 1;height: 100%;"
            :percentage="((edbIndex+1)/edbsLength)*100" color="#0052D9" track-color="#ECF2FE"></van-progress>
            <div class="edb-toggle-count">
              <span>{{ edbIndex+1 }}</span>/{{ edbsLength }}
            </div>
          </div>
          <div class="edb-toggle-buttons">
            <van-button type="primary" class="toggle-button" :disabled="edbIndex==0" @click="lastToggle">上一个</van-button>
            <van-button class="toggle-button" @click="handleClose">取消</van-button>
            <van-button type="primary" class="toggle-button" @click="handleSave">
              {{ edbIndex+1 < edbsLength?'下一个':'保存' }}
            </van-button>
          </div>
        </div>
    </div>
  </van-popup>

  <!-- 选择分类 -->
  <van-popup 
    v-model:show="showSelectClassify" 
    round 
    position="bottom"
  >
      <van-cascader
          v-model="BatchList[edbIndex].ClassifyId"
          title="选择目录"
          :options="edbClassifyList"
          :field-names="{text:'ClassifyName',value:'ClassifyId',children:'Children'}"
          @close="showSelectClassify = false"
      />
      <div style="width:300px;margin:0 auto;padding:20px 0">
          <van-button type="primary" round block @click="showSelectClassify = false">确定</van-button>
      </div>
  </van-popup>

  <!-- 选择频率 -->
  <van-popup 
      v-model:show="showSelectFrequency" 
      round 
      position="bottom"
  >
      <van-picker
          title="请选择频率"
          :columns="frequencyOpts"
          @cancel="showSelectFrequency=false"
          @confirm="onConfirmSelectFrequency"
      />
  </van-popup>

  <!-- 选择单位 -->
  <van-popup 
    v-model:show="showSelectUnit" 
    round 
    position="bottom"
  >
    <van-picker
      title="选择单位"
      :columns="unitOpts"
      @cancel="showSelectUnit=false"
      @confirm="onConfirmSelectUnit"
    />
  </van-popup>
</template>

<style lang="scss" scoped>
.add-dateSequence-EDB{
  padding-bottom: 112PX;
  .separation{
    width: 100%;
    height: 10PX;
    background-color: #F3F3F3;
  }
  .data-value-wrap{
    display: flex;
    flex-wrap: wrap;
    .item{
      width: 50%;
      padding: 32px;
      border-bottom: 1px solid $border-color;
      display: flex;
      align-items: center;
      &:nth-child(odd){
        border-right: 1px solid $border-color;
      }
      .val-box{
        display: inline-block;
        background-color: #F2F3FF;
        color: $theme-color;
        text-align: center;
        padding: 0 30px;
        line-height: 48px;
        border-radius: 8px;
      }
    }
    .data-empty{
      width: 100%;
      text-align: center;
      color: $font-grey;
      img{
          width: 200PX;
      }
    }
  }
  .edb-toggle-zone{
    position: fixed;
    bottom: 0;
    background-color: white;
    width: 100%;
    .edb-toggle-progress{
      display: flex;
      align-items: center;
      height: 24PX;
      .edb-toggle-count{
        color: #333333;
        font-weight: 600;
        font-size: 16PX;
        height: 100%;
        width: 65PX;
        background-color: #F4F8FE;
        display: flex;
        align-items: center;
        justify-content: center;
        span{
          color: #0052D9;
        }
      }
    }
    .edb-toggle-buttons{
      padding: 24PX;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .toggle-button{
        min-width: 100PX;
        height: 40PX;
        border-radius: 6PX;
        font-weight: 600;
      }
    }
  }
}
@media screen and (min-width:$media-width){
  .add-dateSequence-EDB{
    .data-value-wrap{
      .item{
        padding: 16px;
        .val-box{
            padding: 0 15px;
            line-height: 28px;
            border-radius: 4px;
        }
      }
    }
  }

}
</style>