<template>
    <div class="updCodeWBox" v-loading="loading" :element-loading-text="loadingStr">
        <!-- <div class="updCodeWBox-title">
            <p>弱歸戶</p>
        </div>
        <el-divider border-style="dashed" /> -->
        <div style="line-height: 1px;height: 100%;overflow: auto;">
            <div style="margin-bottom: 10px;">
                <h3>區域</h3>
                <el-radio-group class="radioSty" v-model="countryId" @change="cIdChange">
                    <el-radio label="CN" size="large"  border>大陆地区</el-radio>
                    <el-radio label="TW" size="large" border>臺灣地區</el-radio>
                </el-radio-group>
            </div>
            
            <div style="margin-bottom: 10px;" v-if="provinceIdData != null">
                <h3>省/直轄市</h3>
                <el-radio-group class="radioSty" v-model="provinceId" @change="pIdChange">
                    <el-radio size="large" :label="p.provinceId"  border v-for="p in provinceIdData">{{ p.provinceName }}</el-radio>
                </el-radio-group>
            </div>

            <div style="margin-bottom: 10px;" v-if="cityIdData != null">
                <h3>市/界</h3>
                <el-radio-group class="radioSty" v-model="cityId">
                    <el-radio size="large" :label="c.cityId"  border v-for="c in cityIdData" @click="searchSchool(c.cityId)">{{ c.cityName }}</el-radio>
                </el-radio-group>
            </div>

            <div style="margin-bottom: 10px;margin-top: 70px;">
                <div style="display: flex;justify-content: center;align-items: center;">
                    <span style="font-weight: bold;font-size: 23px;margin-right: 5px;">搜尋</span>
                    <el-input v-model="wordFilter" placeholder="請填入簡碼或學校名稱" style="width: 500px;"/>
                </div>
                <el-table :data="showData" stripe style="width: 100%" >
                    <el-table-column prop="code" label="代碼"  />
                    <el-table-column prop="shortCode" label="簡碼"  />
                    <el-table-column prop="name" label="學校名稱"  />
                    <el-table-column label="">
                        <template #default="scope">
                            <el-button type="primary" size="small" @click="handleUpdSchoolW(scope.row.id, scope.row.name, scope.row.shortCode)">歸戶</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
    </div>
</template>
<script setup>
import country from '@/static/country.json'
import { h, reactive, ref, computed, getCurrentInstance, markRaw } from 'vue'
import { SuccessFilled, Warning } from '@element-plus/icons'
import { ElMessageBox, ElMessage, ElInput, ElForm, ElFormItem } from 'element-plus'
let { proxy } = getCurrentInstance()

const loading = ref(false)
const countryId = ref(null)
const provinceId = ref(null)
const provinceIdData = ref(null)
const cityId = ref(null)
const cityIdData = ref(null)
const tableData = ref([])
const wordFilter = ref('')
const loadingStr = ref('')

const cIdChange = (cId) => {
    cityId.value = null
    provinceId.value = null
    provinceIdData.value = null
    cityIdData.value = null
    switch(cId){
        case 'TW':
            cityIdData.value = country.filter(function(c){
                return c.countryId == cId && c.lang == 'zh-tw' && c.areaType == 'y'
            })
        break;
        case 'CN':
            provinceIdData.value = country.filter(function(c){
                return c.countryId == cId && c.lang == 'zh-cn' && c.areaType == 'p'
            })
        break;
    }
}

const pIdChange = (provinceId) =>{
    cityId.value = null
    cityIdData.value = null
    let lang = ''
    switch(countryId.value){
        case 'TW':
            lang = 'zh-tw'
        break;
        case 'CN':
            lang = 'zh-cn'
        break;
    }

    cityIdData.value = country.filter(function(c){
        return c.provinceId == provinceId && c.lang == lang && c.areaType == 'y'
    })
}

const searchSchool = async (cityId) =>{
    let data = {
        countryId: countryId.value,
        cityId: cityId,
        fullData: true
    }

    if(provinceId.value != null) {
        data.provinceId = provinceId.value
    }
    wordFilter.value = ''
    loadingStr.value = '搜索學校中...'
    loading.value = true

    await proxy.$api.getSchooBasicInfo(data).then((res) => {
        tableData.value = res
    }).catch(e=>{
        ElMessage.error('搜尋失敗')
    }).finally(() => {
        loading.value = false
    })
}

