<template>
    <!-- 地址 -->
    <el-form label-width="auto" ref="form" :model="formItem.value">
        <el-form-item
            prop="region"
            :rules="rules(listItem)"
            :info.prop="info(listItem.title, formItem.value.region, '', formItem.hide)"
        >
            <el-cascader
                :placeholder="listItem.placeholder"
                :options="list"
                :props="{ label: 'name', value: 'code', expandTrigger: 'hover' }"
                clearable
                separator=" "
                v-model="region"
                @change="change"
                ref="cascader"
            ></el-cascader>
        </el-form-item>
        <el-form-item
            prop="detail"
            :rules="rules(listItem, 'detail')"
            :info.prop="info('详细地址', formItem.value.detail, '', formItem.hide)"
            v-if="listItem.address.type === 1"
        >
            <el-input
                type="textarea"
                :placeholder="listItem.placeholder2"
                resize="none"
                v-model="formItem.value.detail"
            ></el-input>
        </el-form-item>
    </el-form>
</template>

<script>
import mixin from '../mixin.js'
export default {
    name: 'FormAddress',
    props: {
        listItem: { type: Object, default: () => ({}) },
        formItem: { type: Object, default: () => ({}) }
    },
    mixins: [mixin],
    data () {
        return {
            list: [],
            region: this.listItem.address.value
        }
    },
    created () {
        this.init()
    },
    methods: {
        // 获取省市区（1 2 省市区，3 省市，4 省）
        init () {
            const call = res => { this.list = res.data }
            if (this.listItem.address.type <= 2) this.$api.commonApi.getPCA().then(call)
            else if (this.listItem.address.type === 3) this.$api.commonApi.getPC().then(call)
            else this.$api.commonApi.getP().then(call)
        },
        // 同步 value
        change () {
            this.formItem.value.region = this.$refs.cascader.getCheckedNodes()[0].pathLabels.join(' ')
        },
        // 获取校验规则
        rules (item, type) {
            const rules = []
            if (item.verify.required) rules.push(this.required(!type ? item.title : '详细地址')) // mixin
            return rules
        },
        // 提交校验
        verify () {
            return new Promise((resolve, reject) => {
                this.$refs.form.validate(valid => {
                    valid ? resolve() : reject(new Error('address 错误'))
                })
            })
        }
    }
}
</script>

<style lang="less" scoped>
.el-cascader {
    display: block;
}
</style>
