<script setup>
import { computed, ref, watch } from 'vue'
import { customInterence } from '@/api/api.js'
import moment from 'moment'

const props = defineProps({
  isTotalDayDialogShow: {
    type: Boolean,
    default: false,
  },//控制弹窗展示
  customInfo: {
    type: Object,
    default:()=>{
      return {
        CompanyType:''
      }
    }
  },//客户信息
})
const emit = defineEmits(['close'])


const tabsShow = computed(() =>{
  const{IsShared} = props.customInfo
  //是否是共享客户
  if(!IsShared) return false
  //是否是管理员
  const role = localStorage.getItem("Role");
  if(!role.includes('admin'))return false
  return true
})

const tabs = [{label:'FICC',key:'ficc'},{label:'权益',key:'rai'}]
const tableLabel = [
    {
        label:'试用日期',
        key:'Date',
        minwidthsty:180
    },
    {
        label:'试用天数',
        key:'Days',
        widthsty:80
    },
    {
        label:'状态',
        key:'Status',
        minwidthsty:150
    },
]

const activeTab = ref('ficc')//默认选中的tab ficc/rai
const tableData = ref([])
const pageNo = ref(1)
const pageSize = ref(5)
const total = ref(1)
async function getTabData(){
  const res = await customInterence.tryOutDeail({
    CompanyId:props.customInfo.CompanyId,
    ProductId:activeTab.value==='ficc'?1:2,
    PageSize:pageSize.value,
    CurrentIndex:pageNo.value
  })
  if(res.Ret!==200) return
  //console.log('res',res)
  const {List,Paging} = res.Data
  total.value = Paging.Totals
  tableData.value = List
}

function handleCurrentChange(page){
  pageNo.value = page
  getTabData()
}

const totalDay = ref(props.customInfo.FiccTryOutDay)//累计试用天数
function changeTab(tab){
  const {FiccTryOutDay,RaiTryOutDay} = props.customInfo
  activeTab.value = tab.key
  totalDay.value = activeTab.value==='ficc'?FiccTryOutDay:RaiTryOutDay
  pageNo.value = 1
  getTabData()
}

function formatDate(startDate,endDate,type,index){
  if(type==='range'){
    const startStr = startDate==='0001-01-01T00:00:00Z'?'--':moment(startDate).format('YYYY.MM.DD')
    //如果是第一页的第一条,判断endDate是否超过当天
    let realDate = endDate
    if(index===0&&pageNo.value===1&&moment()<moment(endDate)){
      realDate = moment()
    }
    const endStr = endDate==='0001-01-01T00:00:00Z'?'--':moment(realDate).format('YYYY.MM.DD')
    return `${startStr} ~ ${endStr}`
  }
  if(type==='count'){
    if(startDate==='0001-01-01T00:00:00Z'||endDate==='0001-01-01T00:00:00Z') return 0
    const day = moment(endDate).diff(moment(startDate),'day')
    return Math.max(day+1,1)
  }
}

function formatStatus(status){
    const statusMap = {
      'add_try_out':'增开试用',
      'receive':'流失转试用',
      'thaw':'冻结转试用',
      'delay':'试用延期',
      'apply_receive':'流失转试用',
      'add':'新增试用',
      'edit':'试用变更',
      'formal_to_try_out':'正式转试用'
    }
    return statusMap[status]||'--'
}

function closeDia() {
  tableData.value=[]
  emit("close");
}

watch(
  ()=>props.isTotalDayDialogShow,
  (val) => {
      console.log(val)
      if(val){
        const {CompanyType,IsShared} = props.customInfo
        const companyType = (IsShared||CompanyType.includes('ficc'))?'ficc':'rai'
        changeTab({key:companyType})
      }
  }
)

</script>
<template>
  <el-dialog
    :model-value="isTotalDayDialogShow"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    @close="closeDia"
    width="889px"
    draggable
    center
  >
    <template #header>
      <div style="display: flex; align-items: center">
        <span style="fontsize: 16px"
          >{{ customInfo ? customInfo.CompanyName : "" }}——累计试用天数</span
        >
      </div>
    </template>
    <div class="dialog-container">
      <div class="tab-container" v-if="tabsShow">
        <p class="tab" :class="{active:activeTab===tab.key}" 
          v-for="tab in tabs" :key="tab.key"
          @click="changeTab(tab)">{{tab.label}}</p>
      </div>
      <p style="margin:20px 0;">
        <el-tooltip 
          effect="dark" 
          placement="top-start"
          content="累计试用天数：试用日期的并集"
        >
          <template #content>
            <i class="el-icon-question" style="font-size:16px;"/>
          </template>
        </el-tooltip>
        累计试用天数:<span style="color:#409EFF;">{{totalDay}}</span></p>
      <div class="table-container">
          <el-table
              v-if="tableData"
              :data="tableData"
              border
              max-height="600"
              style="width: 100%; margin-bottom: 20px">
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="50">
              </el-table-column>
              <el-table-column align="center"
                  v-for="item in tableLabel" :key="item.key"
                  :label="item.label"
                  :prop="item.prop"
                  :width="item.widthsty" 
                  :min-width="item.minwidthsty"
              >
              <template #default="{row,$index}">
                <span v-if="item.key==='Date'">
                  {{formatDate(row['StartDate'],row['EndDate'],'range',$index)}}
                </span>
                <span v-if="item.key==='Days'">
                  {{formatDate(row['StartDate'],row['RealEndDate'],'count')}}
                </span>
                <span v-if="item.key==='Status'">
                  {{formatStatus(row['Source'])}}
                </span>
              </template>
              </el-table-column>
          </el-table>
          <el-pagination 
            layout="total,prev,pager,next" 
            background
            :current-page="pageNo"
            @current-change="handleCurrentChange"
            :page-size="pageSize" 
            :total="total"
            style="text-align:right;">
					</el-pagination>
      </div>
    </div>
  </el-dialog>
</template>
<style scoped lang="scss">
.dialog-container{
  padding:0 50px 15px 50px;
  .tab-container{
    display: flex;
    .tab{
      cursor: pointer;
      width:110px;
      height:40px;
      text-align: center;
      line-height: 40px;
      font-size: 14px;
      background-color: #ECF5FF;
      color:#409EFF;
      border:1px solid #B3D8FF;
      margin-right: 42px;
      border-radius: 4px;
      &.active{
        border-color: #409EFF;
        background-color: #409EFF;
        color: #FFFFFF;
      }
    }
  }
}

</style>