const showData = computed({
    get(){
        if(wordFilter.value != ''){
            let result = []
            console.log(wordFilter.value, 'wordFilter.value')
            tableData.value.forEach((f)=>{
                if(f.name.indexOf(wordFilter.value) >= 0){
                    result.push(f)
                } else if(f.shortCode && f.shortCode.indexOf(wordFilter.value) >= 0){
                    result.push(f)
                }
            })
            return result
        } else {
            return tableData.value
        }
    }
})

const handleUpdSchoolW = async (schDocId, schName, shortCode) =>{
    const iDsCount = ref(0)
    // 檢查array 內容是否重複
    function isArrayRep(array){
        var result = new Set();
        var repeat = new Set();
        array.forEach(item => {
            result.has(item) ? repeat.add(item) : result.add(item);
        })
        // console.log(result); // {1, 2, "a", 3, "b"}
        // console.log(repeat); // {1, "a"}
        // console.log(repeat.size)
        if(repeat.size != 0){
            return true
        } else {
            return false
        }
    }
    // 規則檢查: iDs
    const checkIds = (value) => {
        let isErr = false
        if(!value) {
            isErr = true
            return "請填入要歸戶的醍摩豆ID"
        } else if(value && !/^[0-9\n]+$/.test(value)){
            isErr = true
            return "只能輸入醍摩豆ID與換行"
        } else if(value && isArrayRep(value.split('\n'))){
            isErr = true
            return "醍摩豆ID有重複"
        } else if(value){
            let errIds = []
            let tmp = value.split('\n')
            tmp.forEach(e=> {
                if(e.length != 10) {
                    errIds.push(e)
                } else {
                    let now = Math.floor(new Date().getTime() / 1000)
                    let orgId = parseInt(e)
                    if(parseInt(e.substring(0, 1)) >= 6){
                        orgId -= 5000000000
                    }

                    if(orgId > now){
                        errIds.push(e)
                    }
                }
            })

            if(errIds.length > 0){
                // console.log(errIds, 'errIds')
                isErr = true
                return "請檢查醍摩豆ID是否符合格式或有空格"
            }
        }

        if(!isErr && value != ''){
            let tArray = value.split('\n')
            iDsCount.value = tArray.length
        } else {
            iDsCount.value = 0
        }

        return true
    }

    if(!shortCode){
        ElMessageBox.alert('此學校目前沒有簡碼', `***${schName}***`,
            {
                type: 'warning',
                icon: markRaw(Warning),
            }
        )
        // 中斷
        return 
    }

    ElMessageBox.prompt(
        '請填入要歸戶的醍摩豆ID', `歸戶至 ${schName} - ${shortCode}`, {
            confirmButtonText: '歸戶',
            cancelButtonText: '取消',
            inputType: 'textarea',
            inputValidator: checkIds,
            customClass: 'prompClass',
            roundButton: true,
            closeOnClickModal: false
        }
    ).then(({value})=>{
        let showStr = value.replaceAll('\n', ', ')
        ElMessageBox.confirm(
            `確認要歸戶以下的醍摩豆ID嗎?\n${showStr} \n\n 總共 ${iDsCount.value} 位`,
            `歸戶至 ${schName}  - ${shortCode}`,
            {
                confirmButtonText: '確認',
                cancelButtonText: '先不要',
                type: 'info',
                customClass: 'confirmClass'
            }
        ).then(async ()=>{
            let reqData = {
                schoolDocId: schDocId,
                ids: value.split('\n')
            }
            
            loadingStr.value = '弱歸戶...'
            loading.value = true

            await proxy.$api.updUserSchoolW(reqData).then((res) => {
                ElMessageBox.alert('成功', '弱歸戶成功',
                    {
                        type: 'info',
                        icon: markRaw(SuccessFilled),
                    }
                )
            }).catch(e=>{
                ElMessage.error('搜尋失敗')
            }).finally(() => {
                loading.value = false
            })
        })
    })
}
</script>
<style>
.prompClass textarea{
    min-height: 220px!important;
}
.confirmClass p{
    white-space: pre-line;
}
.radioSty .el-radio__input{
    display: none;
}
.radioSty .el-radio__label{
    font-weight: bold;
    font-size: 15px!important;
}
.radioSty .el-radio{
    margin-right: 10px;
}
</style>
<style scoped>
.updCodeWBox{
    width: 100%;
    height: 82vh;
    background-color: #fff;
    z-index:999;
    box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    padding: 1%;
    text-align: left;
}
.updCodeWBox-title{
    line-height: 40px;
    font-size:24px;
    font-weight: bold;
    color:#7b84a9;
    text-align: center;
}
</style>