<template>
   <view class="a">
    
    <uni-popup ref="inputDialog" type="dialog">
        <view class="edit-view">
            <view class="title">{{titleOpt[detailActive]}}登记</view>
            <!-- <view class="tabs">
                <view class="tabs-item" :class="{'active': detailActive === 'xmnga'}" @click="detailClick('xmnga')">废品明细</view>
                <view class="tabs-item" :class="{'active': detailActive === 'upmnga'}" @click="detailClick('upmnga')">返修明细</view>
                <view class="tabs-item" :class="{'active': detailActive === 'cmnga'}" @click="detailClick('cmnga')">让步明细</view>
                <view class="tabs-item" :class="{'active': detailActive === 'umnga'}" @click="detailClick('umnga')">改型明细</view>
            </view> -->
            <view class="inp-view">
                <uni-forms ref="formRef" :key="detailActive" :modelValue="{formData:formData}" label-width='60px'>
                    <template v-for="(item, index) in formData">
                        <view :key='item.id' class="form-wrapper">
                            <uni-forms-item label="代码" >
                                <uni-easyinput v-model="item.typeCode" @input="(e) => handleCodeChange(e, item)" placeholder="请输入" />
                            </uni-forms-item>
                            <uni-forms-item label="类型" required :name="['formData', index, 'last']" :rules="[{'required': true,errorMessage: '请选择类型'}]">
                                <!-- <picker
                                    @change="bindPickerChange"
                                    :value="warehosueVal"
                                    :range="range"
                                    range-key="name"
                                > -->
                                <!-- <input
                                    class="uni-input"
                                    @click="pickShow = true"
                                    :value="item.last"
                                    placeholder="请选择"
                                /> -->
                                <uni-data-picker placeholder="请选择类型" @change="e => handleLastChange(e, item)" popup-title="请选择类型" :localdata="item.range" v-model="item.last"
                                    >
                                </uni-data-picker>
                                <!-- </picker> -->
                                <!-- <uni-data-select
                                    v-model="item.last"
                                     @change="e => handleLastChange(e, item)" 
                                    :localdata="range"
                                ></uni-data-select> -->
                            </uni-forms-item>
                            <uni-forms-item label="数量" required :name="['formData', index, 'first']" :rules="[{'required': true,errorMessage: '请输入数量'}]">
                                <uni-easyinput type='number' v-model="item.first" placeholder="请输入" />
                            </uni-forms-item>
                            <view class="handle">
                                <button type="warn" @click="handleDel(index)" >删除</button>
                            </view>
                        </view>
                    </template>
                                
                </uni-forms>
            </view>
            <view class="footer">
                <button type="primary" @click="handleAdd" >增加明细</button>
                <button type='primary' @click="handleSave">保存</button>
                <button @click='handleCancel'>关闭</button>
            </view>
        </view>
    </uni-popup>
    <!-- <u-action-sheet :list="range" v-model="pickShow"></u-action-sheet> -->
   </view>
</template>


<script>

