<template>
    <div class="device-info_install addinstall">
        <div class="device_content">
            <div class="left_content">
                <div class="form_head">
                    <p>基本信息</p>
                </div>
                <div class="form_content">
                    <el-scrollbar class="app-list-scroll" style="height: 100%">
                        <div class="form_content_disform">
                            <zz-form :cols="detailCols" :data="formdata" :rules="formrules" labelWidth="98" ref="detailform">
                                <el-select v-model="formdata.communityId" placeholder="请选择社区名称" slot="communityId" class="width100">
                                    <el-option
                                        v-for="(item, index) in communityArray"
                                        :label="item.communityName"
                                        :value="item.id"
                                        :key="index"
                                    ></el-option>
                                </el-select>
                                <el-select
                                    v-model="formdata.buildingType"
                                    placeholder="请选择楼栋类型"
                                    slot="buildingTypeList"
                                    class="width100"
                                >
                                    <el-option label="高层" :value="1"></el-option>
                                    <el-option label="底层" :value="2"></el-option>
                                </el-select>

                                <el-select
                                    v-model="formdata.buildingPurpose"
                                    placeholder="请选择楼栋用途"
                                    slot="buildingPurpose"
                                    class="width100"
                                >
                                    <el-option
                                        v-for="(item, index) in buildingPurposeType"
                                        :label="item.label"
                                        :value="item.id"
                                        :key="index"
                                    ></el-option>
                                </el-select>

                                <el-select
                                    v-model="formdata.buildingStructure"
                                    placeholder="请选择楼栋用途"
                                    slot="buildingStructure"
                                    class="width100"
                                >
                                    <el-option
                                        v-for="(item, index) in buildingStructureType"
                                        :label="item.label"
                                        :value="item.id"
                                        :key="index"
                                    ></el-option>
                                </el-select>
                                <el-input
                                    type="textarea"
                                    :rows="4"
                                    slot="remarks"
                                    show-word-limit
                                    v-model="formdata.remarks"
                                    maxlength="300"
                                >
                                </el-input>
                            </zz-form>
                        </div>
                    </el-scrollbar>
                </div>
            </div>
            <div class="right_content">
                <div class="right_content_head">
                    <span class="head_text">创建房屋</span>
                    <span class="close" @click="close">
                        <i class="el-icon-close"></i>
                    </span>
                </div>
                <div class="right_content_info">
                    <div class="head_fr" v-if="isAdd">
                        <div class="head_content head_add">
                            <div class="checkbox_style">
                                <el-checkbox :disabled="!isAdd" @change="checkedUnit" v-model="initialUnitList.checkedUnit"></el-checkbox>
                            </div>
                            <div class="form_content">
                                <zz-form
                                    :cols="unitCols"
                                    labelposition="left"
                                    :rules="unitrules"
                                    :data="formdata"
                                    :disabled="!isAdd"
                                    labelWidth="50"
                                    ref="unitform"
                                >
                                    <template slot="unitRule" prop="unitRule">
                                        <div class="row_class">
                                            <el-radio-group
                                                :disabled="!initialUnitList.checkedUnit"
                                                v-model="initialUnitList.unit.type"
                                                @change="radioChange('unit', $event)"
                                            >
                                                <el-radio label="Number">按数字1-20生成</el-radio>
                                                <el-radio label="Letter">按字母A-Z生成</el-radio>
                                            </el-radio-group>
                                            <el-select
                                                :disabled="!initialUnitList.checkedUnit"
                                                class="w120 wfirst"
                                                v-model="initialUnitList.unit.start"
                                                prop="floorstart"
                                                placeholder="起始单元"
                                            >
                                                <el-option
                                                    v-for="item in unitOptions"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                >
                                                </el-option>
                                            </el-select>
                                            <el-select
                                                class="w120 wsecond"
                                                :disabled="!initialUnitList.checkedUnit"
                                                v-model="initialUnitList.unit.end"
                                                placeholder="单元数"
                                            >
                                                <el-option
                                                    v-for="item in unitOptions"
                                                    :key="item.value"
                                                    :label="item.label"
                                                    :value="item.value"
                                                >
                                                </el-option>
                                            </el-select>
                                        </div>
                                        <div class="row_class addfloo">
                                            <div class="last_level">
                                                <label class="label_text">每栋层数</label>
                                                <el-select class="w120" v-model="formdata.floorsNumber" placeholder="请选择楼栋层数">
                                                    <el-option
                                                        v-for="item in floorlevelOptions"
                                                        :key="item.value"
                                                        :label="item.label"
                                                        :value="item.value"
                                                    >
                                                    </el-option>
                                                </el-select>
                                            </div>
                                            <div class="last_level">
                                                <label class="label_text">每层户数</label>
                                                <el-select class="w120" v-model="formdata.householdsPerFloor" placeholder="请选择每层户数">
                                                    <el-option
                                                        v-for="item in unithouseOptions"
                                                        :key="item.value"
                                                        :label="item.label"
                                                        :value="item.value"
                                                    >
                                                    </el-option>
                                                </el-select>
                                            </div>
                                            <div class="last_level" v-if="isAdd">
                                                <label class="label_text">房屋类型</label>
                                                <el-select
                                                    class="w120"
                                                    v-model="formdata.houseType"
                                                    @change="toggleUnithOptions"
                                                    placeholder="请选择每层户数"
                                                >
                                                    <el-option label="住宅" :value="1"></el-option>
                                                    <el-option label="商业" :value="2"></el-option>
                                                </el-select>
                                            </div>
                                        </div>
                                    </template>
                                </zz-form>
                            </div>
                            <div class="btn_unit">
                                <el-button type="primary" class="el-mgRight-md" :disabled="!isAdd" @click="createDoor"
                                    >{{ doorData.length ? '重新' : '' }}生成房屋</el-button
                                >
                                <el-button @click="clearDoor" :disabled="!isAdd">清空房屋</el-button>
                            </div>
                        </div>
                        <div class="title_class">
                            <span class="title_txt">楼栋信息</span>
                            <el-tooltip v-if="doorData && doorData.length > 0" class="item text-wrapper" effect="light" placement="right">
                                <div slot="content">
                                    双击可对楼栋、单元名称进行自定义修改<br />单击选中楼栋、单元、单元户信息根据选中的楼栋、单元进行展示
                                </div>
                                <img src="@/assets/img/menuicon/icon_tishi_zhengchang.png" alt="" />
                            </el-tooltip>
                        </div>
                    </div>
                    <div class="floorinfo">
                        <div class="door-wrap door_install">
                            <div class="top_content" :class="!isAdd ? 'is-disabled' : ''">
                                <el-scrollbar class="app-list-scroll" style="height: 100%">
                                    <div class="floor_unit" v-if="doorData && doorData.length > 0">
                                        <div class="box clearfix">
                                            <div class="label_left">楼栋</div>
                                            <div class="el-fl-left tags">
                                                <el-tag :disable-transitions="false" data-code="build" class="active">
                                                    {{ formdata.buildingName }}
                                                </el-tag>
                                            </div>
                                        </div>
                                        <div
                                            class="box clearfix"
                                            v-if="
                                                initialUnitList.enableUnit &&
                                                doorData[buildingIndex] &&
                                                doorData[buildingIndex].unitFloorList &&
                                                doorData[buildingIndex].unitFloorList.length
                                            "
                                        >
                                            <div class="label_left">单元</div>

                                            <div class="el-fl-left tags">
                                                <el-tag
                                                    :key="index2"
                                                    v-for="(unit, index2) in doorData"
                                                    closable
                                                    :disable-transitions="false"
                                                    data-code="unit"
                                                    @close="handleClose('unit', index2, doorData)"
                                                    @click="unitIndex = index2"
                                                    :class="{ active: unitIndex === index2 }"
                                                >
                                                    <span @dblclick="showInput">{{ unit.unitName }}</span>
                                                    <el-input
                                                        style="display: none"
                                                        v-model="unit.unitName"
                                                        @keyup.enter.native="inputConfirm($event, doorData)"
                                                        @blur="inputConfirm($event, doorData)"
                                                        data-code="unit"
                                                        maxlength="20"
                                                    ></el-input>
                                                </el-tag>
                                                <el-button class="el-icon-plus button-new-tag" size="small" @click="showInput"></el-button>
                                                <el-input
                                                    class="input-new-tag"
                                                    style="display: none"
                                                    size="small"
                                                    placeholder="请输入单元号"
                                                    v-model="inputValue.unit"
                                                    @keyup.enter.native="handleInputConfirm($event, doorData)"
                                                    @blur="handleInputConfirm($event, doorData)"
                                                    data-code="unit"
                                                    maxlength="20"
                                                >
                                                </el-input>
                                            </div>
                                        </div>
                                    </div>
                                    <div v-else class="empty_floor">
                                        <p>暂无相关信息</p>
                                    </div>
                                    <div class="title_class border_hr">
                                        <span class="title_txt">单元户信息</span>
                                        <el-tooltip
                                            v-if="
                                                doorData[buildingIndex] &&
                                                doorData[buildingIndex].unitFloorList &&
                                                doorData[buildingIndex].unitFloorList.length
                                            "
                                            class="item"
                                            effect="light"
                                            placement="right"
                                            :content="unitMsg"
                                        >
                                            <img src="@/assets/img/menuicon/icon_tishi_zhengchang.png" alt="" />
                                        </el-tooltip>
                                    </div>

                                    <div
                                        class="unit"
                                        v-if="
                                            doorData[buildingIndex] &&
                                            doorData[buildingIndex].unitFloorList &&
                                            doorData[buildingIndex].unitFloorList.length
                                        "
                                    >
                                        <div
                                            class="floor"
                                            v-if="
                                                doorData[buildingIndex].unitFloorList[unitIndex] &&
                                                doorData[buildingIndex].unitFloorList[unitIndex].roomList &&
                                                doorData[buildingIndex].unitFloorList[unitIndex].roomList.length
                                            "
                                        >
                                            <!-- <h2>单元户<span>鼠标双击修改名称； 修改楼层名称后，请自行修改单元户的名称</span></h2> -->
                                            <div
                                                class="box clearfix"
                                                :key="index3"
                                                v-for="(floor, index3) in doorData[buildingIndex].unitFloorList"
                                            >
                                                <!-- <span class="el-fl-left label">楼层：</span> -->
                                                <div class="unit_left">
                                                    <el-tag
                                                        closable
                                                        :disable-transitions="false"
                                                        data-code="floor"
                                                        @close="handleClose('floor', index3, doorData[buildingIndex].unitFloorList)"
                                                    >
                                                        <span @dblclick="showInput">{{ floor.floorNumber }}</span>
                                                        <el-input
                                                            style="display: none"
                                                            v-model="floor.floorNumber"
                                                            @keyup.enter.native="
                                                                inputConfirm($event, doorData[buildingIndex].unitFloorList)
                                                            "
                                                            @blur="inputConfirm($event, doorData[buildingIndex].unitFloorList)"
                                                            data-code="floor"
                                                            maxlength="20"
                                                        ></el-input>
                                                    </el-tag>
                                                    <span class="unit_text">层</span>
                                                </div>
                                                <span class="el-fl-left tags">
                                                    <div class="door" v-if="floor">
                                                        <el-tag
                                                            :key="index4"
                                                            v-for="(door, index4) in floor.roomList"
                                                            closable
                                                            :disable-transitions="false"
                                                            data-code="door"
                                                            @close="handleClose('door', index4, floor.roomList)"
                                                        >
                                                            <span @dblclick="showInput">{{ door.roomNumber }}</span>
                                                            <el-input
                                                                style="display: none"
                                                                v-model="door.roomNumber"
                                                                @keyup.enter.native="inputConfirm($event, floor.roomList)"
                                                                @blur="inputConfirm($event, floor.roomList)"
                                                                data-code="door"
                                                                maxlength="20"
                                                            ></el-input>
                                                        </el-tag>
                                                        <el-button
                                                            class="el-icon-plus button-new-tag"
                                                            size="small"
                                                            @click="showInput"
                                                        ></el-button>
                                                        <el-input
                                                            class="input-new-tag"
                                                            style="display: none"
                                                            size="small"
                                                            placeholder="请输入户号"
                                                            v-model="inputValue.door"
                                                            @keyup.enter.native="handleInputConfirm($event, floor.roomList)"
                                                            @blur="handleInputConfirm($event, floor.roomList)"
                                                            data-code="door"
                                                            maxlength="20"
                                                        >
                                                        </el-input>
                                                    </div>
                                                </span>
                                            </div>
                                            <div class="add-floor">
                                                <el-button class="el-icon-plus button-new-tag" size="small" @click="showInput"></el-button>
                                                <el-input
                                                    class="input-new-tag"
                                                    style="display: none"
                                                    size="small"
                                                    placeholder="请输入楼层号"
                                                    v-model="inputValue.floor"
                                                    @keyup.enter.native="handleInputConfirm($event, doorData[buildingIndex].unitFloorList)"
                                                    @blur="handleInputConfirm($event, doorData[buildingIndex].unitFloorList)"
                                                    data-code="floor"
                                                    maxlength="20"
                                                >
                                                </el-input>
                                            </div>
                                        </div>
                                    </div>
                                    <div v-else class="unit_empty">
                                        <div class="center_text">
                                            <img src="@assets/img/menuicon/img_wuxiaoxi@2x.png" alt="" />
                                            <span>暂无相关信息</span>
                                        </div>
                                    </div>
                                </el-scrollbar>
                            </div>
                            <div class="btns footer_btn">
                                <el-button @click="resetForm">重置</el-button>
                                <el-button @click="close">取消</el-button>
                                <el-button type="primary" @click="submit">保存</el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import initList from '../mixins/initList';
