<template>
    <view class="page-css">
        <view class="repair_detail">
            <view class="repair_title">提报信息</view>
            <u-form labelPosition="left" :rules="rules" ref="repairDetailsForm" :model="repairDetails"
                :label-width="200" class="repair_form">
                <u-form-item label="需求单号:" prop="requirementCode" :border-bottom="false">
                    <!-- <u-input v-model="repairDetails.requirementCode" type="text" :border="true"  /> -->
                    <betone-new-input label="" v-model="repairDetails.requirementCode" placeholder="请输入"
                        :disabled="disabled" />
                </u-form-item>
                <u-form-item label="提报单位:" prop="reportUnit" :border-bottom="false">
                    <!-- <u-input v-model="repairDetails.reportUnit" type="text" :border="true" :disabled="disabled" /> -->
                    <betone-new-input label="" v-model="repairDetails.reportUnit" placeholder="请输入"
                        :disabled="disabled" />
                </u-form-item>
                <u-form-item label="故障现象描述:" prop="faultDescribe" :border-bottom="false">
                    <!-- <u-input v-model="repairDetails.faultDescribe" type="textarea" :border="true"
                        :disabled="disabled" /> -->
                    <betone-new-input label="" v-model="repairDetails.faultDescribe" placeholder="请输入"
                        :disabled="disabled" />
                </u-form-item>
                <u-form-item label="故障位置:" prop="faultLocation" :border-bottom="false">
                    <!-- <u-input v-model="repairDetails.faultLocation" type="text" :border="true" :disabled="disabled" /> -->
                    <betone-new-input label="" v-model="repairDetails.faultLocation" placeholder="请输入"
                        :disabled="disabled" />
                </u-form-item>
                <u-form-item label="设备名称:" prop="deviceName" :border-bottom="false">
                    <!-- <u-input v-model="repairDetails.deviceName" type="text" :border="true" :disabled="disabled" /> -->
                    <betone-new-input label="" v-model="repairDetails.deviceName" placeholder="请输入"
                        :disabled="disabled" />
                </u-form-item>
                <u-form-item label="设备专业类型:" prop="faultType" :border-bottom="false">
                    <!-- <u-input v-model="repairDetails.faultType" type="text" :border="true" :disabled="disabled" /> -->
                    <betone-new-input label="" v-model="repairDetails.faultType" placeholder="请输入"
                        :disabled="disabled" />
                </u-form-item>
            </u-form>
        </view>
        <view class="repair_detail">
            <view class="repair_title">派单信息</view>
            <u-form labelPosition="left" :rules="sendRules" ref="sendOrderForm" :model="sendOrder" :label-width="200"
                class="repair_form">
                <u-form-item label="维修人员:" prop="name" :border-bottom="false" :required="true">
                    <u-input v-if="dataTypes == 2" v-model="sendOrder.name" type="select" :border="true"
                        @click="sendOrdersShow = true" :disabled="disabled" />
                    <betone-new-input v-if="dataTypes == 4" label="" v-model="sendOrder.name" placeholder="请输入"
                        :disabled="disabled" />
                </u-form-item>
                <u-form-item label="计划完成时间:" prop="planCompleteTime" :border-bottom="false">
                    <u-input v-if="dataTypes == 2" v-model="sendOrder.planCompleteTime" type="select"
                        @click="calendarShow = true" :border="true" placeholder="请选择时间" :disabled="disabled" />
                    <betone-new-input v-if="dataTypes == 4" label="" v-model="sendOrder.planCompleteTime"
                        placeholder="请输入" :disabled="disabled" />
                </u-form-item>
                <u-form-item label="客服意见:" prop="reportPeople" :border-bottom="false">
                    <u-input v-if="dataTypes == 2" v-model="sendOrder.customerOpinion" type="textarea" :border="true"
                        :disabled="disabled" />
                    <betone-new-input v-if="dataTypes == 4" label="" v-model="sendOrder.customerOpinion"
                        placeholder="请输入" :disabled="disabled" />
                </u-form-item>

                <u-form-item v-if="dataTypes == 4" label="是否申领物料:" prop="isNeedMaterials" :border-bottom="false"
                    :label-width="200" :isRequire="true">
                    <uni-data-checkbox v-model="sendOrder.isNeedMaterials"
                        :localdata="isMaterialList"></uni-data-checkbox>
                </u-form-item>

                <view class="selectForm clearfix" v-if="sendOrder.isNeedMaterials == 1">
                    <view class="form-item form-label">物料申领:</view>
                    <view class="form-item form-content">
                        <view class="select-box clearfix">
                            <view class="select-box-item clearfix" v-for="(item, index) in sendOrder.materialsData"
                                :key="index">
                                <view class="material-text">名称：{{ item.name }}</view>
                                <view class="material-text">规格：{{ item.rule }}</view>
                                <view class="material-text">型号：{{ item.xh }}</view>
                                <view class="material-text">数量：{{ item.goodsNum }}</view>
                                <view class="material-text">单位：{{ item.unit }}</view>
                                <view class="material-text">价格：{{ item.brand }}</view>
                            </view>
                        </view>
                        <u-button size="medium" :plain="true" style="margin-right: 32rpx;width:100%" type="primary"
                            @click="goodsSelect()">{{ sendOrder.materialsData.length > 0 ? '修改' : '添加' }}</u-button>
                    </view>
                </view>
                <u-form-item v-if="dataTypes == 4" label="备注:" prop="remark" :border-bottom="false">
                    <u-input v-model="sendOrder.remark" type="textarea" :border="true" />

                </u-form-item>
            </u-form>
        </view>
        <!-- btns -->
        <view class="repair-btn" style="margin-right: 32rpx;width:100%" v-if="dataTypes == 2">
            <u-button size="medium" @click="endOrderCancel()">取消</u-button>
            <u-button size="medium" type="primary" @click="sendOrderSubmit()">确定派单</u-button>
        </view>
        <view class="repair-4-btn" style="margin-right: 32rpx;width:100%" v-if="dataTypes == 4">
            <u-button size="medium" @click="endOrderCancel()">取消</u-button>
            <u-button size="medium" @click="turnShow = true">驳回</u-button>
            <u-button size="medium" type="primary" @click="repairOrderSubmit()">确定派单</u-button>
        </view>

        <!-- 选择维修人员 -->
        <u-select v-model="sendOrdersShow" :list="sendOrdersList" @confirm="sendOrdersConfirm" :isShowsearch="true"
            value-name="id" title="选择维修人员"></u-select>
        <!-- 选择时间 -->
        <u-calendar v-model="calendarShow" mode="date" @change="calendarChange" :disabled-dates="disabledDates"
            :min-date="minDate" :max-date="maxDate"></u-calendar>

        <!-- 维修人员物料选择 -->
        <betone-dialog v-model="aterialShow" height="900rpx">
            <view class="search-box">
                <betone-new-input v-model="goodsearchInfo.goodsName" placeholder="搜索物品名称" icon="search"
                    style="margin-bottom: 32rpx" @changevalue="searchGoodsData()" />
            </view>
            <scroll-view class="scroll-Y" @scrolltolower="goodsLower" scroll-y="true"
                style="max-height: 900rpx; width: auto; background-color: gainsboro;">
                <view class="material-box">
                    <view class="material-item" v-for="(item, index) in goodsTableData" :key="index">
                        <view class="title-wrapper">
                            <u-checkbox v-model="item.checked" shape="circle"></u-checkbox>
                        </view>
                        <view class="item-right">
                            <view class="material-title">
                                <text class="material-title-name">{{ item.name }}</text>
                                <text class="material-title-code">{{ item.code }}</text>
                                <text>库存数：{{ item.num }}</text>
                            </view>
                            <view class="material-text">品牌：{{ item.brand }}</view>
                            <view class="material-text">型号：{{ item.xh }}</view>
                            <view class="material-num">
                                <text>参数：{{ item.rule }}</text><u-number-box v-model="item.goodsNum"
                                    :step="1"></u-number-box>
                            </view>
                        </view>
                    </view>
                </view>
            </scroll-view>

            <view class="material-btn">
                <u-button size="medium" @click="aterialShow = false">取消</u-button>
                <u-button size="medium" type="primary" @click="goodsSubmit()">确认</u-button>
            </view>
        </betone-dialog>

        <!-- 维修人员驳回 -->
        <betone-modal v-model="turnShow" :title="'驳回原因'" @confirm="turnFn">
            <view class="modal-text">
                <betone-new-input v-model="repaiRejectReason" placeholder="请输入" style="margin-bottom: 32rpx" />
            </view>
        </betone-modal>
    </view>
