<template>
    <view class="cust-form">
        <up-form labelPosition="left" :model="formData" ref="form_ref">
            <view v-for="item in column" :key="item.key + 'cust-form'" class="cust-form-item">
                <up-form-item v-if="item.type === 'input'" :label="item.label" :prop="item.key" borderBottom
                    labelWidth="94" :required="item.required">
                    <up-input v-model="formData[item.key]" border="none" :placeholder="'请输入' + item.label"></up-input>
                </up-form-item>

                <up-form-item v-if="item.type === 'select'" :label="item.label" :prop="item.key" borderBottom
                    labelWidth="94" :required="item.required">
                    <view @click.self="() => openActionSheet(item)">
                        <up-input v-model="formData[item.key]" disabled disabledColor="#ffffff"
                            :placeholder="'请选择' + item.label" border="none"></up-input>
                    </view>
                    <template #right>
                        <up-icon name="arrow-right"></up-icon>
                    </template>
                </up-form-item>

                <view v-if="item.type === 'phone-code'">
                    <up-form-item label="手机号" prop="phonenumber" borderBottom labelWidth="94" :rules="[
                        {
                            type: 'string',
                            required: true,
                            len: 11,
                            message: '请填写11位手机号',
                            trigger: ['blur']
                        }
                    ]" :required="true">
                        <up-input v-model="formData.phonenumber" border="none" placeholder="请输入手机号"
                            :disabled="!isCode"></up-input>
                    </up-form-item>

                    <up-form-item label="验证码" prop="code" labelWidth="94" borderBottom :rules="[
                        {
                            type: 'string',
                            required: true,
                            len: 4,
                            message: '请填写4位验证码',
                            trigger: ['blur']
                        }
                    ]" :required="true">
                        <up-input v-model="formData.code" border="none" placeholder="请填写验证码"></up-input>
                        <template #right>
                            <up-button @tap="getCode" :text="code_data.tips" type="success" size="mini"
                                style="flex: 0.5;" :disabled="code_data.disabled"></up-button>
                        </template>

                    </up-form-item>
                </view>
                <up-form-item v-if="item.type === 'textarea'" :label="item.label" :prop="item.key" labelWidth="94"
                    :required="item.required">
                    <up-textarea :placeholder="'请输入' + item.label" v-model="formData[item.key]" count></up-textarea>
                </up-form-item>

                <up-form-item v-if="item.type === 'face'" :label="item.label" :prop="item.key" borderBottom
                    labelWidth="94" :required="item.required">
                    <up-button size="small" type="primary" text="前往人脸识别" @click="startFace"></up-button>
                </up-form-item>

                <up-form-item v-if="item.type === 'city'" :label="item.label" :prop="item.key" borderBottom
                    labelWidth="94" :required="item.required">
                    <pickerAddress @change="(info) => addressChange(info, item)"
                        :selectValue="[formData.provinceInd, formData.cityInd, formData.districtInd]">
                        <view class="inp"
                            :class="formData.provinceName && formData.cityName && formData.districtName ? '' : 'address-inp'">
                            {{ formData.provinceName ? formData.provinceName : '省' }} /
                            {{ formData.cityName ? formData.cityName : '市' }} /
                            {{ formData.districtName ? formData.districtName : '区' }}
                        </view>
                    </pickerAddress>
                    <template #right>
                        <up-icon name="map" size="22" @click="onCityWx(item)"></up-icon>
                    </template>
                </up-form-item>

                <up-form-item v-if="item.type === 'cascader'" :label="item.label" :prop="item.key" borderBottom
                    labelWidth="94" :required="item.required">
                    <view @click.self="() => clickPick(item)">
                        <up-input v-model="formData[item.key]" disabled disabledColor="#ffffff"
                            :placeholder="'请选择' + item.label" border="none"></up-input>
                    </view>
                    <template #right>
                        <up-icon name="arrow-right"></up-icon>
                    </template>
                </up-form-item>
            </view>
        </up-form>

        <up-action-sheet :show="showSex" :actions="actions.option" :title="'请选择' + actions.label"
            @close="showSex = false" @select="ActionSheetSelect">
        </up-action-sheet>

        <up-code ref="uCode" @change="codeChange" seconds="60" @start="code_data.disabled = true"
            @end="code_data.disabled = false"></up-code>

        <!-- 省市区选择 province city area初始省市区设置 show:是否显示  @changeClick：更改省市区事件 @sureSelectArea：确认事件 @hideShow：隐藏事件-->
        <CcSelectDity :province="cityData.province" :city="cityData.city" :area="cityData.area" :show="cityShow"
            @sureSelectArea="onsetCity" @hideShow="onCityShow"></CcSelectDity>

        <Picker :columnData="options[actions.optionKey]" ref="pickerRef" @submit="ActionSheetSelect" />
    </view>
