<template>
    <div>
        <!-- 设备台账全部信息 -->
        <el-dialog v-if="visible" :title="title" width="60%" custom-class="dialog-max" top="5vh" center
            :before-close="dialogClose" :visible.sync="visible" :close-on-click-modal="false" :append-to-body="true">
            <el-form ref="deviceLedgerForm" :model="deviceLedgerForm" :rules="deviceLedgerRules" label-width="180px"
                label-position="left">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="设备类别" prop="deviceType" label-width="22%">
                            <el-input v-model="deviceLedgerForm.deviceType" disabled placeholder="请选择设备类别" maxlength="10">
                                <el-button type="primary" slot="append" icon="el-icon-search"
                                    @click="chooseDeviceType">选择</el-button>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="设备名称" prop="deviceName" label-width="22%">
                            <el-input v-model="deviceLedgerForm.deviceName" placeholder="设备名称" maxlength="10" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="设备编号" prop="deviceNum" label-width="22%">
                            <el-input v-model="deviceLedgerForm.deviceNum" placeholder="设备编号" maxlength="10" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="设备等级" prop="deviceLevel" label-width="22%">
                            <el-select clearable v-model="deviceLedgerForm.deviceLevel" placeholder="请选择设备等级">
                                <el-option v-for="deviceLevel in deviceLevelList" :key="deviceLevel.id"
                                    :label="deviceLevel.dictValue" :value="deviceLevel.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="设备规格型号" prop="deviceModel" label-width="30%">
                            <el-input v-model="deviceLedgerForm.deviceModel" placeholder="设备规格型号" maxlength="10" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="设备位置" prop="deviceLocation" label-width="22%">
                            <el-input v-model="deviceLedgerForm.deviceLocation" placeholder="设备位置" maxlength="10" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="设备健康状态" prop="deviceHealth" label-width="30%">
                            <el-select clearable v-model="deviceLedgerForm.deviceHealth" placeholder="请选择健康状态">
                                <el-option v-for="deviceHealth in deviceHealthList" :key="deviceHealth.id"
                                    :label="deviceHealth.dictValue" :value="deviceHealth.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="使用部门" prop="deviceDeptName" label-width="22%">
                            <el-input v-model="deviceLedgerForm.deviceDeptName" disabled placeholder="请选择使用部门" maxlength="10">
                                <el-button slot="append" icon="el-icon-search" @click="chooseDept"></el-button>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="责任人" prop="devicePersonName" label-width="22%">
                            <el-input v-model="deviceLedgerForm.devicePersonName" disabled placeholder="请选择责任人" maxlength="10">
                                <el-button type="primary" slot="append" icon="el-icon-search"
                                    @click="chooseDevicePerson">选择</el-button>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="购买时间" prop="buyTime" label-width="22%">
                            <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="deviceLedgerForm.buyTime"
                                type="date" placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="投用时间" prop="useTime" label-width="22%">
                            <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="deviceLedgerForm.useTime"
                                type="date" placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="供应商" prop="supplier" label-width="22%">
                            <el-select clearable v-model="deviceLedgerForm.supplier" placeholder="请选择供应商">
                                <el-option v-for="supplier in supplierList" :key="supplier.id" :label="supplier.dictValue"
                                    :value="supplier.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="制造商" prop="manufacturer" label-width="22%">
                            <el-select clearable v-model="deviceLedgerForm.manufacturer" placeholder="请选择制作商">
                                <el-option v-for="manufacturer in manufacturerList" :key="manufacturer.id"
                                    :label="manufacturer.dictValue" :value="manufacturer.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="设备序列号" prop="serialNumber" label-width="30%">
                            <el-input v-model="deviceLedgerForm.serialNumber" placeholder="设备位置" maxlength="10" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="运行条件" prop="runCondition" label-width="22%">
                            <el-input v-model="deviceLedgerForm.runCondition" placeholder="设备位置" maxlength="10" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="使用状态" prop="deviceState" label-width="22%">
                            <el-select clearable v-model="deviceLedgerForm.deviceState" placeholder="请选择使用状态">
                                <el-option v-for="deviceState in deviceStateList" :key="deviceState.id"
                                    :label="deviceState.dictValue" :value="deviceState.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="单位" prop="deviceUnit" label-width="22%">
                            <el-select clearable v-model="deviceLedgerForm.deviceUnit" placeholder="请选择单位">
                                <el-option v-for="deviceUnit in deviceUnitList" :key="deviceUnit.id"
                                    :label="deviceUnit.dictValue" :value="deviceUnit.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="设备技术参数" prop="technicalDataList" label-width="22%">
                            <el-upload class="upload-demo" action="" :multiple="true" :auto-upload="false"
                                :on-change="handleChangeTechnical" :on-remove="handleRemoveTechnical"
                                :file-list="deviceLedgerForm.technicalDataList" list-type="text">
                                <el-button size="small" type="primary">点击上传</el-button>
                                <img />
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="设备图片" prop="pictureList" label-width="22%">
                            <el-upload class="upload-demo" action="" :multiple="true" :auto-upload="false"
                                :on-change="handleChangePicture" :on-remove="handleRemovePicture"
                                :file-list="deviceLedgerForm.pictureList" list-type="picture" accept=".jpg,.jpeg,.png">
                                <el-button size="small" type="primary">点击上传</el-button>
                                <!-- <div>
                                    deviceLedgerForm.pictureList
                                    <img v-for="picture in pictureList" :src="URL.createObjectURL(picture.raw)" />
                                </div> -->
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" v-model="deviceLedgerForm.remark" placeholder="请输入备注"
                        maxlength="100"></el-input>
                </el-form-item>
                <el-form-item style="text-align: center;">
                    <el-button v-show="!queryShow" type="primary" @click="saveDeviceLedgerEvent">确定</el-button>
                    <el-button v-show="queryShow" type="primary" @click="queryDeviceLedgerEvent">查询</el-button>
                    <!-- <el-button type="primary" @click="resetForm('deviceTypeForm')">重置</el-button> -->
                    <el-button @click="dialogClose">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 选择设备类别 -->
        <ChooseDeviceType ref="chooseDeviceType" @receiveChooseDeviceType="receiveChooseDeviceType"></ChooseDeviceType>
        <!-- 选择部门 -->
        <ChooseDept ref="chooseDept" @receiveChooseDept="receiveChooseDept"></ChooseDept>
        <!-- 选择责任人 -->
        <ChooseStaff ref="chooseDevicePerson" @receiveChooseStaff="receiveChooseStaff"></ChooseStaff>
    </div>
