<template>
    <div class="store_page">
        <div class="page_header">
            <div class="header_left">
                <div class="header_label">用户管理</div>
            </div>
            <div class="header_right">
                <userBox />
            </div>
        </div>
        <div class="filter_box">
            <div class="filter_left">
                <div class="filter_item">
                    <label>手机号：</label>
                    <Input v-model="phone" icon="ios-search" placeholder="请输入" clearable @on-change="handleSearch" />
                </div>
                <div class="filter_item">
                    <label>经销商：</label>
                    <Select v-model="storeId" clearable @on-change="handleSearch">
                        <Option v-for="item in storeList" :key="item.id" :value="item.id" :label="item.name">{{item.name}}</Option>
                    </Select>
                </div>
            </div>
            <div class="filter_right">
                <div class="add_btn" @click="handleAdd">新增用户</div>
            </div>
        </div>
        <div class="page_content" ref="tableContent">
            <div class="table_content">
                <!--表格-->
                <Table row-key="id" :loading="loading" :height="tableHeight" :columns="tableColumns" :data="tableData">
                </Table>
                <!-- 分页 -->
                <Page :total="total" :current="currentPage" show-total show-sizer @on-change="handleCurrentChange"
                    @on-page-size-change="handlePageSize" :page-size-opts="pageSizeOpts" />
            </div>
        </div>
        <Modal scrollable v-model="showDialog" width="442">
            <div slot="header">
                <p>{{ formValidate.id ? '编辑用户' : '新增用户' }}</p>
            </div>
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="120">
                <FormItem :label="`手机号：`" prop="phone">
                    <Input v-model="formValidate.phone" :maxlength="11" placeholder="请输入"></Input>
                </FormItem>
                <FormItem label="经销商：" prop="storeId">
                    <Select v-model="formValidate.storeId" transfer>
                        <Option v-for="item in storeList" :key="item.id" :value="item.id" :label="item.name">{{item.name}}</Option>
                    </Select>
                </FormItem>
                <FormItem :label="`短信模板ID：`">
                    <Input v-model="formValidate.smsAfterCallParam" placeholder="请输入" />
                </FormItem>
            </Form>
            <template slot="footer">
                <Button class="cancel-btn" @click="showDialog = false">取消</Button>
                <Button class="confirm-btn" type="primary" :loading="btnLoading"
                    @click="handleOk('formValidate')">确定</Button>
            </template>
        </Modal>
    </div>