</template>
<script setup>
import { onMounted, reactive, ref } from "vue";
import CcSelectDity from '@/pages_home/components/cc-selectDity/cc-selectDity.vue';
import Picker from '@/pages_home/components/picker/index.vue'
import { sendCode } from '@/api/sm.js';
import {
    onShow,
    onUnload
} from "@dcloudio/uni-app";
import { splitAddress, getCityCode } from '@/utils/adress'
import { regionAddresstree } from '@/api/home.js'

import pickerAddress from '../pickerAddress/pickerAddress.vue'

const props = defineProps({
    column: {
        type: Array,
        default: [],
    },
    isCode: {
        type: Boolean,
        default: true
    }
});
const formData = reactive({
    sex: null,
    city: null,

    provinceName: '', // 省
    provinceCode: '',
    provinceInd: 21,

    cityName: '', // 市
    cityCode: '',
    cityInd: 0,

    districtName: '',
    districtCode: '',
    districtInd: 17,

    // address: "永川区",
    // age: "1",
    // city: "重庆",
    // code: "1111",
    // idCard: "5002302000000000001",
    // name: "陈陈",
    // phonenumber: "18696601933",
    // sex: '男',
    // skillDescribe: "测试备注",
});
const form_ref = ref(null);

const showSex = ref(false);
const actions = ref({
    option: [],
    optionKey: 'businessManagementOption'
});
const pickerRef = ref(null)

const options = reactive({
    businessManagementOption: []
})

const cityData = reactive({
    province: "重庆",
    city: "重庆市",
    area: "永川区",
})
const cityShow = ref(false)

const code_data = reactive({
    disabled: false,
    tips: ''
})
const uCode = ref(null);


function hideKeyboard() {
    uni.hideKeyboard()
}

function openActionSheet(row) {
    console.log(row);
    hideKeyboard();
    showSex.value = true;
    actions.value = row
}
function onCityShow() {
    console.log('onCityShow');
    cityShow.value = false;
}

function openCity(row) {
    console.log(row);
    cityShow.value = true
    actions.value = row
}
function onsetCity(e) {
    console.log('onsetCity', e);
    cityShow.value = false
    Object.assign(formData, {
        [actions.value.key]: e.address
    })

    console.log('formData', formData);

}

function ActionSheetSelect(e) {
    console.log('e', e);
    Object.assign(formData, {
        [actions.value.key]: e.key || e.name
    })
    if (actions.value.type === 'cascader') {
        Object.assign(formData, {
            [actions.value.key + 'key']: e.value
        })
    }
    console.log('formData.value', formData);

    // form_ref.value.validateField(actions.key)
}


async function getCode() {
    if (uCode.value.canGetCode) {
        // 模拟向后端请求验证码

        if (formData.phonenumber) {
            uni.showLoading({
                title: '正在获取验证码'
            })
            const res = await sendCode(formData.phonenumber);
            console.log(res);

            if (res.code == 200) {
                uni.hideLoading();
                uCode.value.start();
                uni.$u.toast('验证码已发送');
            }
        } else {
            uni.$u.toast('请输入手机号');
        }
    } else {
        uni.$u.toast('倒计时结束后再发送');
    }
}

function codeChange(text) {
    code_data.tips = text;
}

function startFace() {
    console.log('startFace', formData);

}


