<template>
    <div>
        <el-form ref="form" :model="addForm" :rules="addRules" label-width="120px" label-position="left"
            style="height: 500px;overflow: auto;">
            <div>
                <div style="color: #101010;font-size: 20px;font-weight: 550;margin-bottom: 20px;">基本信息</div>
                <el-form-item label="单位名称" prop="unitId" v-if="title == '新建'">
                    <el-select style="width:98%" placeholder="请选择单位名称" v-model="addForm.unitId" @change="changeUnit">
                        <el-option v-for="item in unitData" :key="item.id" :label="item.title"
                            :value="item.id"></el-option>
                        <!-- <el-option label="畜牧局实验室" value="2"></el-option> -->
                    </el-select>
                </el-form-item>
                <el-form-item label="单位名称" prop="unitNam" v-if="title == '查看' || title == '编辑'">
                    <el-input v-model="addForm.unitName" disabled></el-input>
                </el-form-item>
            </div>
            <div>
                <div style="color: #101010;font-size: 20px;font-weight: 550;margin-bottom: 20px;">巡检内容</div>
                <el-form-item label="巡检标题" prop="content">
                    <el-input style="width: 98%;" type="textarea" v-model="addForm.content" placeholder="请输入巡检标题"
                        :disabled="title == '查看'"></el-input>
                </el-form-item>
                <el-form-item label="楼层">
                    <div style="display: flex;">
                        <div v-for="item in floorArr" :key="item.id" @click="clickFloor(item)"
                            style="padding: 0px 15px;border: 1px solid #bbbbbb; height: 30px;display: flex;align-items: center;justify-content: center;margin-right: 10px;border-radius: 3px;cursor: pointer;"
                            :style="{ background: item.id == activeFloor ? '#3a62d7' : '', color: item.id == activeFloor ? '#fff' : '', borderColor: item.id == activeFloor ? '#3a62d7' : '#bbb' }">
                            {{ item.deptName }}
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="房间">
                    <div style="display: flex;">
                        <div v-for="item in roomArr" :key="item.id" @click="clickRoom(item)"
                            style="padding: 0px 15px;border: 1px solid #bbbbbb; height: 30px;display: flex;align-items: center;justify-content: center;margin-right: 10px;border-radius: 3px;cursor: pointer;"
                            :style="{ background: item.id == activeRoom ? '#3a62d7' : '', color: item.id == activeRoom ? '#fff' : '', borderColor: item.id == activeRoom ? '#3a62d7' : '#bbb' }">
                            {{ item.deptName }}
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="巡检配置">
                    <el-table :data="addForm.tableData" border style="width: 100%" :span-method="objectSpanMethod"
                        v-loading="isLoad">
                        <el-table-column width="50" align="center">
                            <template slot="header" slot-scope="scope">
                                <div @click="addColumn()"
                                    style="width:30px;height: 30px;background: #409eff;border-radius: 50%;cursor: pointer;display: flex;align-items: center;justify-content: center;">
                                    <i style="color:#fff;font-size: 20px;" class="el-icon-plus"></i>
                                </div>
                            </template>
                            <template slot-scope="scope">
                                <div @click="deleteColumn(scope.row, scope.$index)"
                                    style="width:30px;height: 30px;background: #f56c6c;border-radius: 50%;cursor: pointer;display: flex;align-items: center;justify-content: center;">
                                    <i style="color:#fff;font-size: 20px;" class="el-icon-delete"></i>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="deviceId" align="center" label="设备">
                            <template slot-scope="scope">
                                <el-select placeholder="请选择设备" :disabled="title == '查看'" v-model="scope.row.deviceId"
                                    @change="((val) => { changeDevice(val, scope.$index) })">
                                    <el-option v-for="item in deviceList" :disabled="item.disabled" :key="item.id"
                                        :label="item.name" :value="item.id"></el-option>
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column prop="checkContent" align="center" label="巡检内容">
                            <template slot-scope="scope">
                                <el-input placeholder="请输入巡检内容" :disabled="title == '查看'"
                                    v-model="scope.row.checkContent"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="craft" align="center" label="工艺要求">
                            <template slot-scope="scope">
                                <el-input v-model="scope.row.craft" :disabled="title == '查看'"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="period" align="center" label="巡检周期">
                            <template slot-scope="scope">
                                <el-select placeholder="请选择巡检周期" :disabled="title == '查看'" v-model="scope.row.period">
                                    <!-- <el-option label="日" value="001"></el-option>
                                    <el-option label="月" value="002"></el-option>
                                    <el-option label="年" value="003"></el-option> -->
                                    <el-option v-for="item in periodArr" :key="item.dictKey" :label="item.dictValue"
                                        :value="parseInt(item.dictKey)"></el-option>
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column prop="startTime" align="center" label="开始时间">
                            <template slot-scope="scope">
                                <el-date-picker style="width: 100%;" v-model="scope.row.startTime" type="date"
                                    @change="((val) => changeStartTime(val, scope.$index))" placeholder="请选择开始时间"
                                    format="yyyy-MM-dd" value-format="yyyy-MM-dd" :disabled="title == '查看'">
                                </el-date-picker>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <el-form-item label="维保合同" prop="contractFile">
                    <el-upload class="upload-demo" action="/api/blade-resource/oss/endpoint/put-file"
                        :on-success="handleSuccess" :on-remove="handleRemove" :headers="headers" multiple
                        :disabled="title == '查看'" accept=".docx,.pdf," :limit="3" :on-exceed="handleExceed"
                        :file-list="imgList">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">支持上传docx、pdf文件，且不超过10M</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="实验室图纸" prop="drawingFile">
                    <el-upload class="upload-demo" action="/api/blade-resource/oss/endpoint/put-file"
                        :on-success="handledrawSuccess" :on-remove="handledrawRemove" :headers="headers" multiple
                        list-type="picture-card" :disabled="title == '查看'" accept=".png,.jpeg,.jpg," :limit="3"
                        :on-exceed="handleExceed" :file-list="drawList">
                        <i class="el-icon-plus"></i>
                        <!-- <el-button size="small" type="primary">点击上传</el-button> -->
                        <div slot="tip" class="el-upload__tip">支持上传png、jpeg、jpg文件，且不超过10M</div>
                    </el-upload>
                </el-form-item>
            </div>
        </el-form>
    </div>
