<template>
    <navigation :title="title" :back-url="backUrl">
        <template #right>
            <my-link @tap="toMyDeclaration" style="font-size: 14px;">我的</my-link>
        </template>
    </navigation>
    <view class="contentBox">
        <uv-form ref="formRef" labelPosition="left" class="form" :model="formData" label-width="150rpx">
            <!-- 联系人 -->
            <uv-form-item label="联系人" prop="contactName">
                <uv-input placeholder="请输入联系人" v-model="formData.contactName" clearable border="none" />
            </uv-form-item>
            <!-- 联系电话 -->
            <uv-form-item label="联系电话" prop="contactPhone">
                <uv-input placeholder="请输入联系电话" maxlength="11" type="number" v-model="formData.contactPhone" clearable
                    border="none" />
            </uv-form-item>
            <!-- 交付时间 -->
            <uv-form-item label="交付时间" @tap="toChooseTime">
                <view v-if="formData?.deliveryTime">{{ formData.deliveryTime
                    === '0' ? '15天' : formData.deliveryTime === '1' ? '立即' : '其他' }}</view>
            </uv-form-item>
            <!-- 存放地址 -->
            <uv-form-item label="存放地址" prop="address" class="topLabel">
                <uv-textarea v-model="formData.address" placeholder="请输入存放地址" border="none"></uv-textarea>
            </uv-form-item>
            <!-- 申报图片 -->
            <uv-form-item label="申报图片" prop="fileList" class="topLabel">
                <uv-upload :fileList="formData?.fileList" name="1" multiple :maxCount="6" @afterRead="afterRead"
                    @delete="deleteImg" :previewFullImage="true"></uv-upload>

            </uv-form-item>
        </uv-form>
        <!-- 物料列表 - 添加物料 -->
        <MaterialList ref="materialRef" :formData="{ material: formData?.itemList }"
            :isEdit="flag == 'declaration_edit' ? 5 : 1" :pathParams="{ ...pathParams.value, type: 'declaration' }"
            @setStorage="toSetStorage" />
        <!-- 底部操作栏 -->
        <view class="bottom">
            <uv-button @tap="scanCode">扫码添加</uv-button>
            <uv-button type="primary" @tap="submitForm">提交</uv-button>
        </view>
    </view>
    <!-- 选择物料 -->
    <uv-modal ref="modalRef" class="chooseModal" :title="none" :showConfirmButton="false" :showCancelButton="false">
        <p class="link" @tap="toCheckTime('0')">15天</p>
        <p class="link" @tap="toCheckTime('1')">立即</p>
        <p class="link" @tap="toCheckTime('2')">其他</p>

    </uv-modal>
</template>
<script setup>
import _ from 'lodash';
import { ref } from 'vue';
import { onLoad } from "@dcloudio/uni-app";

import { objectToQuery, removeStorage } from '../../until';

import { addDeclareBill, declareBillUpdate } from '@/api/declaration'
import { uploadTechnicalFile } from '@/api/stockOut'
import { getMaterialByQrCodeInfo } from '@/api/uniqueCode';

import Navigation from '../../components/Navigation.vue';
import MaterialList from '../../components/MaterialList.vue';
const OPERATE_CONFIG = {
    declaration: {
        title: '申报单开单',
        back: 'pages/warehousing/index'
    },
    my: {
        title: '',//申报单编辑
        back: '/pages/warehousing/Declaration/components/detail'
    },
}
const title = ref('申报单开单')// ref：标题
const backUrl = ref('')
const formData = ref({ itemList: [], contactName: '', contactPhone: '', address: '', fileList: [], deliveryTime: '' })
// 数据：路径参数
const pathParams = ref('')
// 标志：区分页面
const flag = ref('')
// ref：物料绑定
const materialRef = ref([])
// 弹窗：交付时间选择
const modalRef = ref()
// 交付时间选择
const toChooseTime = () => {
    modalRef.value.open()
}
const toCheckTime = (val) => {
    formData.value.deliveryTime = val
    modalRef.value.close()
}
// 上传申报图片
const afterRead = async (event) => {
    // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
    let files = event.file?.map(file => file.url);
    let formDataVal = {
        scene: 'DECLARE',
        bizType: 'DECLARE_ADDRESS',
    }
    uploadTechnicalFile(files, formDataVal).then(res => {
        const some = _.some(res, { success: false })
        if (some) return;
        if (!formData.value?.fileList || formData.value?.fileList.length == 0) {
            formData.value.fileList = []
        }
        res?.forEach(item => {
            formData.value.fileList.push({ url: item?.url, name: item?.name, scene: 'DECLARE', bizType: 'DECLARE_ADDRESS' })
        })
    })
}
const toMyDeclaration = () => {
    const query = objectToQuery(pathParams.value)
    uni.navigateTo({
        url: `/pages/warehousing/Declaration/my${query}`,
    });
}
// 数据：缓存当前填入数据
const toSetStorage = () => {
    uni.setStorageSync('app_declaration', formData.value)
}
// 数据：获取缓存信息
const getDeclarationInfo = () => {

    const declarationInfo = uni.getStorageSync('app_declaration');// 申报信息
    formData.value = declarationInfo || { itemList: [], contactName: '', contactPhone: '', address: '', fileList: [], deliveryTime: '' }

    const material = uni.getStorageSync('app_material') || [];   // 物料信息
    formData.value.itemList = material
}