</template>

<script>
import SelectTree from '@/components/SelectTree/index.vue'
import ChooseDeviceType from '@/views/device/deviceType/chooseDeviceType.vue'
import ChooseDept from '@/views/system/dept/chooseDept.vue'
import ChooseStaff from '@/views/system/staff/chooseStaff.vue'
import { getDictListByType } from '@/api/system/dict';
import {
    addDeviceLedger,
    updateDeviceLedger
} from '@/api/device/deviceLedger'
export default {
    components: {
        SelectTree,
        ChooseDeviceType,
        ChooseDept,
        ChooseStaff
    },
    mounted() {
        this.getDictListByType('device_level', (data) => {
            this.deviceLevelList = data
        })
        this.getDictListByType('device_health', (data) => {
            this.deviceHealthList = data
        })
        this.getDictListByType('supplier', (data) => {
            this.supplierList = data
        })
        this.getDictListByType('manufacturer', (data) => {
            this.manufacturerList = data
        })
        this.getDictListByType('device_state', (data) => {
            this.deviceStateList = data
        })
        this.getDictListByType('device_unit', (data) => {
            this.deviceUnitList = data
        })
    },
    data() {
        return {
            visible: false,
            title: '新增设备台账',
            queryShow: false,
            //表单参数
            deviceLedgerForm: {
                id: null,
                directoryId: null,
                deviceTypeId: null,
                deviceType: null,
                deviceName: null,
                deviceNum: null,
                deviceLevel: null,
                deviceModel: null,
                deviceLocation: null,
                deviceHealth: null,
                deviceDeptId: null,
                deviceDeptName: null,
                devicePerson: null,
                devicePersonName: null,
                buyTime: null,
                useTime: null,
                supplier: null,
                manufacturer: null,
                serialNumber: null,
                technicalDataList: [],
                runCondition: null,
                deviceState: null,
                pictureList: [],
                unit: null,
                remark: null
            },
            //字典回显参数
            deviceLevelList: [],
            deviceHealthList: [],
            supplierList: [],
            manufacturerList: [],
            deviceStateList: [],
            deviceUnitList: [],
            //设备技术参数得到的文件
            technicalDataFiles: [],
            //图片上传得到的文件
            pictureFiles: [],
            //修改时，删除的技术参数文件名
            delTechnicalNameList: [],
            //修改时，删除的图片文件名
            delPictureNameList: [],
            deviceLedgerRules: {
                deviceType: [
                    { required: true, message: '设备类别不能为空', trigger: 'blur' }
                ],
                deviceName: [
                    { required: true, message: '设备名称不能为空', trigger: 'blur' }
                ],
                deviceNum: [
                    { required: true, message: '设备编号不能为空', trigger: 'blur' }
                ],
                deviceLevel: [
                    { required: true, message: '设备等级不能为空', trigger: 'blur' }
                ],
                deviceModel: [
                    { required: true, message: '设备规格型号不能为空', trigger: 'blur' }
                ],
                deviceLocation: [],
                deviceHealth: [
                    { required: true, message: '设备健康状态不能为空', trigger: 'blur' }
                ],
                deviceDeptName: [
                    { required: true, message: '使用部门不能为空', trigger: 'blur' }
                ],
                devicePersonName: [
                    { required: true, message: '责任人不能为空', trigger: 'blur' }
                ],
                buyTime: [],
                useTime: [
                    { required: true, message: '投用时间不能为空', trigger: 'blur' }
                ],
                supplier: [],
                manufacturer: [],
                serialNumber: [],
                runCondition: [],
                deviceState: [],
                deviceUnit: [],
            }
        }
    },
    methods: {
        /** 关闭弹出层 */
        dialogClose() {
            this.resetForm('deviceLedgerForm')
            this.$emit('getDeviceLedgerPage')
            this.visible = false
            this.queryShow = false
        },
        /** 重置表单 */
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        /** 获取字典数据 */
        getDictListByType(params, callback) {
            getDictListByType({ keyType: params }).then(res => {
                callback(res.data);
            })
        },
        /** 高级查询 */
        queryDeviceLedgerEvent() {

        },
        /** 保存设备台账 */
        saveDeviceLedgerEvent() {
            this.$refs['deviceLedgerForm'].validate((valid) => {
                if (valid) {
                    if (!this.deviceLedgerForm.id) {
                        this.addDeviceLedger()
                    } else {
                        this.updateDeviceLedger()
                    }
                }
            })
        },
        /** 新增设备台账 */
        addDeviceLedger() {
            const formData = new FormData()
            Object.keys(this.deviceLedgerForm).forEach(key => {
                if (this.deviceLedgerForm[key] instanceof Array) {
                    // 如果是数组就循环加入表单，key保持相同即可，这就是表达单的数组
                    // this.deviceLedgerForm[key].forEach(item => {
                    //     formData.append(key, item)
                    // })
                } else {
                    if (this.deviceLedgerForm[key]) {
                        // 如果不是数组就直接追加进去
                        formData.append(key, this.deviceLedgerForm[key])
                    }
                }
            })
            this.technicalDataFiles.map(item => {
                if (item.raw) {
                    formData.append("technicalDataFiles", item.raw);
                }
            });
            this.pictureFiles.map(item => {
                if (item.raw) {
                    formData.append("pictureFiles", item.raw);
                }
            });
            addDeviceLedger(formData).then(res => {
                if (!res || !res.data) {
                    this.$message({
                        message: '新增设备台账失败！',
                        type: 'warning'
                    })
                    return
                }
                this.$message({
                    message: '新增设备台账成功！',
                    type: 'success'
                })
                this.dialogClose()
            })
        },
        /** 修改设备台账 */
        updateDeviceLedger() {
            const formData = new FormData()
            Object.keys(this.deviceLedgerForm).forEach(key => {
                if (this.deviceLedgerForm[key] instanceof Array) {
                    // 如果是数组就循环加入表单，key保持相同即可，这就是表达单的数组
                    // this.deviceLedgerForm[key].forEach(item => {
                    //     formData.append(key, item)
                    // })
                } else {
                    if (this.deviceLedgerForm[key]) {
                        // 如果不是数组就直接追加进去
                        formData.append(key, this.deviceLedgerForm[key])
                    }
                }
            })
            //将新上传的文件添加到FormData中
            this.technicalDataFiles.map(item => {
                if (item.raw) {
                    formData.append("technicalDataFiles", item.raw);
                }
            });
            this.pictureFiles.map(item => {
                if (item.raw) {
                    formData.append("pictureFiles", item.raw);
                }
            });
            this.delTechnicalNameList.map(item => {
                formData.append("delTechnicalNameList", item);
            })
            this.delPictureNameList.map(item => {
                formData.append("delPictureNameList", item);
            })
            updateDeviceLedger(formData).then(res => {
                if (!res || !res.data) {
                    this.$message({
                        message: '修改设备台账失败！',
                        type: 'warning'
                    })
                    return
                }
                this.$message({
                    message: '修改设备台账成功！',
                    type: 'success'
                })
                this.dialogClose()
            })
        },
        /** 选择设备类别 */
        chooseDeviceType() {
            this.$refs.chooseDeviceType.visible = true
        },
        /** 接收选择设备类别传过来的值 */
        receiveChooseDeviceType(data) {
            this.deviceLedgerForm.deviceTypeId = data.id
            this.deviceLedgerForm.deviceType = data.deviceType
        },
        /** 选择部门 */
        chooseDept() {
            this.$refs.chooseDept.visible = true
        },
        /** 接收选择部门传过来的值 */
        receiveChooseDept(data) {
            this.deviceLedgerForm.deviceDeptId = data.id
            this.deviceLedgerForm.deviceDeptName = data.departmentName
        },
        /** 选择责任人 */
        chooseDevicePerson() {
            this.$refs.chooseDevicePerson.visible = true
        },
        receiveChooseStaff(data) {
            this.deviceLedgerForm.devicePerson = data.id
            this.deviceLedgerForm.devicePersonName = data.staffName
        },
        /** 设备技术参数改变 */
        handleChangeTechnical(file, fileList) {
            const obj = new Object();
            obj.url = file.url;
            obj.name = file.name;
            this.deviceLedgerForm.technicalDataList.push(obj)
            this.technicalDataFiles = fileList
        },
        /** 设备技术参数移除 */
        handleRemoveTechnical(file, fileList) {
            this.deviceLedgerForm.technicalDataList = this.deviceLedgerForm.technicalDataList.filter(item => item.url !== file.url)
            let url = file.url
            this.delTechnicalNameList.push(url.substring(url.indexOf(process.env.VUE_APP_BASE_API + "/") + (process.env.VUE_APP_BASE_API + "/").length))
        },
        /** 设备图片状态改变 */
        handleChangePicture(file, fileList) {
            const obj = new Object();
            obj.url = file.url;
            obj.name = file.name;
            this.deviceLedgerForm.pictureList.push(obj)
            this.pictureFiles = fileList
        },
        /** 设备图片移除文件 */
        handleRemovePicture(file, fileList) {
            this.deviceLedgerForm.pictureList = this.deviceLedgerForm.pictureList.filter(item => item.url !== file.url)
            let url = file.url
            this.delPictureNameList.push(url.substring(url.indexOf(process.env.VUE_APP_BASE_API + "/") + (process.env.VUE_APP_BASE_API + "/").length))
        }
    }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.dialog-max {
    height: 90vh;

    .el-dialog__body {
        height: 77vh;
        overflow: auto;
    }
}

.el-upload-list {
    // height: 40px;
    overflow: auto;
}
</style>