function setData(data) {
    console.log('setData=>data', data);
    Object.assign(formData, {
        ...data,
        sex: data.sex === 0 ? '男' : '女',
    })
    for (let i = 0; i < props.column.length; i++) {
        const element = props.column[i];


        if (element.type === 'cascader') {
            const key = data[element.key]
            // const key ='7'

            const lable = pickerRef.value.piceInit(key);
            console.log('element.type', lable, key, element.key);
            Object.assign(formData, {
                [element.key]: lable,
                [element.key + 'key']: key
            })
            console.log('eformData', formData);
        } else {

        }

    }

}

function onSubmit() {
    // 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
    return new Promise(async (resolve, reject) => {

        const res = await form_ref.value.validate();
        if (!res) {
            reject()
            return
        }
        resolve(formData);
    })
}
function onResetField() {
    form_ref.value.resetFields()
    form_ref.value.clearValidate()
}

function clickPick(row) {
    console.log('e', row);
    actions.value = row
    console.log('e', actions.value);
    pickerRef.value.show();

}


function addressChange(info, row) {
    actions.value = row
    console.log(info, '>>>>data');

    if (!info || !info.data) {
        console.error('Invalid address change info:', info);
        return;
    }

    if (!Array.isArray(info.data) || info.data.length < 3) {
        console.error('Invalid address data:', info.data);
        return;
    }

    const code = Array.isArray(info.code) ? info.code : ['', '', ''];

    let indexArray;
    if (Array.isArray(info.index)) {
        indexArray = info.index;
    } else if (info.index && typeof info.index[Symbol.iterator] === 'function') {
        indexArray = Array.from(info.index);
    } else {
        indexArray = [0, 0, 0];
    }


    Object.assign(formData, {
        provinceName: info.data[0],
        provinceCode: info.code[0],
        provinceInd: indexArray[0] || 0,
        cityName: info.data[1],
        cityCode: info.code[1],
        cityInd: indexArray[1] || 0,
        districtName: info.data[2],
        districtCode: info.code[2],
        districtInd: indexArray[2] || 0
    })
    console.log('formData===>', formData);

}
function onCityWx(row) {
    console.log('地区选点', row);
    wx.chooseLocation({
        success: async function (res) {
            console.log('res.address', res.address);

            const result = splitAddress(res.address);
            console.log("TCL: onCityWx -> result", result)
            const res_dara = await regionAddresstree();
            const handlecityData = getCityCode([result.province, result.city, result.district].join(' '), res_dara.data)
            console.log("TCL: onCityWx -> handlecityData", handlecityData)
            addressChange(handlecityData, row)

            Object.assign(formData, {
                // [row.key]: `${result.province}${result.city}${result.district}`,
                address: result.detail
            })

            // Object.assign(cityData, {     
            //     province: result.province,
            //     city: result.city,
            //     area:result.district,
            // })

            // Object.assign(formData, {
            // provinceName: result.province,
            // provinceCode: info.code[0],
            // provinceInd:indexArray[0] || 0,
            // cityName: result.city,
            // cityCode:info.code[1],
            // cityInd:indexArray[1] || 0,
            // districtName: result.district,
            // districtCode:info.code[2],
            // districtInd:indexArray[2] || 0,

            // address:result.detail
            // })

            // Object.assign(formData, {
            //     [row.key]: `${result.province}${result.city}${result.district}`,
            //     address:result.detail
            // })
        },
        fail: function (err) {
            console.log(err);
            uni.showToast({
                title: '获取地址失败',
                icon: 'error',
            });
        },
    })
}

onShow(() => {

})
onUnload(() => {

})
onMounted(async () => {
    const rules = {};
    for (let i = 0; i < props.column.length; i++) {
        rules[props.column[i].key] = props.column[i].rules;
        if (props.column[i].type === 'cascader') {
            const res = await props.column[i].apifun();
            Object.assign(options, {
                [props.column[i].optionKey]: res
            })
            console.log('onMounted9999', options);
        }
    }
    form_ref.value && form_ref.value.setRules(rules)
    console.log('uni=====>', uni);

})

defineExpose({
    setData,//修改表单数据值
    onSubmit,//提交表单,先校验再提交
    onResetField,//表单重置
})
</script>
<style lang="scss" scoped>
// .cust-form-item{
//     position: relative;
// }
// .required-icon {
//     color: red;
//     position: absolute;
// }</style>
