<template>
    <div class="select-allot-wrap">
        <el-card class="top-card" :body-style="{ padding: '26px 20px' }">
            <div class="title-wrap">
                <el-button class="top-button" type="info" size="small" @click="goBack()">
                    <i class="el-icon-arrow-left"></i>
                    {{ $t('product.product-edit.473153-44') }}
                </el-button>
                <span class="info-item">{{ $t('device.device-select-allot.903153-0') }}</span>
            </div>
        </el-card>

        <el-card class="main-card">
            <el-row>
                <el-form ref="queryForm" :model="queryParams" :inline="true">
                    <el-form-item label="" prop="productName">
                        <el-input readonly v-model="queryParams.productName" :placeholder="$t('device.allot-import-dialog.060657-1')">
                            <el-button slot="append" @click="selectProduct()">{{ $t('device.device-edit.148398-6') }}</el-button>
                        </el-input>
                    </el-form-item>
                    <el-form-item prop="deviceName">
                        <el-input :placeholder="$t('device.device-edit.148398-2')" clearable v-model="queryParams.deviceName"></el-input>
                    </el-form-item>
                    <el-form-item prop="serialNumber">
                        <el-input :placeholder="$t('device.device-edit.148398-8')" clearable v-model="queryParams.serialNumber"></el-input>
                    </el-form-item>

                    <div style="float: right">
                        <el-button type="primary" icon="el-icon-search" @click="handleQuery">{{ $t('device.device-select-allot.903153-4') }}</el-button>
                        <el-button icon="el-icon-refresh-left" @click="resetQuery" style="margin-left: 5px">{{ $t('device.device-select-allot.903153-5') }}</el-button>
                    </div>
                </el-form>
            </el-row>
            <div class="general">
                <div class="topLeft">
                    <div style="padding: 15px 10px; background-color: #f4f4f5">
                        <span style="font-size: 15px; font-weight: bold">{{ $t('device.device-select-allot.903153-6') }}</span>
                        <span style="font-size: 15px; font-weight: bold; float: right">{{ selectedCount }}/{{ this.count }}</span>
                    </div>
                    <el-row>
                        <el-table ref="leftTableData" :data="menuTableData" style="width: 100%" max-height="400" @selection-change="changeCheckBoxValueLeft" :border="false">
                            <template slot="empty">
                                <el-empty style="height: 400px" :image-size="100" :description="$t('device.device-select-allot.903153-7')"></el-empty>
                            </template>
                            <el-table-column type="selection" align="center" width="50" :selectable="checkSelectable"></el-table-column>
                            <el-table-column prop="productName" :label="$t('device.allot-record.155854-2')" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="serialNumber" :label="$t('device.device-edit.148398-7')" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="deviceName" :label="$t('device.device-edit.148398-1')" show-overflow-tooltip></el-table-column>
                        </el-table>
                    </el-row>
                </div>
                <div class="topCenter">
                    <el-button type="primary" :disabled="add" @click="rightAdd"><i class="el-icon-arrow-right el-icon--right"></i></el-button>
                    <el-button type="primary" :disabled="del" @click="leftDelete"><i class="el-icon-arrow-left el-icon--left"></i></el-button>
                </div>
                <div class="topRight">
                    <div style="padding: 15px 10px; background-color: #f4f4f5">
                        <span style="font-size: 15px; font-weight: bold">{{ $t('device.device-select-allot.903153-11') }}</span>
                        <span style="font-size: 15px; font-weight: bold; float: right">{{ selectedCount1 }}/500</span>
                    </div>
                    <el-row>
                        <el-table ref="rightTableData" :data="rightTableData" style="width: 100%" max-height="400" @selection-change="changeCheckBoxValueRight" :border="false">
                            <template slot="empty">
                                <el-empty style="height: 400px" :image-size="100" :description="$t('device.device-select-allot.903153-7')"></el-empty>
                            </template>
                            <el-table-column type="selection" align="center" width="50"></el-table-column>
                            <el-table-column prop="productName" :label="$t('device.allot-record.155854-2')" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="serialNumber" :label="$t('device.device-edit.148398-7')" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="deviceName" :label="$t('device.device-edit.148398-1')" show-overflow-tooltip></el-table-column>
                        </el-table>
                    </el-row>
                </div>
            </div>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :pager-count="5" :limit.sync="queryParams.pageSize" :pageSizes="[10, 20, 30, 40]" @pagination="getList" />
            <div style="width: 100%">
                <el-form label-position="top" :model="allotForm" ref="allotForm" :rules="allotRules">
                    <div style="width: 45%; margin: 60px 0">
                        <el-form-item :label="$t('device.allot-import-dialog.060657-2')" prop="deptId">
                            <treeselect v-model="allotForm.deptId" :options="deptOptions" :show-count="true" :placeholder="$t('device.allot-import-dialog.060657-3')" :appendToBody="true" z-index="9000" />
                        </el-form-item>
                    </div>
                </el-form>
            </div>
            <div class="footer">
                <el-button type="primary" @click="confirmDistribution">{{ $t('device.device-select-allot.903153-14') }}</el-button>
            </div>
        </el-card>

        <product-list ref="productList" :productId="queryParams.productId" @productEvent="getProductData($event)" />
    </div>