import { initDoor, calcDoor } from './basedata';
const createContinueData = (type, num) => {
    //type--类型，num生成的个数
    let objArr = [];
    if (type == 'Number') {
        [...new Array(Number(num)).keys()].map((idx) => {
            let obj = { label: Number(idx) + 1, value: Number(idx) + 1 };
            objArr.push(obj);
        });
    } else {
        for (let i = 0; i < num; i++) {
            let letter = String.fromCharCode(65 + i);
            let obj = { label: letter, value: letter };
            objArr.push(obj);
        }
    }
    return objArr;
};
const txtI18n = {
    build: '楼栋',
    unit: '单元',
    floor: '楼层',
    door: '单元户'
};
export default {
    mixins: [initList],
    name: 'editBuilding',
    data() {
        return {
            unitCols: [[{ label: '单元', slot: 'unitRule', prop: 'unitRule' }]],
            detailCols: [
                [
                    {
                        label: '所属社区',
                        prop: 'communityId',
                        slot: 'communityId'
                    },
                    {
                        label: '楼栋名称',
                        prop: 'buildingName',
                        input: 'true'
                    },
                    {
                        label: '楼栋编号',
                        prop: 'buildingNumber',
                        input: 'true'
                    },
                    {
                        label: '楼栋类型',
                        prop: 'buildingTypeList',
                        slot: 'buildingTypeList'
                    },
                    {
                        label: '楼栋用途',
                        prop: 'buildingPurpose',
                        slot: 'buildingPurpose'
                    },
                    {
                        label: '建筑结构',
                        prop: 'buildingStructure',
                        slot: 'buildingStructure'
                    },
                    {
                        label: '建成日期',
                        prop: 'builtDate',
                        date: 'true',
                        widt: true
                    },
                    {
                        label: '验收日期',
                        prop: 'acceptanceDate',
                        date: 'true',
                        widt: true
                    },
                    {
                        label: '建筑面积',
                        prop: 'buildingArea',
                        input: true
                    },
                    {
                        label: '使用面积',
                        prop: 'useArea',
                        input: 'true'
                    },
                    {
                        label: '备注信息',
                        prop: 'remarks',
                        slot: 'remarks'
                    }
                ]
            ],
            formdata: {
                communityId: '',
                buildingName: '',
                buildingNumber: '', //楼栋编号
                buildingType: '',
                buildingPurpose: '',
                buildingStructure: '',
                builtDate: '',
                acceptanceDate: '',
                buildingArea: '',
                useArea: '',
                remarks: '',
                houseType: 1,
                floorsNumber: '1', //每栋层数
                unitNumber: '2', //单元数
                householdsPerFloor: '1' //每层户数
            },
            initialUnitList: {
                checkedUnit: false,
                enableUnit: 1, //勾选了复选框
                unit: {
                    type: 'Number', //  Number letter
                    start: '1', // 1 A单元的起始单元
                    end: '1'
                }
            },
            formrules: {
                communityId: this.$valid.selectRequired(['社区']),
                buildingName: [this.$valid.inputRequired('楼栋名称')]
            },
            buildingPurposeType: [
                {
                    label: '住宅楼',
                    id: 1
                },
                {
                    label: '商场',
                    id: 2
                },
                {
                    label: '写字楼',
                    id: 3
                },
                {
                    label: '公寓',
                    id: 4
                },
                {
                    label: '别墅',
                    id: 5
                },
                {
                    label: '自建楼',
                    id: 6
                },
                {
                    label: '其他',
                    id: 7
                }
            ],
            buildingStructureType: [
                {
                    label: '钢结构',
                    id: 1
                },
                {
                    label: '钢筋混凝土结构',
                    id: 2
                },
                {
                    label: '筋混凝土结构',
                    id: 3
                },
                {
                    label: '混合结构',
                    id: 4
                },
                {
                    label: '砖木结构',
                    id: 5
                },
                {
                    label: '其他结构',
                    id: 6
                }
            ]
        };
    },
    props: {
        params: {
            type: Object
        },
        isAdd: {
            type: Boolean,
            default: true
        }
    },
    methods: {
        radioChange(type, val) {
            let length = val == 'Number' ? '20' : '26';
            if (val == 'Letter') {
                this.unitOptions = createContinueData(val, length);
                this.initialUnitList.unit.type = 'Letter';
                this.initialUnitList.unit.start = 'A';
                this.initialUnitList.unit.end = 'A';
            } else {
                this.initialUnitList.unit = this.copyrules.unit;
                this.unitOptions = createContinueData(val, length);
            }
        },

        resetForm() {
            this.formdata = {};
            this.formdata = this.copyformdata;
            // this.doorData = [];
            this.$refs.detailform.validateField('communityId');
        },

        checkedUnit(val) {
            if (val) {
                this.initialUnitList.enableUnit = 1;
            } else {
                this.formdata.unitNumber = 1;
                this.initialUnitList.enableUnit = 0;
            }
        },
        createDoor() {
            if (this.formdata.buildingName == '') {
                this.$message.error('先输入楼栋名称');
                return;
            }
            new Promise((resolve) => {
                this.$refs.unitform.validate(resolve);
            }).then((v) => {
                if (this.initialUnitList.checkedUnit) {
                    this.initialUnitList.enableUnit = 1;
                } else {
                    this.formdata.unitNumber = 1;
                    this.initialUnitList.enableUnit = 0;
                }
                let isNumberUnitFlag = this.initialUnitList.unit.type == 'Number' ? true : false;
                let checkUnit = this.initialUnitList.unit.start <= this.initialUnitList.unit.end ? true : false;
                if (this.initialUnitList.checkedUnit) {
                    if (checkUnit && isNumberUnitFlag) {
                        this.formdata.unitNumber = this.initialUnitList.unit.end - this.initialUnitList.unit.start + 1;
                    } else if (!isNumberUnitFlag && checkUnit) {
                        this.formdata.unitNumber =
                            this.initialUnitList.unit.end.charCodeAt() - this.initialUnitList.unit.start.charCodeAt() + 1;
                    } else {
                        this.formdata.unitNumber = 1;
                        this.$message.error('单元起始和结束设置出错');
                        return;
                    }
                }

                this.doorData = initDoor(this.formdata, this.initialUnitList).generateUnit;
                console.log(initDoor(this.formdata, this.initialUnitList));
            });
        },
        handleInputConfirm(e, arr) {
            const { value, dataset } = e.target;
            if (value && dataset) {
                const { code } = dataset;
                const querySame = () => _.isEmpty(_.filter(arr, (v) => v.name == value));
                const generate = {
                    unit: initDoor(this.formdata, this.initialUnitList).generateUnit,
                    floor: initDoor(this.formdata, this.initialUnitList).generateFloor,
                    door: initDoor(this.formdata, this.initialUnitList).generateDoor(value)
                };
                if (querySame()) {
                    if (code == 'unit') {
                        arr.push({
                            unitName: value,
                            unitFloorList: code != 'door' ? generate['floor'] : undefined
                        });
                    } else if (code == 'door') {
                        arr.push({
                            roomNumber: value
                        });
                    } else if (code == 'floor') {
                        arr.push({
                            floorNumber: value,
                            roomList: code != 'door' ? generate['door'] : undefined
                        });
                    }
                    this.inputValue[code] = '';
                } else {
                    this.$message.error(`${txtI18n[code]}名称重复，请重新添加`);
                }
            }
            e.target.parentElement.style.display = 'none';
            e.target.parentElement.previousElementSibling.style.display = 'inline-block';
            e.target.value = '';
        },

        submit() {
            new Promise((resolve) => {
                this.$refs.detailform.validate(resolve);
            }).then((v) => {
                const { buildNumber, unitNumber, floorNumber, doorNumber } = calcDoor(this.doorData, this.initialUnitList.checkedUnit);
                const txt = `请检查信息是否填写完整（包含重复名称，名称为空现象）<br>确认提交单元户信息：<br>总楼栋数：${buildNumber}${
                    this.initialUnitList.enableUnit ? `<br>总单元数：${unitNumber}` : ''
                }<br>总楼层数：${floorNumber}<br>总单元户数：${doorNumber}`;
                this.__confirm(txt, '提交')
                    .then((v) => {
                        this.formdata.buildingUnitList = this.doorData;
                        let url = '/sc-community/assets/building/add';
                        if (!!this.params.id) {
                            url = '/sc-community/assets/building/update';
                        }
                        this.$http
                            .post(url, this.formdata)
                            .then(({ msg, status }) => {
                                this.$message({
                                    type: status === 0 ? 'success' : 'error',
                                    message: msg
                                });
                                if (status === 0) {
                                    this.close();
                                }
                            })
                            .catch(() => {});
                    })
                    .catch(() => {});
            });
        },

        getDetailData(id) {
            this.$http.get('/sc-community/assets/building/house/find', { id: id }).then(({ status, data, msg }) => {
                if (0 === status) {
                    if (data.buildingUnitList.length !== 0) {
                        this.formdata = data;
                        this.formdata.householdsPerFloor = data.buildingUnitList[0].unitFloorList[0].roomList.length;
                        this.initialUnitList = {
                            checkedUnit: false,
                            enableUnit: 1, //勾选了复选框
                            unit: {
                                type: 'Number', //  Number letter
                                start: data.buildingUnitList[0]['unitName'], // 1 A单元的起始单元
                                end: data.buildingUnitList[data.buildingUnitList.length - 1]['unitName']
                            }
                        };
                        this.doorData = data.buildingUnitList;
                    }
                }
            });
        }
    },
    mounted() {},
    created() {
        this.copyformdata = this.deepClone(this.formdata);
        if (!!this.params.id) {
            this.getDetailData(this.params.id);
        }
        this.copyrules = JSON.parse(JSON.stringify(this.initialUnitList));
    }
};
</script>
<style lang="scss" >
@import './popup.scss';
</style>