</template>

<script>
import website from '@/config/website';
import { getToken, removeToken, removeRefreshToken } from '@/util/auth';
import { getDeepData, getDeviceLists } from '@/api/labManagement/inspectionManagement'
import { getDeviceList, getDetail } from '@/api/device/device'
import { getChildList } from '@/api/system/dictbiz'
import func from "@/util/func";
export default {
    name: 'addDialog',
    props: {
        unitData: Array,
        detailForm: Object,
        title: String
    },
    data() {
        return {
            isLoad: false,
            addForm: {
                tableData: []
            },
            addRules: {
                unitId: { required: true, message: '请选择单位', trigger: 'blur' },
                content: { required: true, message: '请输入巡检内容', trigger: 'blur' }
            },
            filesList: [],
            drawList: [],
            drawfiles: [],
            imgList: [],
            periodArr: [],
            floorArr: [],
            activeFloor: '',
            roomArr: [],
            activeRoom: '',
            tableData: [],
            deviceCurrent: 1,
            deviceSize: 100,
            deviceList: [],
            spanArr: [],
            pos: 0,
            currentIndex: 0,
            headers: {},
            labId: ''

        }
    },
    watch: {
        detailForm(newVal, oldVal) {
            if (JSON.stringify(newVal) != '{}') {
                this.deviceList = []
                this.detailForm = newVal
                this.addForm = {
                    ...this.detailForm,
                    unitId: newVal.deptId,
                    unitName: newVal.deptName,
                    content: newVal.planContent,
                }
                this.floorArr = []
                this.roomArr = []
                if (newVal.details && newVal.details.length != 0) {
                    this.tableData = this.getDeepCode(newVal.details, [])
                    this.tableData.map(item => {
                        item.period = item.period
                    })
                    this.changeUnit(newVal.deptId)
                }
                this.imgList = []
                this.filesList = []
                this.drawList = []
                this.drawfiles = []
                this.filesList = this.detailForm.attaches
                this.imgList = this.detailForm.attaches
                this.detailForm.draws.map(item => {
                    this.drawList.push({
                        name: item.name,
                        url: item.link
                    })
                    this.drawfiles.push({
                        name: item.name,
                        url: item.link
                    })
                })
            } else {
                this.deviceList = []
                this.imgList = []
                this.filesList = []
                this.drawList = []
                this.drawfiles = []
                // this.getDeviceData()
                getChildList(1, 100, '1858710780677984257').then(res => {
                    this.periodArr = res.data.data
                })
                this.headers = {
                    "Authorization": `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`,
                    'Blade-Auth': 'bearer ' + getToken(),
                    'Blade-Requested-With': 'BladeHttpRequest'
                }
            }
        }
    },
    created() {
        this.deviceList = []
        // this.getDeviceData()
        getChildList(1, 100, '1858710780677984257').then(res => {
            this.periodArr = res.data.data
        })
        this.headers = {
            "Authorization": `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`,
            'Blade-Auth': 'bearer ' + getToken(),
            'Blade-Requested-With': 'BladeHttpRequest'
        }
        this.imgList = []
        this.filesList = []
        this.drawList = []
        this.drawfiles = []
        if (JSON.stringify(this.detailForm) != '{}') {
            this.addForm = {
                ...this.detailForm,
                unitId: this.detailForm.deptId,
                unitName: this.detailForm.deptName,
                content: this.detailForm.planContent,
            }
            this.floorArr = []
            this.roomArr = []
            this.tableData = this.getDeepCode(this.detailForm.details, [])
            this.changeUnit(this.detailForm.deptId)

            this.detailForm.attaches.map(item => {
                this.imgList.push({
                    name: item.name,
                    url: item.link
                })
                this.filesList.push({
                    name: item.name,
                    url: item.link
                })
            })
            this.detailForm.draws.map(item => {
                this.drawList.push({
                    name: item.name,
                    url: item.link
                })
                this.drawfiles.push({
                    name: item.name,
                    url: item.link
                })
            })
        } else {
            this.drawList = []
            this.drawfiles = []
            this.imgList = []
            this.filesList = []
            this.addForm = {}
        }
    },
    methods: {
        getDeepCode(data, arr) {
            data.map(item => {
                if (item.details.length != 0) {
                    this.getDeepCode(item.details, arr)
                } else {
                    arr.push(item)
                }
            })
            return arr
        },
        handleSuccess(response, file, fileList) {
            if (response.code == 200) {
                this.filesList.push({
                    url: response.data.link,			//附件url 
                    name: response.data.originalName,	//附件名称
                })
            }
        },
        handleRemove(res, file) {
            this.filesList = this.filesList.filter(item => item.link == res.url && item.name == res.name)
        },
        handledrawSuccess(response, file, fileList) {
            if (response.code == 200) {
                this.drawfiles.push({
                    url: response.data.link,			//附件url 
                    name: response.data.originalName,	//附件名称
                })
            }
        },
        handledrawRemove(res, file) {
            this.drawfiles = this.drawfiles.filter(item => item.link == res.url && item.name == res.name)
        },
        getDeviceData() {
            getDeviceList({ current: this.deviceCurrent, size: this.deviceSize }).then(res => {
                this.deviceList = res.data.data.records
                this.deviceList.forEach(item => {
                    item.disabled = false
                })
            })
        },
        async justify() {
            //校验成功则方法自动返回true，校验方法报错则说明校验失败，返回false
            try {
                return await this.$refs['form'].validate()
            } catch (error) {
                return false
            }
        },
        getSpanArr(data) {
            for (var i = 0; i < data.length; i++) {
                if (i === 0) {
                    this.spanArr.push(1);
                    this.pos = 0
                } else {
                    // 判断当前元素与上一个元素是否相同
                    if (data[i].deviceId === data[i - 1].deviceId) {
                        this.spanArr[this.pos] += 1;
                        this.spanArr.push(0);
                    } else {
                        this.spanArr.push(1);
                        this.pos = i;
                    }
                }
            }
        },
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            if (columnIndex === 1 && row.deviceId != '') {
                if (this.spanArr.length != 0) {
                    const _row = this.spanArr[rowIndex];
                    const _col = _row > 0 ? 1 : 0;
                    return {
                        rowspan: _row,
                        colspan: _col
                    }
                }
            }
        },
        // 切换开始时间
        changeStartTime(val, index) {
            this.addForm.tableData[index].nextStartTime = val
        },
        // 切换设备
        changeDevice(val, index) {
            console.log('val------------->', val, index)
            getDetail({ id: val }).then(res => {
                if (this.title == '新建') {
                    console.log('tmp------------------->', this.tableData.find(item => item.deviceId == val))
                    let arr = []
                    res.data.data.maintenances.map(item => {
                        arr.push({
                            floorId: this.activeFloor,							// 楼层id
                            floorName: this.floorArr.find(item => item.id == this.activeFloor).deptName,					// 楼层名称
                            deviceId: item.deviceId,
                            deviceName: res.data.data.name,
                            deptId: this.activeRoom,		// 房间id
                            deptName: this.roomArr.find(item => item.id == this.activeRoom).deptName,					// 房间名称
                            checkContent: item.checkContent,
                            majorName: '',
                            nextStartTime: item.startTime,
                            startTime: item.startTime,
                            craft: item.craft,
                            period: item.period,
                        })
                    })
                    this.tableData = [...this.tableData, ...arr]
                    this.addForm.tableData = this.tableData.filter(item => item.floorId == this.activeFloor && item.deptId == this.activeRoom)
                    this.spanArr = []
                    this.pos = 0
                    this.getSpanArr(this.addForm.tableData)
                    let arr1 = this.deviceList.filter(item1 =>
                        this.addForm.tableData.some(item2 =>
                            item1.id == item2.deviceId
                        )
                    );
                    this.deviceList.map(item1 => {
                        item1.disabled = false
                        arr1.map(item2 => {
                            if (item2.id == item1.id) {
                                item1.disabled = true
                            }
                        })
                    })
                } else {
                    let arr = []
                    res.data.data.maintenances.map(item => {
                        arr.push({
                            floorId: this.activeFloor,							// 楼层id
                            floorName: this.floorArr.find(item => item.id == this.activeFloor).deptName,					// 楼层名称
                            deviceId: item.deviceId,
                            deviceName: res.data.data.name,
                            deptId: this.activeRoom,		// 房间id
                            deptName: this.roomArr.find(item => item.id == this.activeRoom).deptName,					// 房间名称
                            checkContent: item.checkContent,
                            majorName: '',
                            nextStartTime: item.startTime,
                            startTime: item.startTime,
                            craft: item.craft,
                            period: item.period,
                        })
                    })
                    if (index == this.addForm.tableData.length - 1) {
                        this.addForm.tableData.splice(index, 1, ...arr)
                        // this.tableData.splice(index,1,...arr)
                        this.spanArr = []
                        this.pos = 0
                        this.getSpanArr(this.addForm.tableData)
                    } else {
                        this.addForm.tableData.splice(index, this.spanArr[index], ...arr)
                        // this.tableData.splice(index,this.spanArr[index],...arr)
                        this.spanArr = []
                        this.pos = 0
                        this.getSpanArr(this.addForm.tableData)
                    }
                    this.addForm.tableData = func.process(this.addForm.tableData)
                    this.$forceUpdate()
                    this.spanArr = []
                    this.pos = 0
                    this.getSpanArr(this.addForm.tableData)
                    this.tableData = [...this.tableData, ...this.addForm.tableData]
                    this.tableData = func.process(this.tableData)
                    let arr1 = this.deviceList.filter(item1 =>
                        this.addForm.tableData.some(item2 =>
                            item1.id == item2.deviceId
                        )
                    );
                    console.log('arr1==============>', arr1)
                    this.deviceList.map(item1 => {
                        item1.disabled = false
                        arr1.map(item2 => {
                            if (item2.id == item1.id) {
                                item1.disabled = true
                            }
                        })
                    })
                    console.log('this.deviceList', this.deviceList)
                }
            })
        },
        // 切换实验室
        changeUnit(val) {
            console.log('val===========>', val)
            console.log('unitData===============>', this.unitData)
            this.labId = val
            if (this.title == '新建') {
                this.addForm.unitName = this.unitData.find(item => item.id == val).title
                this.deviceList.map(item => {
                    item.disabled = false
                })
            }
            getDeepData({ parentId: val }).then(res => {
                console.log('res ------------------->', res)
                this.floorArr = res.data.data
                this.activeFloor = res.data.data.length > 0 ? res.data.data[0].id : ''
                getDeepData({ parentId: this.activeFloor }).then(res => {
                    this.roomArr = res.data.data
                    this.activeRoom = res.data.data.length > 0 ? res.data.data[0].id : ''
                    this.clickRoom(res.data.data[0])
                    if (JSON.stringify(this.detailForm) != '{}') {
                        console.log(this.activeFloor, this.activeRoom)
                        this.addForm.tableData = this.tableData.filter(item => item.floorId == this.activeFloor && item.deptId == this.activeRoom)
                        console.log('addForm==========>', this.addForm.tableData)
                        let arr1 = this.deviceList.filter(item1 =>
                            this.addForm.tableData.some(item2 =>
                                item1.id == item2.deviceId
                            )
                        );
                        console.log('arr1==============>', arr1)
                        this.deviceList.map(item1 => {
                            item1.disabled = false
                            arr1.map(item2 => {
                                if (item2.id == item1.id) {
                                    item1.disabled = true
                                }
                            })
                        })
                        console.log('deviceList', this.deviceList)
                        this.spanArr = []
                        this.pos = 0
                        this.getSpanArr(this.addForm.tableData)
                    }
                })
            })
        },
        openForm() {
            this.addForm.tableData = [
                { floorId: this.activeFloor, roomId: this.activeRoom, majorName: '', checkContent: '', craft: '' },
            ]
            this.tableData = this.tableData.concat(this.addForm.tableData)
            this.activeFloor = '001'
            this.activeRoom = '001'
        },
        clearForm() {
            this.$refs['form'].resetFields()
            this.tableData = []
            this.addForm = {
                tableData: []
            }
        },
        addColumn() {
            if (this.title == '查看') {
                return
            } else {
                this.addForm.tableData.push({ floorId: this.activeFloor, roomId: this.activeRoom, majorName: '', checkContent: '', craft: '', deviceId: '' })
                this.tableData = this.tableData.filter(item => (item.floorId != this.activeFloor || item.roomId != this.activeRoom))
            }
        },
        deleteColumn(row, index) {
            if (this.title == '查看') {
                return
            } else {
                this.tableData.splice(index, 1);
                this.spanArr = []
                this.pos = 0
                this.addForm.tableData.splice(index, 1);
                this.getSpanArr(this.addForm.tableData)
                console.log('tableData',this.tableData)
            }
        },
        dealFloor(val) {
            getDeepData({ parentId: val }).then(res => {
                this.roomArr = res.data.data
                this.activeRoom = this.roomArr[0].id
                this.clickRoom(this.roomArr[0])
                this.addForm.tableData = this.tableData.filter(item => item.floorId == this.activeFloor && item.deptId == this.activeRoom)
                if (this.addForm.tableData.length == 0) {
                    this.addForm.tableData = [{ floorId: this.activeFloor, roomId: this.activeRoom, majorName: '', checkContent: '', craft: '' }]
                }
                const uniqueArr = this.addForm.tableData.filter((item, index, self) => {
                    return index === self.findIndex(obj => obj.craft === item.craft && obj.deviceId === item.deviceId);
                });
                this.addForm.tableData = uniqueArr
                let arr1 = this.deviceList.filter(item1 =>
                    this.addForm.tableData.some(item2 =>
                        item1.id == item2.deviceId
                    )
                );
                this.deviceList.map(item1 => {
                    item1.disabled = false
                    arr1.map(item2 => {
                        if (item2.id == item1.id) {
                            item1.disabled = true
                        }
                    })
                })
                this.spanArr = []
                this.pos = 0
                this.getSpanArr(this.addForm.tableData)
            })
        },
        clickFloor(val) {
            this.activeFloor = val.id
            this.dealFloor(val.id)
        },
        clickRoom(val) {
            this.activeRoom = val.id
            console.log('val1------------->', val)
            console.log('title------------->', this.title)
            if (this.title == '新建') {
                getDeviceLists({ limsId: this.labId, floorId: this.activeFloor, roomId: this.activeRoom }).then(res => {
                    this.deviceList = res.data.data
                    console.log('res==============>', res)
                    console.log('table-------------->', this.tableData)
                    res.data.data.map((item, index) => {
                        if (!this.tableData.find(item => item.deptId == this.activeRoom)) {
                            this.changeDevice(item.id, index)
                        } else {
                            this.addForm.tableData = this.tableData.filter(item => item.floorId == this.activeFloor && item.deptId == this.activeRoom)
                            this.spanArr = []
                            this.pos = 0
                            this.getSpanArr(this.addForm.tableData)
                            let arr1 = this.deviceList.filter(item1 =>
                                this.addForm.tableData.some(item2 =>
                                    item1.id == item2.deviceId
                                )
                            );
                            this.deviceList.map(item1 => {
                                item1.disabled = false
                                arr1.map(item2 => {
                                    if (item2.id == item1.id) {
                                        item1.disabled = true
                                    }
                                })
                            })
                        }
                    })
                })
            } else {
                this.isLoad = true
                getDeviceLists({ limsId: this.labId, floorId: this.activeFloor, roomId: this.activeRoom }).then(res => {
                    this.deviceList = res.data.data
                    this.addForm.tableData = this.tableData.filter(item => item.floorId == this.activeFloor && item.deptId == this.activeRoom)
                    setTimeout(() => {
                        this.isLoad = false
                    }, 200)
                    this.deviceList.map(item1 => {
                        item1.disabled = false
                        if(this.addForm.tableData.filter(item2 => item2.deviceId == item1.id).length == item1.maintenances.length){
                            item1.disabled = true
                        }
                        // arr1.map(item2 => {
                        //     if (item2.id == item1.id) {
                        //         item1.disabled = true
                        //     }
                        // })
                    })
                    console.log('this.addForm.tableData',this.addForm.tableData)
                    this.$forceUpdate();
                    this.spanArr = []
                    this.pos = 0
                    this.getSpanArr(this.addForm.tableData)
                })
            }
        },
    }

}
</script>

<style></style>