<template>
    <view v-if="show">
        <view class="form-item" v-for="(item, index) in listData" :key="index">
            <view class="label" v-if="item.detailDisplay == 'Y'">
                <text class="c-red" v-if="item.detailRequired == 'Y'">*</text>
                <view class="t">
                    <text class="t-index">{{ item.index +'、' }}</text>
                    <text class="t-cont">{{ item.detailDesc }}</text>
                </view>
            </view>
            <!--input-->
            <view class="item-cont unit-wrap" :class="'cell-' + item.detailTypeCode" v-if="(item.detailTypeCode == 'Input' || item.detailTypeCode == 'InputNumber') && item.detailDisplay == 'Y'">
                <view class="prefix" v-if="item.detailPrefix">{{ item.detailPrefix }}</view>
                <view class="link-dynamic-box"
                    v-if="item.detailPropertiesCode == 'address' || item.detailPropertiesCode == 'native'"
                    :data-index="index" :data-id="item.detailID" :data-type="item.detailPropertiesCode"
                    @tap="showLinkDynamicChange">
                    <!-- <view class="link-dynamic {{item.resultValue?'':'placeholder'}}">{{ item.resultValue ? item.resultValue:'请选择' }}</view> -->
                    <input class="link-dynamic" :class="item.resultValue?'':'placeholder'" type="text"
                        :value="item.resultValue ? item.resultValue:'请选择'" disabled="true" />
                    <view class="unit-box">
                        <uni-icons class="unit" type="down" :size="20" />
                    </view>
                </view>
                <input v-else :type="item.detailTypeCode == 'InputNumber'?'digit':item.detailPropertiesCode == 'IDCard'?'idcard':item.detailPropertiesCode == 'mobile'?'number':'text'" :placeholder="'请输入'+ item.detailDesc"
                    :data-index="index" :data-id="item.detailID"
                    :readonly="item.detailReadOnly == 'Y' ? true:false" placeholder-class="placeholder"
                    @change="inputChange" :maxlength="140" />
                <view class="suffix" v-if="item.detailSuffix">{{ item.detailSuffix }}</view>
            </view>
            <!-- select -->
            <view class="item-cont unit-wrap " :class="'cell-'+ item.detailTypeCode" v-if="item.detailTypeCode == 'Select' && item.detailDisplay == 'Y'">
                <picker mode="selector" :value="item.resultIndex" :range="item.detailItem.item"
                    :data-values="item.detailItem.item" :data-index="index" :data-id="item.detailID"
                    range-key="itemDesc" @change="publicPickerChange">
                    <view class="select-box">
                        <view class="select-text">{{ item.detailItem.item[item.resultIndex].itemDesc }}</view>
                        <view class="unit-box">
                            <van-icon class="unit" name="arrow-down" />
                        </view>
                    </view>
                </picker>
            </view>
            <!-- date -->
            <view class="item-cont unit-wrap" :class="'cell-'+ item.detailTypeCode" v-if="item.detailTypeCode == 'DatePicker' && item.detailDisplay == 'Y'">
                <picker :name="[pIndex,index]" mode="date" :value="item.resultValue" start="1950-01-01"
                    :data-index="index" :data-id="item.detailID" @change="dateChange">
                    <view class="date-box">
                        <view class="date-text" :class="item.resultValue?'':'placeholder'">{{ item.resultValue ? item.resultValue : '请选择' }}</view>
                        <view class="unit-box">
                            <uni-icons class="unit" type="down" :size="20" />
                        </view>
                    </view>
                </picker>
            </view>
            <!--radio-->
            <view class="item-cont unit-wrap" :class="'cell-'+ item.detailTypeCode" v-if="item.detailTypeCode == 'Radio' && item.detailDisplay == 'Y'">
                <radio-group :name="[pIndex,index]" :data-index="[pIndex,index]" :data-id="item.detailID" @change="chooseOptionPublicChange">
                    <view class="" v-for="(childData,childIndex) in item.detailItem.item" :key="childIndex">
                        <radio :value="childData.itemValue">{{ childData.itemDesc }}</radio>
                        <view class="radio-child-container" v-if="childData.detailItem.item.length > 0">
                            <questionnaire-option :show="childData.checked" :detailData="questionaireData" :data="childData.detailItem.item" :pIndex="[pIndex,index]" @optionchange="bindChange" />
                        </view>
                    </view>
                </radio-group>
            </view>
            <!--checkbox-->
            <view class="item-cont unit-wrap" :class="'cell-'+ item.detailTypeCode" v-if="item.detailTypeCode == 'Checkbox' && item.detailDisplay == 'Y'">
                <checkbox-group :name="[pIndex,index]" :data-index="[pIndex,index]" :data-id="item.detailID" @change="chooseOptionPublicChange">
                    <view class="checkbox-item" v-for="(childData,childIndex) in item.detailItem.item" :key="childIndex">
                        <label class="item-box">
                            <checkbox :value="childData.itemValue" />
                            <text>{{ childData.itemDesc }}</text>
                        </label>
                        <view class="radio-child-container" v-if="childData.detailItem.item.length > 0">
                            <questionnaire-option :show="childData.checked" :detailData="questionaireData" :data="childData.detailItem.item" :pIndex="[pIndex,index,childIndex]" @optionchange="bindChange" />
                        </view>
                    </view>
                </checkbox-group>
            </view>
            <!-- textarea -->
            <view class="item-cont unit-wrap cell-Textarea" v-if="item.detailTypeCode == 'Text' && item.detailDisplay == 'Y'">
                <textarea class="textarea" :name="'form'+index" :placeholder="'请输入'+ item.detailDesc" :data-index="index" :data-id="item.detailID" @input="inputChange" />
            </view>
        </view>
    </view>