</template>
<script>
import { mapState } from 'vuex'
import { debounce, checkPhone } from '@/utils'
import userBox from '@/pages/platform/components/userBox'
import tablePageMixin from '_m/tablePage.mixin'
export default {
    mixins: [tablePageMixin],
    components: {
        userBox
    },
    data() {
        return {
            loading: false,
            btnLoading: false,
            tableData: [],
            showDialog: false,
            formValidate: {
                id: undefined,
                phone: undefined,
                smsAfterCallParam: undefined,
                storeId: undefined,
            },
            ruleValidate: {
                phone: [
                    { required: true, validator: this.handleValidatePhone.bind(this), trigger: 'blur' }
                ],
                // smsAfterCallParam: [
                //     { type: 'string', required: true, message: '请输入', trigger: 'blur' }
                // ],
                storeId: [
                    { type: 'number', required: true, message: '请选择', trigger: 'change' }
                ],
            },
            phone: null,
            tableHeight: 0,
            storeList: [],
            storeId: null
        }
    },
    computed: {
        ...mapState({
            user: (state) => state.user, //
        }),
        tableColumns() {
            let columns = [
                {
                    title: '手机号',
                    minWidth: 140,
                    key: 'phone',
                    align: 'left',
                },
                {
                    title: '经销商',
                    minWidth: 140,
                    key: 'store',
                    align: 'center',
                    render: (h, params) => {
                        const { row } = params
                        let text = (row.store && row.store.name) || ''
                        return h('span', undefined, text)
                    },
                },
                {
                    title: '短信模板ID',
                    minWidth: 140,
                    key: 'smsAfterCallParam',
                    align: 'center'
                },
                {
                    title: '状态',
                    minWidth: 140,
                    key: 'status',
                    align: 'center',
                    render: (h, params) => {
                        const { row } = params
                        let text = ''
                        if (row.userStatus === 1) {
                            return (
                                h('span', {
                                    style: {
                                        color: '#35E89A'
                                    }
                                }, '正常')
                            )
                        } else if (row.userStatus === -1) {
                            return (
                                h('span', {
                                    style: {
                                        color: '#cccccc'
                                    }
                                }, '已禁用')
                            )
                        } else {
                            return (
                                h('span', {
                                    style: {
                                        color: '#999999'
                                    }
                                }, '未激活')
                            )
                        }
                    }
                },
                {
                    title: '操作',
                    align: 'left',
                    minWidth: 100,
                    render: (h, params) => {
                        const array = []
                        const { row, index } = params
                        array.push(h('div', {
                            style: {
                                margin: '5px 10px 5px 0',
                                color: '#1677FF',
                                cursor: 'pointer',
                                display: 'inline-block',
                                paddingRight: '30px',
                                lineHeight: '17px',
                            },
                            on: {
                                click: (event) => {
                                    this.handleEdit(row)
                                }
                            }
                        }, '编辑'))
                        if (row.userStatus !== -1) {
                            array.push(h('div', {
                                style: {
                                    margin: '5px 10px 5px 0',
                                    color: '#FF4E4E',
                                    cursor: 'pointer',
                                    display: 'inline-block',
                                    lineHeight: '17px',
                                },
                                on: {
                                    click: (event) => {
                                        this.handleDelete(row)
                                    }
                                }
                            }, '禁用'))
                        }
                        return h('div', array)
                    }
                }
            ]
            return columns
        }
    },
    created () {
        this.handleCalcTableHeight()
        const resize = debounce(() => {
            this.handleCalcTableHeight()
        }, 300)
        window.addEventListener('resize', resize)
        this.$once('hook:beforeDestroy', () => {
            window.removeEventListener('resize', resize)
        })
        this.getStoreList()
        this.initData()
    },
    methods: {
        handleValidatePhone(rule, value, callback) {
            if (!value) {
                //callback(new Error('请输入手机号'))
                callback()
            } else if (!checkPhone(value)) {
                callback(new Error('请输入正确的手机号'))
            } else {
                callback()
            }
        },
        handleCalcTableHeight () {
            this.$nextTick().then(() => {
                const tableContent = this.$refs['tableContent']
                let tableContentHeight = 0
                if (tableContent) {
                    // 普通的 html节点
                    tableContentHeight = tableContent.getBoundingClientRect().height
                }
                this.tableHeight = tableContentHeight - (32 + 40 + 58)
            })
        },
        handleSearch() {
            this.currentPage = 1
            this.initData()
        },
        initData() {
            this.$http.post(`/call/api/user/m/findListByPage?page=${this.currentPage}&pageCount=${this.pageSize}`, {
                phone: this.phone,
                storeId: this.storeId
            }).then((response) => {
                let { data, code, msg } = response
                if (code === 1) {
                    this.tableData = data.records
                    this.total = data.total
                } else {
                    this.$Notice.warning({
                        desc: msg
                    })
                }
            })
        },
        handleAdd() {
            this.showDialog = true
            this.formValidate = {
                id: undefined,
                phone: undefined,
                smsAfterCallParam: undefined,
                storeId: undefined,
            }
        },
        handleEdit(row) {
            this.showDialog = true
            this.formValidate = {
                id: row.id,
                phone: row.phone,
                smsAfterCallParam: row.smsAfterCallParam || undefined,
                storeId: (row.store && row.store.id) || undefined,
            }
        },
        getStoreList () {
            this.$http.post(`/call/api/call-store/findListByPage?page=1&pageCount=1000`, {}).then((response) => {
                const { code, data, msg } = response
                if (code === 1) {
                    this.storeList = data.records
                }
            })
        },
        handleOk(name) {
            this.$refs[name].validate((valid) => {
                if (valid) {
                    this.btnLoading = true
                    this.$http.post(`/call/api/user/m/${this.formValidate.id ? 'updateUser' : 'addUser'}`, {
                        ...this.formValidate,
                    }).then((response) => {
                        let { code, msg } = response
                        if (code === 1) {
                            this.$Notice.success({
                                title: msg,
                            })
                            this.showDialog = false
                            this.handleSearch()
                        } else {
                            this.$Notice.warning({
                                desc: msg
                            })
                        }
                    }).finally(() => {
                        this.btnLoading = false
                    })
                }
            })
        },
        handleDelete(row) {
            this.$Modal.confirm({
                title: '提示',
                content: `<div class="confirm_cont text_conter">确认禁用该用户？</div>`,
                onOk: () => {
                    this.$http.post(`/call/api/user/m/forbiddenUser`, {
                        id: row.id
                    }).then((response) => {
                        let { code, msg } = response
                        if (code === 1) {
                            this.$Notice.success({
                                title: msg,
                            })
                            this.handleSearch()
                        } else {
                            this.$Notice.warning({
                                desc: msg
                            })
                        }
                    })
                }
            })
        },
    },
}
</script>
<style lang="less" scoped>
.store_page {
    .page_content {}
}
</style>
