<template >
    <div class="addAccess">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="110px">
            <el-form-item label="所属社区" prop="communityId">
                <el-select v-model="formData.communityId" placeholder="请选择社区" clearable>
                    <el-option v-for="(item, index) in communityArr" :key="index" :label="item.communityName" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="员工" prop="userId">
                <el-cascader
                    ref="userName"
                    placeholder="请选择员工"
                    v-model="formData.userId"
                    :props="defaultProps"
                    :options="findUser"
                    @change="findUserToggle"
                ></el-cascader>
            </el-form-item>
            <el-form-item label="发卡" prop="cardNo">
                <div class="disCarInput">
                    <div class="disCardButton is-active" @click="getReadCard()">读取卡</div>
                    <div class="disCardButton" @click="formatCard()">格式化卡</div>
                </div>
                <div class="disCarInput">卡号：{{ formData.cardNo }}</div>
            </el-form-item>
            <el-form-item label="到期时间" prop="expirationTime">
                <el-date-picker
                    v-model="formData.expirationTime"
                    value-format="yyyyMMdd"
                    type="date"
                    placeholder="选择日期"
                    class="width100"
                >
                </el-date-picker>
            </el-form-item>
        </el-form>
    </div>
</template>
<script >
export default {
    props: ['params'],
    data() {
        return {
            defaultProps: {
                value: 'id', // 唯一标识
                label: 'label', // 标签显示
                children: 'children',
                emitPath: false
            },
            formData: {
                communityId: '',
                expirationTime: '',
                cardNo: '',
                cardType: 2,
                userId: '',
                username: ''
            },
            formRules: {
                communityId: [this.$valid.selectRequired('所属社区')],
                userId: [this.$valid.selectRequired('员工')],
                expirationTime: [this.$valid.selectRequired('到期时间')],
                cardNo: [
                    {
                        required: true,
                        message: `卡号不能为空`,
                        trigger: 'change',
                        validator(rule, value, cb) {
                            if (!value) {
                                cb(new Error());
                            } else {
                                cb();
                            }
                        }
                    }
                ]
            },
            communityArr: [],
            findUser: []
        };
    },
    methods: {
        getorgTree() {
            this.$http
                .get('/sc-community/assets/community/list')
                .then((data) => {
                    this.communityArr = data.data;
                })
                .catch(function () {});
        },
        getUserList() {
            this.$http.get('/sc-user-center/user/findUserList').then(({ data, status, msg }) => {
                this.findUser = data;
            });
        },
        findUserToggle() {
            this.formData.username = this.$refs.userName.getCheckedNodes()[0].label;
        },
        submit() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    let installData = JSON.parse(JSON.stringify(this.formData));
                    this.gateIds.map((item, index) => {
                        installData.gateIds.push({ deviceId: item });
                    });
                    this.writeCard(installData);
                }
            });
        },
        //验证绑定
        queryBinding(cardNo) {
            this.$http.get('/sc-gate-web/gateCard/queryBinding', { cardNo: cardNo }).then(({ data, status, msg }) => {
                if (status == 0) {
                    if (data == 0) {
                        this.formData.cardNo = cardNo;
                    } else {
                        this.$message.warning('此卡已绑定，请更换卡或格式化卡');
                    }
                }
            });
        },
        //读卡
        getReadCard() {
            new Promise((resolve) => {
                this.$http.get('/card/load').then(({ data, status, msg }) => {
                    if (status == 0) {
                        if (!!data) {
                            // this.$message.success(msg);
                            resolve && resolve(data);
                        } else {
                            this.$message.warning('没有读取到卡号');
                        }
                    } else {
                        this.$message.error('读取失败');
                    }
                });
            }).then((res) => {
                this.queryBinding(res);
            });
        },
        //格式化
        formatCard() {
            this.$http.get('/card/format').then(({ data, status, msg }) => {
                if (status == 0) {
                    this.$message.success(data);
                }
            });
        },
        writeCard(installData) {
            let ids = () => {
                let newAr = [],
                    devNo = [];
                installData.gateIds.map((item) => {
                    newAr.push(item.deviceId);
                });

                let newObj = this.gateList.filter((item, index) => {
                    return newAr.includes(item.id);
                });
                newObj.map((item) => {
                    devNo.push(item.deviceNo);
                });
                return devNo;
            };
            let inFrom = {
                depId: installData.communityId,
                expire_date: installData.expirationTime,
                guids: ids().join(',')
            };
            new Promise((resolve) => {
                this.$http.post('/card/issue/manage', [inFrom]).then(({ data, status, msg }) => {
                    if (status == 0) {
                        this.$message.success(msg);
                        resolve && resolve();
                    } else {
                        this.$message.error(msg);
                    }
                });
            }).then((res) => {
                this.isOk(installData);
            });
        },
        isOk(installData) {
            var loading = this.$loading();
            this.$http
                .post('/sc-gate-web/gateCard/add', installData)
                .then(({ status, msg }) => {
                    if (status == 0) {
                        this.$message.success(msg);
                        this.params.callback();
                        this.$emit('close');
                    } else {
                        this.$message.error(msg);
                    }
                    loading.close();
                })
                .catch(() => {
                    loading.close();
                });
        }
    },
    created() {
        this.getorgTree();
        this.getUserList();
    }
};
</script>
<style lang="scss" scoped>
@import '@assets/css/public-style.scss';
.formContent-item_title {
    line-height: rem(20);
}
.form-item-flex {
    display: flex;
    .form-item-flex-input {
        width: rem(165) !important;
        margin-left: rem(20);
        margin-bottom: 0 !important;
        &:first-child {
            margin: 0;
        }
    }
}
.disCarInput {
    display: inline-block;
    font-size: 12px;
    line-height: rem(30);
    margin-left: rem(20);
    &:first-child {
        margin: 0;
    }
}
.el-checkbox {
    margin-bottom: rem(20);
}
.disCardButton {
    padding: 0 rem(15);
    text-align: center;
    font-size: rem(14);
    height: rem(30);
    box-sizing: border-box;
    border-radius: rem(2);
    border: 1px solid #e0e1e3;
    color: #535766;
    display: inline-block;
    cursor: pointer;
    &.is-active {
        color: #0eaeff;
        border-color: #0eaeff;
    }
    &:active {
        color: #0eaeff6b;
        border-color: #0eaeff6b;
    }
    &:not(:last-child) {
        margin-right: rem(20);
    }
}
.buttonSelect {
    padding: 0 rem(15);
    text-align: center;
    font-size: rem(14);
    height: rem(30);
    box-sizing: border-box;
    border-radius: rem(2);
    border: 1px solid #e0e1e3;
    color: #535766;
    display: inline-block;
    cursor: pointer;
    &.is-active,
    &.is-checked {
        color: #0eaeff;
        border-color: #0eaeff;
    }
    &:not(:last-child) {
        margin-right: rem(20);
    }
}
/deep/ .el-radio-button .el-radio-button__inner,
/deep/ .el-checkbox-button .el-checkbox-button__inner {
    border: none;
    box-sizing: border-box;
    padding: 0;
    line-height: rem(24);
    margin-top: rem(2);
    display: block;
}

/deep/ .el-radio-button__orig-radio:checked + .el-radio-button__inner,
/deep/ .el-checkbox-button.is-checked .el-checkbox-button__inner {
    color: #0eaeff;
    background-color: white;
    box-shadow: none;
}
</style>