</template>

<script>
export default {
    props: {
        show: {
            type: Boolean,
            default: false
        },
        listData: {
            type: Array,
            default: []
        },
        pIndex: {
            type: [Array, String],
            default: null
        },
        detailData: {
            type: Object,
            default: null
        }
    },
    watch: {
        show: function(newVal) {},
        detailData: function (newVal) {
            this.questionaireData = newVal
        }
    },
    data() {
        return {
            questionaireData: null,
            showProvinceCity: false, // 是否显示省市区街道选择
            currentLinkDynamicType: null, // 省市区联动类型
            linkDynamicVal: [0, 0, 0, 0],
            linkDynamicData: [], // 联动数据集
            provinceData: ['请选择'], // 省
            cityData: ['请选择'], // 市
            countryData: ['请选择'], // 区
            areaData: [], // 街道
            currentLinkDynamicID: null,
            currentLinkDynamicVal: null
        }
    },
    created() {
        this.questionaireData = this.detailData
    },
    mounted() {
        const self = this
        self.listData = self.listData.map((item,index)=> {
            item['index'] = self.formatOptionIndex(item, index)
            return item
        })
    },
    methods: {
        formatOptionIndex(pIndex, index) {
            var resultOptionIndex = []
            pIndex.map(function (item, idx) {
                item = item + ''
                if (item.indexOf(',') > -1) {
                    item.split(',').map(function (data) {
                        if (data) {
                            resultOptionIndex.push(data)
                        }
                    })
                } else {
                    if (item) {
                        resultOptionIndex.push(item)
                    }
                }
            })
            resultOptionIndex.push(index)
            resultOptionIndex = resultOptionIndex.map(function (item) {
                item = parseInt(item) + 1
                return item
            })
            return resultOptionIndex.join('-')
        },

        chooseOptionPublicChange(e) {
            const id = e.currentTarget.dataset.id
            const val = e.detail.value
            let questionaireData = this.questionaireData
            const detailData = this.findItem(questionaireData, val, id)
            this.$emit('optionchange', {
                detailData
            })
        },
        // 公共Picker Change
        publicPickerChange(e) {
            let questionaireData = this.questionaireData
            const {
                id,
                values
            } = e.currentTarget.dataset
            const index = parseInt(e.detail.value)
            let val = []
            values.map((item, idx) => {
                if (index == idx) {
                    val.push(item.itemValue)
                }
            })
            console.log(val, id, index)
            const detailData = this.findItem(questionaireData, val, id, index)
            this.$emit('optionchange', {
                detailData
            })
        },
        // 公共Input Change
        inputChange(e) {
            console.log(e)
            let questionaireData = this.questionaireData
            const id = e.currentTarget.dataset.id
            const val = e.detail.value
            console.log(val, id)
            const detailData = this.findItem(questionaireData, val, id)
            this.$emit('optionchange', {
                detailData
            })
        },
        // 公共Date Change
        dateChange(e) {
            let questionaireData = this.questionaireData
            const id = e.currentTarget.dataset.id
            const val = e.detail.value
            const detailData = this.findItem(questionaireData, val, id)
            this.$emit('optionchange', {
                detailData
            })
        },
        // 级联省市区选择
        showLinkDynamicChange(e) {
            let index, id, type
            if (e) index = e.currentTarget.dataset.index
            if (e) id = e.currentTarget.dataset.id
            if (e) type = e.currentTarget.dataset.type
            this.setData({
                currentLinkDynamicType: type,
                linkDynamicIndex: index,
                showProvinceCity: !this.showProvinceCity,
                currentLinkDynamicID: id
            }, function () {
                this.getProvince()
            })
        },
        showLinkDynamicConfirm() {
            let questionaireData = this.questionaireData
            let id = this.currentLinkDynamicID
            const {
                linkDynamicData,
                linkDynamicVal
            } = this
            let arr = []
            linkDynamicVal.map((item, index) => {
                if (linkDynamicData[index] && linkDynamicData[index][item]) arr.push(linkDynamicData[index][item].descripts)
            })
            let reslutPCC = []
            arr.map(item => {
                if (item != '请选择') {
                    reslutPCC.push(item)
                }
            })
            for (let i = 0; i < linkDynamicData.length; i++) {
                if (linkDynamicData[i] && arr[i] == '请选择') {
                    Util.showToast('请选择' + (i == 0 ? '省' : (i == 1 ? '市' : (i == 2 ? '区' : (i == 3 ? '街道' : '')))))
                    return
                }
            }
            const val = reslutPCC.join('-')
            const detailData = this.findItem(questionaireData, val, id)
            this.showLinkDynamicChange()
            this.$emit('optionchange', {
                detailData
            })
        },
        // 获取街道数据
        getProvince() {
            const self = this
            const {
                linkDynamicData
            } = self
            return new Promise((resolve, reject) => {
                let data = {
                    params: [{}]
                }
                uni.showLoading({
                    title: '数据加载中...',
                })
                $http.post("urlS", self, {
                    // namespace: "Y",
                    code: "02010030",
                    data: data,
                    success: function (res) {
                        if (uni.hideLoading(), +res.errorCode === 0) {
                            linkDynamicData[0] = res.result.rows
                            linkDynamicData[0].splice(0, 0, {
                                id: 0,
                                code: 0,
                                descripts: '请选择'
                            })
                            let provinceData = linkDynamicData[0].map(item => item.descripts)
                            self.setData({
                                provinceData,
                                linkDynamicData,
                            })
                            resolve(res.data)
                        } else {
                            uni.hideLoading()
                            resolve([])
                        }
                    },
                    fail(err) {
                        uni.hideLoading()
                        reject(err)
                    }
                })
            })
        },
        // 获取城市
        getCity(provinceID) {
            const self = this
            const {
                linkDynamicData
            } = self
            return new Promise((resolve, reject) => {
                let data = {
                    params: [{
                        provinceID
                    }]
                }
                uni.showLoading({
                    title: '数据加载中...',
                })
                $http.post("urlS", self, {
                    // namespace: "Y",
                    code: "02010031",
                    data: data,
                    success: function (res) {
                        if (uni.hideLoading(), +res.errorCode === 0) {
                            linkDynamicData[1] = res.result.rows
                            linkDynamicData[1].splice(0, 0, {
                                id: 0,
                                code: 0,
                                descripts: '请选择'
                            })
                            let cityData = res.result.rows.map(item => item.descripts)
                            self.setData({
                                cityData,
                                linkDynamicData
                            })
                            resolve(res.data)
                        } else {
                            uni.hideLoading()
                            resolve([])
                        }
                    },
                    fail(err) {
                        uni.hideLoading()
                        reject(err)
                    }
                })
            })
        },
        // 获取街道乡镇数据
        getCountry(cityID) {
            const self = this
            const {
                linkDynamicData
            } = self
            return new Promise((resolve, reject) => {
                let data = {
                    params: [{
                        cityID
                    }]
                }
                uni.showLoading({
                    title: '数据加载中...',
                })
                $http.post("urlS", self, {
                    // namespace: "Y",
                    code: "02010032",
                    data: data,
                    success: function (res) {
                        if (uni.hideLoading(), +res.errorCode === 0) {
                            linkDynamicData[2] = res.result.rows
                            linkDynamicData[2].splice(0, 0, {
                                id: 0,
                                code: 0,
                                descripts: '请选择'
                            })
                            let countryData = res.result.rows.map(item => item.descripts)
                            self.setData({
                                countryData,
                                linkDynamicData
                            })
                            resolve(res.data)
                        } else {
                            uni.hideLoading()
                            resolve([])
                        }
                    },
                    fail(err) {
                        uni.hideLoading()
                        reject(err)
                    }
                })
            })
        },
        // 获取街道数据
        getStreet(areaID) {
            const self = this
            const {
                linkDynamicData
            } = self
            return new Promise((resolve, reject) => {
                let data = {
                    params: [{
                        areaID
                    }]
                }
                uni.showLoading({
                    title: '数据加载中...',
                })
                $http.post("urlS", self, {
                    // namespace: "Y",
                    code: "02010033",
                    data: data,
                    success: function (res) {
                        if (uni.hideLoading(), +res.errorCode === 0) {
                            if (res.result.rows && res.result.rows.length > 0) {
                                linkDynamicData[3] = res.result.rows
                                linkDynamicData[3].splice(0, 0, {
                                    id: 0,
                                    code: 0,
                                    descripts: '请选择'
                                })
                                let areaData = res.result.rows.map(item => item.descripts)
                                self.setData({
                                    areaData,
                                    linkDynamicData
                                })
                            } else {
                                linkDynamicData[3] = []
                                self.setData({
                                    linkDynamicData
                                })
                            }
                            resolve(res.data)
                        } else {
                            uni.hideLoading()
                            resolve([])
                        }
                    },
                    fail(err) {
                        uni.hideLoading()
                        reject(err)
                    }
                })
            })
        },
        bindLdpChange(e) {
            const {
                currentLinkDynamicType,
                linkDynamicVal,
                linkDynamicData
            } = this
            const resVal = e.detail.value
            this.setData({
                linkDynamicVal: resVal
            })
            if (linkDynamicVal[0] == 0) {
                let provinceID = linkDynamicData[0][resVal[0]].value
                this.getCity(provinceID)
            } else {
                for (let i = 0; i < linkDynamicVal.length; i++) {
                    if (linkDynamicVal[i] != resVal[i]) {
                        if (i == 0 && resVal[0] != 0) {
                            let provinceID = linkDynamicData[i][resVal[i]].value
                            this.getCity(provinceID)
                            let val = [resVal[0], 0, 0, 0]
                            this.setData({
                                linkDynamicVal: val,
                                cityData: ['请选择'],
                                countryData: ['请选择'],
                                areaData: [],
                            })
                        }
                        if (i == 1 && resVal[1] != 0) {
                            let cityID = linkDynamicData[i][resVal[i]].value
                            this.getCountry(cityID)
                            let val = [resVal[0], resVal[1], 0, 0]
                            this.setData({
                                linkDynamicVal: val,
                                countryData: ['请选择'],
                                areaData: [],
                            })
                        }
                        if (i == 2 && resVal[2] != 0 && currentLinkDynamicType == 'address') {
                            let areaID = linkDynamicData[i][resVal[i]].value
                            this.getStreet(areaID)
                            let val = [resVal[0], resVal[1], resVal[2], 0]
                            this.setData({
                                linkDynamicVal: val,
                                areaData: [],
                            })
                        }
                    }
                }
            }
        },
        // 递归修改值及子项显示
        findItem(detailData, val, id, idx) {
            const self = this
            return detailData.map(item => {
                // console.log(item.detailID,id)
                if (item.detailID == id) {
                    // select
                    if (item.detailTypeCode == 'Select') {
                        item['resultIndex'] = idx
                    }
                    // radio checkbox input DatePicker
                    item['checked'] = item.hasOwnProperty('checked') || !item.checked ? true : false
                    // console.log(val,val.constructor)
                    if (val.constructor === Array && val.length == 0) val = null
                    item['resultValue'] = item.checked ? val : null
                    // console.log(item)
                    if (item.hasOwnProperty('detailItem')) {
                        if (item.detailTypeCode == 'Radio' || item.detailTypeCode == 'Checkbox' || item.detailTypeCode == 'Select') {
                            item.detailItem.item.map(function (data) {
                                // console.log(val,data.itemValue)
                                if (val && val.indexOf(data.itemValue) > -1) {
                                    data.checked = true
                                } else {
                                    data.checked = false
                                    data.resultValue = null
                                    if (data.hasOwnProperty('resultIndex')) {
                                        data.resultIndex = null
                                    }
                                    if (data.hasOwnProperty('detailItem')) {
                                        self.clearItem(data.detailItem.item)
                                    }
                                }
                                return data
                            })
                        }
                    }
                } else {
                    // console.log(item)
                    if (item.hasOwnProperty('detailItem')) {
                        item.detailItem.item = self.findItem(item.detailItem.item, val, id, idx)
                    }
                }
                return item
            })
        },
        childItem(childData, val, id, idx) {
            const self = this
            return childData.map(item => {
                if (item.detailID == id) {
                    // select
                    if (childData.detailTypeCode == 'Select') {
                        item['resultIndex'] = idx
                    }
                    // radio checkbox Input DatePicker
                    item['checked'] = item.hasOwnProperty('checked') || !item.checked ? true : false
                    if (val.constructor === Array && val.length == 0) {
                        val = null
                    }
                    item['resultValue'] = item.checked ? val : null
                    if (item.detailTypeCode == 'Radio' || item.detailTypeCode == 'Checkbox' || item.detailTypeCode == 'Select') {
                        if (item.hasOwnProperty('detailItem')) {
                            item.detailItem.item.map(function (data) {
                                if (val.indexOf(data.itemValue) > -1) {
                                    data.checked = true
                                } else {
                                    data.checked = false
                                    data.resultValue = null
                                    if (data.hasOwnProperty('resultIndex')) {
                                        data.resultIndex = null
                                    }
                                    if (data.hasOwnProperty('detailItem')) {
                                        self.clearItem(data.detailItem.item)
                                    }
                                }
                                return data
                            })
                        }
                    }
                } else {
                    if (item.hasOwnProperty('detailItem')) {
                        item.detailItem.item = self.childItem(item.detailItem.item, val, id, idx)
                    }
                }
                return item
            })
        },
        // 取消选中后，清除当前项下面选择的所有填写、选择的数据
        clearItem(childData) {
            const self = this
            return childData.map(item => {
                item['checked'] = false
                item['resultValue'] = null
                if (item.hasOwnProperty('detailItem')) {
                    self.clearItem(item.detailItem.item)
                }
                return item
            })
        },
        bindChange(e) {
            const {
                detailData
            } = e.detail
            this.$emit('optionchange', {
                detailData
            })
        }
    }
}
</script>

<style>

</style>