<template>
    <view class="mx3">
        <view class="main-color-bg" style="height: 100rpx; margin: 0 -30rpx"></view>
        <view class="p3 bg-color-white" style="margin-top: -50rpx; border-radius: 20rpx">
            <u-form :model="form" ref="uForm" :label-width="150">
                <!--                <view class="报修单号 f-size-32 f-weight-6 mt-2">基本信息</view>
                <u-form-item label="维修单号">
                    <u-input v-model="form.no" disabled />
                </u-form-item>

                <view class="main-color-text f-size-32 f-weight-6 mt-2">报修信息</view>
                <u-form-item label="报修人">
                    <u-input v-model="form.userName" disabled />
                </u-form-item>-->

                <view class="main-color-text f-size-32 f-weight-6 mt-2">维修信息</view>
                <!--                <u-form-item label="故障类别" prop="badType">
                    <u-input v-model="form.badType" disabled @click="badState = true" type="select" />
                    <u-select v-model="badState" :list="badList" @confirm="badSubmit"></u-select>
                </u-form-item>-->
                <!--                <u-form-item label="维修耗时">
                    <u-input type="number" v-model="form.minutes" />
                    <template slot="right">
                        <view>分钟</view>
                    </template>
</u-form-item>-->
                <!--                <u-form-item label="维修动作" prop="descripitionType">
                    <u-input v-model="form.descripitionType" disabled @click="descripitionState = true" type="select" />
                    <u-select v-model="descripitionState" :list="descripitionList" @confirm="descripitionSubmit"></u-select>
                </u-form-item>-->
                <!-- <u-form-item label="备注">
                    <u-input v-model="form.remark" type="textarea" :height="50" />
                </u-form-item> -->
                <u-form-item label="维修描述" required prop="repairContent" :label-width="150">
                    <u-input v-model="form.repairContent" type="textarea" :height="50" placeholder="请输入维修描述" />
                </u-form-item>
                <!-- <u-form-item label="维修时间">
					<u-input v-model="form.wxtime" disabled @click="wxtimeShow = true" />
					<u-picker v-model="wxtimeShow" mode="time" @confirm="handleWxTime"></u-picker>
				</u-form-item> -->
                <u-form-item label="工单类别" required prop="category" :label-width="150">
                    <u-input v-model="category" disabled @click="categoryState = true" type="select" />
                    <u-select v-model="categoryState" :list="categoryMap" @confirm="categorySubmit"></u-select>
                </u-form-item>
                <u-form-item label="是否停机" required prop="halt" :label-width="150">
                    <u-input v-model="form.halt" disabled @click="haltState = true" placeholder="请选择是否停机"
                        type="select" />
                    <u-select v-model="haltState" :list="haltList" @confirm="haltSubmit"
                        :default-value="haltDefaultValue"></u-select>
                </u-form-item>
                <u-form-item label="完成时间" prop="repairEndTime" :label-width="150">
                    <u-input v-model="form.repairEndTime" disabled @click="endTimeShow = true" placeholder="请选择完成时间"
                        type="select" />
                    <u-picker mode="time" v-model="endTimeShow" :params="dateTimeParams"
                        @confirm="endTimeSubmit"></u-picker>
                </u-form-item>
                <u-form-item label="维修图片">
                    <u-upload width="180" height="180" max-count="3" :action="action" :file-list="fileList"
                        @on-success="uploadSuccess" @on-remove="uploadRemove" :header="header"></u-upload>
                </u-form-item>

            </u-form>

            <view class="p-fixed d-flex j-around a-center footer">
                <!--                <view class="main-color-bg text-color-white common" @tap="goUseRepair">备件</view>-->
                <view class="main-color-bg text-color-white common" @tap="handleSubmit">完成</view>
            </view>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            form: {
                badType: '',
                // wxremarks: '',
                // photo: '',
                // wxtime: '',
                category: '',
                descripitionType: '',
                no: '',
                halt: '',
                needStop: '',
                userName: '',
                repairErrorTypeId: '',
                repairMinutes: '',
                repairRemark: '',
                repairContent: '',
                repairEndTime: ''
            },
            wxtimeShow: false,
            endTimeShow: false, // 完成时间
            dateTimeParams: {
                year: true,
                month: true,
                day: true,
                hour: true,
                minute: true,
                second: true
            },
            badState: false,
            categoryState: false,
            category: '',
            badList: [],
            categoryMap: [],

            haltState: false, // 是否停机
            haltList: [],
            descripitionState: false,
            descripitionList: [],
            action: this.$BaseTool.UserUtil.getUploadUrl(),
            header: {
                Authorization: 'Bearer ' + uni.getStorageSync('accessToken')
            },
            fileList: [],
            imagesList: [],
            detailId: '',
            descripitionMap: {},
            needStopMap: {},
            haltDefaultValue: [0],
            rules: {
                halt: [
                    {
                        required: true,
                        message: '请选择是否停机',
                        trigger: ['blur', 'change']
                    }
                ],
                category: [
                    {
                        required: true,
                        message: '请选择工单类别',
                        trigger: ['blur', 'change']
                    }
                ],
                repairContent: [
                    {
                        required: true,
                        message: '请输入维修描述',
                        trigger: ['blur', 'change']
                    }
                ]
                /* badType: [{
                    required: true,
                    message: '请选择故障类别',
                    trigger: ['blur', 'change']
                }],
                descripitionType: [{
                    required: true,
                    message: '请选择维修描述',
                    trigger: ['blur', 'change']
                }] */
            }
        };
    },
    onLoad(options) {
        if (options) {
            this.detailId = options.id
            this.form.id = options.id
        }
        this.descripitionMap = this.$DictCache.getLabelByValueMapByType(this.$DictCache.TYPE.REPAIRE_ACTION)
        const temp = []
        for (const key in this.descripitionMap) {
            temp.push({
                label: this.descripitionMap[key],
                value: key
            })
            this.descripitionList = temp
        }
        const categoryMap = this.$DictCache.getLabelByValueMapByType(
            this.$DictCache.TYPE.REPAIR_APPLICATION_FORM_CATEGORY
        )
        for (const key in categoryMap) {
            this.categoryMap.push({
                label: categoryMap[key],
                value: key
            });
        }
        this.needStopMap = this.$DictCache.getLabelByValueMapByType(
            this.$DictCache.TYPE.YES_NO
        );
        for (const key in this.needStopMap) {
            this.haltList.push({
                label: this.needStopMap[key],
                value: key
            });
        }
        this.form.halt = this.haltList[this.haltDefaultValue].label;
        this.form.needStop = this.haltList[this.haltDefaultValue].value;
        this.initData()
        this.getType()
    },
    onReady() {
        this.$refs.uForm.setRules(this.rules);
    },
    methods: {
        descripitionSubmit(data) {
            this.form.descripitionType = data[0].label;
            this.form.descripition = data[0].value;
        },
        // 领用备件
        goUseRepair() {
            uni.navigateTo({
                url: '../use-repair/use-repair'
            });
        },
        categorySubmit(data) {
            this.category = data[0].label;
            this.form.category = data[0].value;
            // 与 PC 端 FinishForm 联动逻辑一致：计划性维修默认停机，其余默认不停机
            const needStopValue = data[0].value == 1 ? '1' : '0';
            this.form.needStop = needStopValue;
            const haltItem = this.haltList.find(item => item.value == needStopValue);
            if (haltItem) {
                this.form.halt = haltItem.label;
            }
        },
        badSubmit(data) {
            this.form.badType = data[0].label;
            this.form.errorTypeId = data[0].value;
        },

        // 时间
        // handleWxTime(e) {
        // 	this.form.wxtime = e.year + '-' + e.month + '-' + e.day;
        // },
        // 提交
        handleSubmit() {
            const params = {
                ...this.form
            }
            // 维修图片按 PC 端 FinishForm 的文件 DTO 结构提交（type 12 为维修图片）
            params.repairFileList = this.imagesList.map(item => ({
                type: 12,
                name: item.name,
                fileName: item.fileName,
                fileFormat: item.fileFormat,
                url: item.url
            }))
            this.$refs.uForm.validate(valid => {
                if (valid) {
                    this.$Http
                        .finish(params)
                        .then((res) => {
                            uni.redirectTo({
                                url: '/pages/service-detail/service-detail?id=' + this.detailId
                            })
                        })
                }
            })
        },
        haltSubmit(data) {
            this.form.halt = data[0].label;
            this.form.needStop = data[0].value;
        },
        // 完成时间
        endTimeSubmit(e) {
            this.form.repairEndTime = `${e.year}-${e.month}-${e.day} ${e.hour}:${e.minute}:${e.second}`;
        },
        // 删除成功
        uploadRemove(index, lists, name) {
            this.fileList = lists;
            // 同步移除已收集的图片，避免删除后仍提交给后端
            this.imagesList.splice(index, 1);
        },
        // 上传成功
        uploadSuccess(data, index, lists, name) {
            this.fileList = lists;
            // 后端返回 { code, data: 文件实体 }，只收集文件实体，避免把响应包装对象提交给后端
            if (data && data.data) {
                this.imagesList.push(data.data)
            }
        },

        getType() {
            this.$Http
                .fetchErrorTypeTree({
                    id: this.detailId
                })
                .then((res) => {
                    const temp = []
                    res.data.forEach(item => {
                        temp.push({
                            label: item.title,
                            value: item.id
                        })
                    })
                    this.badList = temp
                })
        },
        initData() {
            this.$Http
                .fetchRepairApplicationForm({
                    id: this.detailId
                })
                .then((res) => {
                    this.form.no = res.data.no;
                    this.form.category = res.data.category
                    this.category = this.categoryMap.find(item => item.value == res.data.category).label
                    this.form.userName = res.data.userName;
                    this.form.repairMinutes = res.data.minutes
                    this.form.repairRemark = res.data.repairRemark
                    this.form.descripitionType = this.descripitionMap[res.data.descripition]
                    this.form.repairContent = res.data.repairContent
                    this.form.repairErrorTypeId = res.data.repairErrorTypeId

                    this.form.badType = res.data.errorTypeName ? res.data.errorTypeName : ''
                });
        }
    }
};
</script>

<style lang="less" scoped>
.submit {
    align-items: center;
    justify-content: space-around;

    view {
        width: 240rpx;
        padding: 15rpx 0;
        border-radius: 40rpx;
        text-align: center;
    }
}

.footer {
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    z-index: 10000;
    border-top: 1rpx solid #f4f4f4;
    height: 100rpx;

    .common {
        padding: 15rpx 100rpx;
        border-radius: 40rpx;
        background-color: #0082ff;
        color: #fff;

        &:last-child {
            background-color: #fff;
            color: #0082ff;
            border: 1rpx solid #0082ff;
        }
    }
}
</style>