</template>

<script type="text/javascript">
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import { deptsTreeSelect } from '@/api/system/user';
import { listDevice, distributionDevice } from '@/api/iot/device';
import productList from './product-list';

export default {
    components: {
        Treeselect,
        productList,
    },
    data() {
        return {
            total: 0,
            productList: [],
            queryParams: {
                productId: null,
                deviceName: '',
                pageNum: 1,
                pageSize: 10,
                productName: null,
                serialNumber: null,
                showChild: false,
            },
            count: 0,
            //导入表单
            allotForm: {
                productId: 0,
                deptId: 0,
            },
            deviceIds: {},
            selectedCount: 0,
            // 机构树选项
            deptOptions: [],
            selectedRow: null,
            add: true,
            del: true,
            leftTableData: [],
            rightTableData: [],
            selectedListLeft: [], //点击左边选中的设备
            selectedListRight: [], //点击右边选中的设备
            //设备列表数据
            menuTableData: [],
            //导入分配表单校验
            allotRules: {
                deptId: [{ required: true, message: this.$t('device.allot-import-dialog.060657-15'), trigger: 'change' }],
            },
        };
    },
    created() {
        this.getDeptTree();
        this.getList();
    },
    computed: {
        //已选设备数量
        selectedCount1() {
            return this.rightTableData.length;
        },
    },
    watch: {
        selectedListLeft: function (val) {
            if (val.length) {
                this.add = false;
            } else {
                this.add = true;
            }
        },
        selectedListRight: function (val) {
            if (val.length) {
                this.del = false;
            } else {
                this.del = true;
            }
        },
    },
    methods: {
        //查询所有设备列表
        getList() {
            this.loading = true;
            listDevice(this.queryParams).then((response) => {
                this.menuTableData = response.rows;
                //isSelect用于判断是否可选
                this.menuTableData.map((item) => {
                    this.leftTableData.push(
                        Object.assign(item, {
                            isSelect: 0,
                        })
                    );
                });
                //分页后保持已选中状态
                if (this.rightTableData.length != 0) {
                    this.menuTableData.forEach((item, index) => {
                        this.rightTableData.forEach((item1) => {
                            if (item1.deviceId == item.deviceId) {
                                item.isSelect = 1;
                            }
                        });
                    });
                }
                this.total = response.total;
                if (this.count === 0) {
                    this.count = this.total;
                }
                this.loading = false;
            });
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.rightTableData = [];
            this.queryParams.productId = null;
            this.resetForm('queryForm');
            this.handleQuery();
        },
        /**选择产品 */
        selectProduct() {
            this.$refs.productList.open = true;
            this.$refs.productList.getList();
        },
        /**获取选中的产品 */
        getProductData(product) {
            this.queryParams.productId = product.productId;
            this.queryParams.productName = product.productName;
        },
        /** 查询机构下拉树结构 */
        getDeptTree() {
            this.allotForm.deptId = null;
            deptsTreeSelect().then((response) => {
                this.deptOptions = response.data;
            });
        },
        // 返回按钮
        goBack() {
            this.$router.go(-1);
        },
        //右边增加的数据
        rightAdd() {
            let leftTableData = JSON.parse(JSON.stringify(this.menuTableData));
            leftTableData.forEach((item, index) => {
                this.selectedListLeft.forEach((item1) => {
                    if (item.deviceId == item1.deviceId) {
                        this.rightTableData = this.rightTableData.concat(item).sort((a, b) => {
                            return a.deviceId - b.deviceId;
                        });
                        item.isSelect = 1;
                    }
                });
            });
            if (this.selectedCount1 != 0) {
                this.count = this.count - this.selectedListLeft.length;
            }
            leftTableData = leftTableData.filter((val) => {
                return val;
            });
            this.menuTableData = leftTableData;
            this.selectedListLeft = [];
        },
        //删除的数据
        leftDelete() {
            let rightTableData = JSON.parse(JSON.stringify(this.rightTableData));
            rightTableData.forEach((item, index) => {
                this.selectedListRight.forEach((item1) => {
                    this.menuTableData.forEach((item2) => {
                        if (item2.deviceId == item1.deviceId) {
                            item2.isSelect = 0;
                        }
                        if (item1.deviceId == item.deviceId) {
                            delete rightTableData[index];
                        }
                    });
                });
            });
            if (this.selectedCount1 != 0) {
                this.count = this.count + this.selectedListRight.length;
                this.getList();
            }
            rightTableData = rightTableData.filter((val) => {
                return val;
            });
            this.rightTableData = rightTableData;
            this.selectedListRight = [];
        },
        checkSelectable(row) {
            let flag = true;
            if (row.isSelect === 0) {
                flag = true;
            } else {
                flag = false;
            }
            return flag;
        },
        //左边数据
        changeCheckBoxValueLeft(val) {
            this.selectedListLeft = val;
            this.selectedCount = val.length;
        },
        //右边
        changeCheckBoxValueRight(val) {
            this.selectedListRight = val;
        },
        //确定分配操作
        confirmDistribution() {
            this.$refs['allotForm'].validate((valid) => {
                if (valid) {
                    this.deviceIds = this.rightTableData.map((item) => item.deviceId);
                    const deviceIds = this.deviceIds.join(',');
                    const deptId = this.allotForm.deptId;
                    distributionDevice(deptId, deviceIds).then((response) => {
                        if (response.code == 200) {
                            this.$modal.msgSuccess(response.msg);
                            this.resetQuery();
                        } else {
                            this.$modal.msgError(response.msg);
                        }
                    });
                }
            });
        },
    },
};
</script>
<style lang="scss" scoped>
.select-allot-wrap {
    padding: 20px;

    .top-card {
        margin-bottom: 10px;

        .title-wrap {
            display: flex;
            flex-direction: row;
            align-items: center;

            .top-button {
                height: 22px;
                color: #909399;
                background: #f4f5f7;
                padding: 0px 8px;
                border: none;
            }

            .info-item {
                font-weight: normal;
                font-size: 14px;
                color: #333333;
                line-height: 20px;
                margin-left: 36px;
            }
        }
    }

    .main-card {
        position: relative;
        padding-bottom: 60px;

        .general {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding-bottom: 20px;

            .topLeft {
                width: 44%;
                height: 450px;
            }

            .topCenter {
                width: 10%;
                display: flex;
                flex-direction: column;
                align-items: center;

                .el-button + .el-button {
                    margin-left: 0px;
                    margin-top: 10px;
                }
            }

            .topRight {
                width: 44%;
                height: 450px;
            }
        }

        .footer {
            position: absolute;
            bottom: 20px;
            left: 50%;
            margin-left: -49px;
        }
    }
}
</style>