// 扫码添加
const scanCode = () => {
    // 先校验是否支持扫码
    uni.scanCode({
        scanType: ['qrCode', 'barCode'], // 支持二维码 + 条形码
        success: (res) => {
            const idx = includes(existList, res.result)
            if (idx) {
                uni.showToast({
                    title: '该物料已添加，请勿重复添加！',
                    mask: true,
                    icon: 'none',
                })
                return
            }
            if (res.result) {
                getMaterialByQrCodeInfo({ code: res.result, existList: existList.value }).then((response) => {
                    if (`${response.code}` === '200') {
                        const material = uni.getStorageSync('app_material');
                        // 处理物料信息 合并
                        const materialInfo = _.filter(material, { isDelete: '0' });
                        console.log('materialInfo====>', materialInfo);
                        const materialId = response.data?.[0]?.materialId;
                        console.log('materialId====>', materialId);
                        // const idx = _.findIndex(materialInfo, (i) => i.materialId ? i.materialId == materialId : i.id == materialId);
                        // console.log('已选中是否有重复数据====>', idx);

                        // if (idx != -1) {
                        //     uni.showToast({
                        //         title: '该物料已添加，请勿重复添加！',
                        //         mask: true,
                        //         icon: 'none',
                        //     })
                        // } else {
                        let _material = [...materialInfo, { ...response.data[0], uniqueCode: res.result }]
                        console.log('新的物料数组====>', _material);
                        formData.value.material = _material
                        uni.setStorageSync('app_material', formData.value.material)
                        existList.value.push(res.result)
                        // }
                    } else {
                        console.log(response.code, 'response.code');
                    }


                })
            }
        },
        fail: () => {
            uni.showToast({ title: '扫码失败', icon: 'none' });
        }
    });
};

// 新增/编辑
const submitForm = () => {
    const materialInfo = materialRef.value.getMaterialList()
    if (!materialInfo || (materialInfo && materialInfo.length == 0)) {
        uni.showToast({
            title: '请填写物料信息',
            mask: true,
            icon: 'error',
        })
        return
    }

    let params = {
        itemList: _.map(materialInfo, (i) => ({ ...i.material })),
        contactName: formData.value.contactName,
        contactPhone: formData.value.contactPhone,
        deliveryTime: formData.value.deliveryTime,
        address: formData.value.address,
        fileList: formData.value.fileList,
    }
    // 新建
    if (!pathParams.value.billNo) {
        addDeclareBill(params).then((res) => {
            if (res.code == 200) {
                uni.showToast({
                    title: '申报单创建成功',
                    mask: true,
                    icon: 'success',
                })
                removeStorage()
                uni.navigateTo({
                    url: backUrl.value,
                });
            } else {
                uni.showToast({
                    title: '申报单创建失败',
                    mask: true,
                    icon: 'error',
                })
                return
            }

        })
    } else {
        // 编辑
        params.billNo = pathParams.value?.billNo
        params.id = formData.value?.id
        declareBillUpdate(params).then((res) => {
            if (res.code == 200) {
                uni.showToast({
                    title: '申报单编辑成功',
                    mask: true,
                    icon: 'success',
                })
                removeStorage()
                uni.navigateTo({
                    url: backUrl.value,
                });
            } else {
                uni.showToast({
                    title: '申报单编辑失败',
                    mask: true,
                    icon: 'error',
                })
                return
            }
        })
    }

}
// 删除图片
const deleteImg = (index, type) => {
    formData.value.fileList?.splice(index, 1)
}
onLoad((options) => {
    pathParams.value = options
    flag.value = options.type
    const query = objectToQuery(options)
    if (options.billNo) {
        title.value = options.billNo
        backUrl.value = OPERATE_CONFIG?.my?.back + query
    } else {
        backUrl.value = OPERATE_CONFIG?.[options.type]?.back
    }
    console.log(backUrl, options.type);

})
getDeclarationInfo();
</script>

<style scoped lang="scss">
.carPickerText {
    color: #c0c4cc;
}

/* 底部按钮 */
::v-deep .bottom {
    position: fixed;
    bottom: 0;
    height: 60rpx;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;

    .uv-button-wrapper {
        width: 50%;
        border-radius: 0;
    }

    .uv-button--info {
        background-color: #07c160;
        color: #fff;

    }
}

::v-deep .form {
    // background-color: #fff;
    padding: 0 0 12rpx 0;

    .uv-input__content {
        .uv-input__content__field-wrapper__field {
            text-align: right !important;
        }
    }

    .uv-form-item__body {
        background-color: #fff;
        padding: 12rpx;
        margin-bottom: 2rpx;
        align-items: center;
    }

    .uv-form-item__body__left__content__label {
        font-size: 14px;
    }

    .uv-line {
        border-bottom: 0 !important;
    }

    .uv-form-item__body__right__content__slot {
        justify-content: flex-end;
        align-items: center;
    }

    .uv-cell__body {
        padding: 0
    }

    .uni-icons {
        display: block;
    }

    .u-slot-title {

        display: flex;
        align-items: center;
    }

    .topLabel {
        .uv-form-item__body {
            display: block;
        }

        .uv-textarea {
            padding-left: 0;

        }

        .uv-upload {
            margin-top: 8px;
        }
    }
}

::v-deep.chooseModal {
    .uv-modal__content {
        display: block;
        padding-top: 24rpx !important;
        padding: 48rpx;

        .title {
            font-size: 16px;
            margin: 16rpx 0;

        }

        .link {
            color: #999;
            margin-top: 24rpx;
            font-size: 14px;

        }
    }
}
</style>