<template>
    <div class="iot-device-recycle">
        <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-recycle.864193-0') }}</span>
            </div>
        </el-card>

        <el-card class="main-card">
            <el-form ref="allotForm" :model="queryParams" :rules="allotRules" label-width="78px">
                <el-form-item :label="$t('device.device-recycle.864193-1')" prop="deptId">
                    <treeselect
                        style="width: 287px"
                        v-model="queryParams.deptId"
                        :options="deptOptions"
                        :show-count="true"
                        :clearable="false"
                        :searchable="true"
                        :placeholder="$t('device.device-recycle.864193-2')"
                        @input="getList"
                    />
                </el-form-item>
            </el-form>
            <el-form ref="queryForm" :model="queryParams" :inline="true">
                <el-form-item label="" prop="productName">
                    <el-input v-model="queryParams.productName" :placeholder="$t('device.device-edit.148398-5')" clearable>
                        <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>
                <div style="float: right">
                    <el-button type="primary" icon="el-icon-search" @click="handleQuery">{{ $t('search') }}</el-button>
                    <el-button style="margin-left: 5px" icon="el-icon-refresh-left" @click="resetQuery">{{ $t('reset') }}</el-button>
                </div>
            </el-form>
            <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-recycle.864193-7') }}</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%" height="400" @selection-change="changeCheckBoxValueLeft" :border="false">
                            <template slot="empty">
                                <el-empty style="height: 400px" :image-size="100" :description="$t('device.device-recycle.864193-8')"></el-empty>
                            </template>
                            <el-table-column type="selection" width="45" align="center" :selectable="checkSelectable"></el-table-column>
                            <el-table-column prop="deptName" :label="$t('device.device-recycle.864193-15')" align="center" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="productName" :label="$t('device.allot-record.155854-2')" align="center" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="serialNumber" :label="$t('device.device-edit.148398-7')" align="center" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="deviceName" :label="$t('device.device-edit.148398-1')" align="center" 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-recycle.864193-12') }}</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%" height="400" @selection-change="changeCheckBoxValueRight" :border="false">
                            <template slot="empty">
                                <el-empty style="height: 400px" :image-size="100" :description="$t('device.device-recycle.864193-8')"></el-empty>
                            </template>
                            <el-table-column type="selection" width="45" align="center"></el-table-column>
                            <el-table-column prop="deptName" :label="$t('device.device-recycle.864193-15')" align="center" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="productName" :label="$t('device.allot-record.155854-2')" align="center" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="serialNumber" :label="$t('device.device-edit.148398-7')" align="center" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="deviceName" :label="$t('device.device-edit.148398-1')" align="center" 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 class="footer">
                <el-button style="width: 100px" type="primary" @click="confirmDistribution">{{ $t('device.device-recycle.864193-13') }}</el-button>
            </div>
        </el-card>
        <product-list ref="productList" :productId="queryParams.productId" @productEvent="getProductData($event)" />
    </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';

import { deptsTreeSelectSub } from '@/api/system/user';
import { listDevice, recycleDevice } from '@/api/iot/device';
import productList from './product-list';

export default {
    components: {
        Treeselect,
        productList,
    },
    data() {
        return {
            productList: [],
            total: 0,
            count: 0,
            productList: [],
            selectedCount: 0,
            queryParams: {
                productId: null,
                deviceName: '',
                pageNum: 1,
                pageSize: 10,
                showChild: true,
                deptId: null,
            },
            deviceIds: {},
            deptOptions: [], // 机构树选项
            add: true,
            del: true,
            leftTableData: [],
            rightTableData: [],
            selectedListLeft: [], //点击左边选中的
            selectedListRight: [], //点击右边选中的
            menuTableData: [],
            //导入分配表单校验
            allotRules: {
                deptId: [{ required: true, message: this.$t('device.device-recycle.864193-14'), trigger: 'change' }],
            },
        };
    },
    created() {
        this.getDeptTree();
    },
    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.$refs['allotForm'].validate((valid) => {
                if (valid) {
                    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.queryParams.productId = null;
            this.rightTableData = [];
            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() {
            const showOwner = false;
            deptsTreeSelectSub(showOwner).then((res) => {
                if (res.code === 200) {
                    this.deptOptions = res.data || [];
                    if (!!this.deptOptions[0]?.id) {
                        this.queryParams.deptId = this.deptOptions[0].id;
                    }
                }
            });
        },
        // 右边增加的数据
        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 recoveryDeptId = this.queryParams.deptId;
                    recycleDevice(deviceIds, recoveryDeptId).then((response) => {
                        if (response.code == 200) {
                            this.$modal.msgSuccess(response.msg);
                            this.resetQuery();
                        } else {
                            this.$modal.msgError(response.msg);
                        }
                    });
                }
            });
        },
        // 返回按钮
        goBack() {
            this.$router.go(-1);
        },
    },
};
</script>

<style lang="scss" scoped>
.iot-device-recycle {
    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;
            }
        }
    }

    ::v-deep .vue-treeselect {
        width: 182.5px;
        height: 34.5px;
        line-height: 34.5px;
        font-size: inherit;
        color: #606266;
    }

    ::v-deep .vue-treeselect__control {
        height: 34.5px;
    }

    ::v-deep .vue-treeselect__placeholder,
    ::v-deep .vue-treeselect__single-value {
        line-height: 34.5px;
    }

    ::v-deep .vue-treeselect__input {
        width: 100%;
        height: unset;
    }

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

        .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>