import { getDict } from "@/api/report/index"
export default {
    
    data(){
        return {
            detailActive:'xmnga',
            callback:null,
            pickShow:false,
            formData:[],
            xmngaRange:[],
            upmngaRange:[],
            cmngaRange:[],
            umngaRange:[],

            xmngaList:[],
            cmngaList:[],
            umngaList:[],
            upmngaList:[],

            titleOpt:{
                xmnga:'废品明细',
                upmnga:'返修明细',
                cmnga:'让步明细',
                umnga:'改型明细',
            },
            pickerVal:0

        }
    },
    // computed:{
    //     range(){
    //         return this[this.detailActive + 'Range']
    //     }
    // },
    created(){
        this._getDict('废品', 'xmngaRange')
        this._getDict('返修', 'upmngaRange')
        this._getDict('让步', 'cmngaRange')
        this._getDict('改型', 'umngaRange')
    },
    methods:{
        open(active, data, callback){

            this.xmngaList = JSON.parse(data.xmngaJson || '[]')
            this.cmngaList = JSON.parse(data.cmngaJson || '[]')
            this.umngaList = JSON.parse(data.umngaJson || '[]')
            this.upmngaList = JSON.parse(data.upmngaJson || '[]')

            this.callback = callback

            this.detailClick(active)
            this.$refs.inputDialog.open()
        },
        
        bindPickerChange(val) {
                this.pickerVal = val?.detail?.value;
        },
        handleCodeChange(e, item){
                item.range = this[this.detailActive + 'Range'].filter(item => item.code.includes(e))
                item.last = ''
                if(item.range.length === 1){
                    item.last =  item.range[0].text
                }
        },
        handleLastChange(e, item){
            const value = e?.detail?.value[0]?.value || e
            const obj = this[this.detailActive + 'Range'].find(item => item.text == value)
            item.typeCode = ""
            if(obj){
                item.typeCode = obj.code
            }
        },
        handleAdd(){
           this.formData.push({
                first:"",
                last:"",
                typeCode:"",
                range:this[this.detailActive + 'Range'],
                id: Date.now()
           })  
        },
        handleSave(){
            this.$refs.formRef.validate().then(res=>{
                this[this.detailActive + 'List'] = uni.$u.deepClone(this.formData.map(item => ({
                    first: item.first,
                    last: item.last
                })))

                this.callback && this.callback({
                     xmngaList:this.xmngaList,
                     cmngaList:this.cmngaList,
                     umngaList:this.umngaList,
                     upmngaList:this.upmngaList,
                })
                this.handleCancel()
			}).catch(err =>{
				console.log('表单错误信息：', err);
			})
        },
        handleCancel(){
            this.$refs.inputDialog.close()
        },
        handleDel(index){
            const _this = this

            uni.showModal({
                title: `确认删除？`,
                content: '',
                confirmText: '确认',
                success: function (res) {
                if (res.confirm) {
                    _this.formData.splice(index, 1)
                }
                }
            })
        },
        handlePicker(){
            this.pickShow = true
        },
        detailClick(name){
            this.formData = uni.$u.deepClone(this[name + 'List']
                            .map((item, index) => ({
                                ...item,
                                typeCode:this[name + 'Range'].find(itm => itm?.value === item.last)?.code, 
                                id:index,
                                range:this[name + 'Range'],
                            })))
            
            this.formData.forEach(item => {
                 this.handleLastChange(item.last, item)
            })
            if (!this.formData.length) {
               this.formData = [{
                    first:"",
                    last:"",
                    typeCode:"",
                    id: Date.now(),
                    range:this[name + 'Range'],
                }] 
            }
            this.detailActive = name
        },
        async _getDict(type, key){
            const res = await getDict(type)
            this[key] = res.map(item => ({
                ...item,
                value:item.mrpDesc,
                text:item.mrpDesc
            }))
        }
    }
}
</script>


<style lang="scss" scoped>
.edit-view{
    background: #fff;
    border-radius: 16rpx;
    padding: 20rpx;
    .inp-view{
        width: 90vw;
        max-height: 60vh;
        min-height: 100rpx;
        overflow: auto;
    }
    /deep/.uni-data-tree-dialog .selected-list{
        justify-content: center;
    }
    /deep/.item{
        text-align: center;
    }
    .title{
    font-size: $uni-font-size-lg;
    padding: 20rpx 0 ;
    margin-bottom: 10rpx;
    }

    /deep/.uni-forms-item__label{
    font-size: $uni-font-size-sm;
    }
    /deep/.uni-input-input,/deep/.uni-input-placeholder,
    /deep/.uni-data-select,/deep/.uni-select__input-placeholder{
       font-size: $uni-font-size-sm;
    }
    /deep/.uni-data-select{
        line-height: 42px;
    }

    .form-wrapper{
         padding-right: 150rpx;
         position: relative;

         .handle{
            position: absolute;
            top: 0;
            right: 0;
            button{
                margin-bottom: 20rpx;
                font-size: $uni-font-size-sm;
            }
         }
    }
}
.tabs{
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 20rpx;
    font-size: $uni-font-size-sm;
    margin-bottom: 10rpx;

    .tabs-item{
        background: rgba(226, 226, 226, 1);
        border: 1rpx solid rgba(226, 226, 226, 1);
        padding: 10rpx 16rpx;

        &.active{
            background: #fff;
        }
    }
}

.footer{
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx;

    button{
        width: 170rpx;
        font-size: $uni-font-size-sm;

    }
}
</style>