</template>
<script>
import { dateFormat } from '@/utils/util.js'

export default {
    computed: {
        dataTypes() {
            return this.$store.state.dataType
        },
        disabled() {
            return this.$store.state.dataType == 2 ? false : true
        }
    },

    data() {
        return {
            disabledDates: {
                to: new Date() // 禁用今天之前的日期
            },
            minDate: null,
            maxDate: null,
            userInfo: {},//用户信息
            orderId: '',//需求提报id
            detailForm: {},//详情信息
            rules: {},
            repairDetails: {
                requirementCode: '',//需求单号
                reportUnit: '',//提报单位
                faultDescribe: '',//故障现象描述
                faultLocation: '',//故障位置
                deviceName: '',//设备名称
                faultType: '',//故障专业类型
            },
            sendOrder: {
                repairPerson: '',//维修人员  id
                name: '',//维修人员名字
                planCompleteTime: '',//计划完成时间
                customerOpinion: '',//客服意见
                isNeedMaterials: null,//是否申领物料
                materialsData: [],//物料列表
                remark: '',//备注
            },
            sendRules: {
                name: {
                    type: "string",
                    required: true,
                    message: "请选择维修人员",
                    trigger: ["blur", "change"],
                }
            },

            sendOrdersShow: false,//派单弹框
            sendOrdersList: [],

            calendarShow: false,//时间选择框

            isMaterialList: [
                {
                    text: '是',
                    value: 1
                },
                {
                    text: '否',
                    value: 2
                }
            ],
            aterialShow: false,//物料选择弹框
            goodsearchInfo: {
                goodsName: '',
            },
            goodsTableData: [],
            goodspage: {
                current: 1,
                size: 10,
            },
            isGoodsNomore: false,
            turnShow: false,//驳回弹框
            repaiRejectReason: '',//驳回弹框
        }
    },
    onReady() {
        this.$refs.sendOrderForm.setRules(this.sendRules);
    },
    onShow() {
        this.getRepairPersons()//获取维修人员列表
        this.orderId = this.$route.query.id
        this.getDtails()
        this.userInfo = uni.getStorageSync("userinfo");
        // 维修人员 获取物料选择
        if (this.dataTypes == 4) {
            this.getGoodsList()
        }
        this.initDate()
    },
    methods: {
        getDtails() {
            this.$u.api.getBreakdownInfo({ id: this.orderId }).then(res => {
                if (res.code == 200) {
                    this.detailForm = res.data
                    this.repairDetails.requirementCode = this.detailForm.requirementCode
                    this.repairDetails.reportUnit = this.detailForm.reportUnit
                    this.repairDetails.faultDescribe = this.detailForm.faultDescribe
                    this.repairDetails.faultLocation = this.detailForm.faultLocation
                    this.repairDetails.deviceName = this.detailForm.deviceName
                    this.repairDetails.faultType = this.detailForm.faultType
                    this.sendOrder.name = this.detailForm.repairPersonName
                    this.sendOrder.repairPerson = this.detailForm.repairPerson
                    this.sendOrder.planCompleteTime = this.detailForm.planCompleteTime.split(' ')[0]
                    this.sendOrder.customerOpinion = this.detailForm.customerOpinion
                    this.sendOrder.remark = this.detailForm.remark
                    // repairPersonName

                }

            })
        },
        // 维修人员
        getRepairPersons() {
            this.$u.api.getRepairPersons().then(res => {
                if (res.code == 200) {
                    let data_ = res.data
                    data_.forEach(i => {
                        this.sendOrdersList.push({ ...i, label: i.name })
                    })
                }
            })
        },
        // 选择维修人员
        sendOrdersConfirm(e) {
            // 获取维修人员
            this.sendOrder.name = e[0].label
            this.sendOrder.repairPerson = e[0].value
        },
        calendarChange(e) {
            this.sendOrder.planCompleteTime = e.result
        },
        endOrderCancel() {
            uni.navigateBack({
                delta: 1 // 默认值是1，表示回退一个页面
            })
        },
        // 客服接单  确认
        sendOrderSubmit() {
            this.$refs.sendOrderForm.validate(valid => {
                if (valid) {
                    let query = {
                        id: this.orderId,
                        reportUnit: this.repairDetails.reportUnit,
                        faultDescribe: this.repairDetails.faultDescribe,
                        faultLocation: this.repairDetails.faultLocation,
                        faultType: this.repairDetails.faultType,
                        deviceName: this.repairDetails.deviceName,
                        dispatchTime: dateFormat("yyyy-MM-dd hh:mm:ss", new Date()),
                        status: this.dataTypes == 2 ? 2 : this.dataTypes == 3 ? 2 : this.dataTypes == 4 ? 3 : '',
                        remark: this.repairDetails.remark,
                        repairPerson: this.sendOrder.repairPerson,
                        planCompleteTime: this.sendOrder.planCompleteTime ? this.sendOrder.planCompleteTime + ' 00:00:00' : '',
                        customerOpinion: this.sendOrder.customerOpinion
                    }
                    this.$u.api.editData(query).then(res => {
                        if (res.code == 200) {
                            uni.showToast({ title: "派单成功", icon: "none" });
                            uni.navigateBack({
                                delta: 1 // 默认值是1，表示回退一个页面
                            })
                        }
                    })
                } else {
                    console.log('验证失败');
                }
            });
        },
        // 物料搜索
        searchGoodsData() {
            // selectGoodsList

        },
        // 弹框滑到底部加载数据
        goodsLower() {
            if (this.isGoodsNomore) {
                return;
            }
            this.goodspage.current++;
            this.getGoodsList();
        },
        // 获取物料列表
        getGoodsList() {
            let query_ = {
                ...this.goodspage
            }
            this.$u.api.getGoodsList(query_).then(res => {
                if (res.code == 200) {
                    var totalPage = res.data.total;
                    var newOrders = res.data.records;
                    newOrders.forEach(element => {
                        // element.rule = element.rule == '' ? 0 : Number(element.rule)
                        this.$set(element, 'goodsNum', 0)
                        this.$set(element, 'checked', false)
                    });
                    this.goodsTableData = [...this.goodsTableData, ...(res.data.records || [])];
                    if (newOrders.length == 0) {
                        // this.loadingState = "nomore";
                        this.isGoodsNomore = true;
                    }
                    if (totalPage == this.goodsTableData.length) {
                        // this.loadingState = "nomore";
                        this.isGoodsNomore = true;
                    }
                }
            })
        },
        // 物料选择确定
        goodsSubmit() {
            let selected = this.goodsTableData.filter(i => {
                return i.checked
            })
            this.sendOrder.materialsData = JSON.parse(JSON.stringify(selected))
            this.aterialShow = false
        },
        goodsSelect() {
            this.aterialShow = true
            // 判断之前是否有选中的
            // 默认给列表全部赋值非选中状态
            // 如果有则对比数组  加载选中状态  this.goodsTableData
            this.goodsTableData.forEach(i => {
                i.checked = false
            })
            if (this.sendOrder.materialsData.length > 0) {
                this.goodsTableData.forEach(i => {
                    this.sendOrder.materialsData.forEach(v => {
                        if (i.id == v.id) {
                            i.checked = true
                        }
                    })
                })
            }
        },
        // 维修人员接单确认
        repairOrderSubmit() {
            let query = {
                id: this.orderId,
                reportUnit: this.repairDetails.reportUnit,
                dispatchTime: this.detailForm.dispatchTime,
                planCompleteTime: this.detailForm.planCompleteTime,
                repairPerson: null,
                status: this.dataTypes == 2 ? 2 : this.dataTypes == 3 ? 2 : this.dataTypes == 4 ? 3 : '',
                remark: this.sendOrder.remark,
                customerOpinion: this.detailForm.customerOpinion
            }
            // 判断是否申领物料  调用申领接口
            if (this.sendOrder.isNeedMaterials == 1 && this.sendOrder.materialsData.length <= 0) {
                uni.showToast({ title: "请选择需要的申领材料", icon: "none" });
                return false
            }
            // 申领物料 数量的判断
            if (this.sendOrder.materialsData.find(item => item.goodsNum == 0)) {
                uni.showToast({ title: "申领数量不能为0", icon: "none" });
                return false
            }
            let data = []
            console.log('this.materialsData', this.sendOrder.materialsData)
            this.sendOrder.materialsData.map(item => {
                data.push({
                    productId: item.productName,//物资id
                    productName: item.name,	//物资名称
                    brand: item.brand,//品牌
                    xh: item.xh,//型号
                    rule: item.rule,//参数
                    applyNum: item.applyNum,//领用数量
                })
            })
            let query1 = {
                details: data,
                applyUserId: this.userInfo.user_id,	//申领人Id
                applyUser: this.userInfo.user_name,	//申领人
                applyTime: dateFormat("yyyy-MM-dd hh:mm:ss", new Date()),//申领时间(yyyy-MM-dd HH:mm:ss)
                status: 0,
                workId: this.orderId,
            }
            this.$u.api.applySave(query1).then(res => {

            })

            this.$u.api.editData(query).then(res => {
                if (res.code == 200) {
                    uni.showToast({ title: "派单成功", icon: "none" });
                    uni.navigateBack({
                        delta: 1 // 默认值是1，表示回退一个页面
                    })
                }
            })
        },
        // 维修人员驳回
        turnFn() {
            if (this.repaiRejectReason == '') {
                uni.showToast({ title: "请输入驳回原因", icon: "none" });
                return false
            }
            let query = {
                id: this.orderId,
                repaiRejectReason: this.repaiRejectReason,
                status: 7
            }
            this.$u.api.repairReject(query).then(res => {
                if (res.code == 200) {
                    this.turnShow = false
                    uni.showToast({ title: "驳回成功", icon: "none" });
                    uni.navigateBack({
                        delta: 1 // 默认值是1，表示回退一个页面
                    })
                }
            })
        },

        initDate() {

            let date = new Date();
            let year = date.getFullYear();

            let month = date.getMonth() + 1;

            let day = date.getDate();

            if (month < 10) {

                month = "0" + month;

            }

            if (day < 10) {

                day = "0" + day;
            }

            let minyear = year - 1;

            this.minDate = minyear + "-" + month + "-" + day;

            //let maxyear = year + 1;

            this.maxDate = year + 1 + "-" + month + "-" + day; // 最大日期可选到一年后

            //this.maxDate = year  + '-'+ month +'-' + day; // 最大日期可选到今天

        },


    }
}
</script>
<style lang="scss" scoped>
.page-css {
    padding: 0;
    height: 100%;
    overflow: auto;

    .repair_detail {
        margin: 32rpx 24rpx 20rpx;
        border-radius: 20rpx;
        background-color: rgba(255, 255, 255, 1);
        padding: 6rpx 0 34rpx;

        .repair_title {
            line-height: 60rpx;
            color: rgba(0, 0, 0, 1);
            font-size: 32rpx;
            text-align: left;
            font-family: SourceHanSansSC-bold;
            margin: 18rpx 0 0rpx 20rpx;
            font-weight: bold;
        }

        .repair_form {
            padding: 0 18rpx;
        }
    }

    .repair-btn {
        width: 100%;
        display: flex;
        justify-content: space-around;
        /* 水平均匀分布 */
        margin-top: 32rpx;
        padding: 0 32rpx;
        margin-bottom: 32rpx;

        /deep/.u-btn {
            width: 47%;
        }
    }

    .repair-4-btn {
        width: 100%;
        display: flex;
        justify-content: space-around;
        /* 水平均匀分布 */
        margin-top: 32rpx;
        padding: 0 32rpx;
        margin-bottom: 32rpx;

        /deep/.u-btn {
            width: 32%;
        }
    }

    .selectForm {
        width: 100%;
        padding: 26rpx;
        line-height: 60rpx;
        display: flex;
        flex-direction: row;

        .form-item {
            float: left;
            width: calc(100% - 26rpx - 26rpx - 200rpx);

            .material-text {
                width: 50%;
                float: left;
            }
        }

        .form-content {
            flex: 1;
        }

        .form-label {
            width: 200rpx;
            text-align: center;
        }
    }

    .material-box {
        flex: 1;
        background: #fff;
        margin: 0;
        overflow: auto;
        // padding-bottom: 32rpx;

        .material-item {
            height: 300rpx;
            border-radius: 20rpx;
            background-color: rgba(249, 249, 249, 1);
            margin: 32rpx 0 0;
            padding: 32rpx;
            display: flex;
            flex-direction: row;

            .title-wrapper {}

            .item-right {
                flex: 1;

                .material-title {
                    display: flex;
                    flex-direction: row;
                    color: rgba(108, 108, 108, 1);
                    font-size: 28rpx;
                    line-height: 60rpx;

                    .material-title-name {
                        color: rgba(51, 51, 51, 1);
                        font-size: 36rpx;
                        font-weight: 550;
                        padding-right: 16rpx;
                    }

                    .material-title-code {
                        flex: 1;
                    }
                }

                .material-text {
                    line-height: 60rpx;
                    color: rgba(108, 108, 108, 1);
                    font-size: 28rpx;
                }

                .material-num {
                    display: flex;
                    flex-direction: row;
                    justify-content: space-between;
                }
            }

        }


    }

    .material-btn {
        width: 100%;
        display: flex;
        justify-content: space-between;
        /* 水平均匀分布 */
        margin-top: 32rpx;
        padding: 0 32rpx;

        /deep/.u-btn {
            width: 48%;
        }
    }

    .select-box {
        width: 100%;

        .select-box-item {
            width: 100%;
            border-radius: 20rpx;
            background-color: rgba(249, 249, 249, 1);
            margin-bottom: 32rpx;
            line-height: 60rpx;
            color: rgba(108, 108, 108, 1);
            font-size: 28rpx;
            padding: 24rpx;
        }
    }

}
</style>