<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>
            <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="name">
                    <Input v-model="formValidate.name" placeholder="请输入" />
                </FormItem>
                <FormItem :label="`经销商ID：`">
                    <!-- <Input v-model="formValidate.tenancyId" placeholder="请输入" /> -->
                    <Select v-model="formValidate.tenancyId" placeholder="请选择（选填）" transfer>
                        <Option v-for="item in storeList" :key="item.id" :value="item.id" :label="item.name">{{item.name}}</Option>
                    </Select>
                </FormItem>
                <FormItem label="可用话术：">
                    <TreeSelect v-model="formValidate.typeIdList" :loading="filterLoading" multiple show-checkbox :data="typeTreeList" v-width="400" />
                </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 TreeSelect from './tree-select/tree-select'
import tablePageMixin from '_m/tablePage.mixin'
export default {
    mixins: [tablePageMixin],
    components: {
        userBox,
        TreeSelect
    },
    data() {
        return {
            loading: false,
            btnLoading: false,
            filterLoading: false,
            tableData: [],
            showDialog: false,
            formValidate: {
                id: undefined,
                tenancyId: undefined,
                name: undefined,
                typeIdList: [],
            },
            ruleValidate: {
                name: [
                    { type: 'string', required: true, message: '请输入', trigger: 'blur' }
                ],
                typeIdList: [
                    { type: 'number', required: true, message: '请选择', trigger: 'change' }
                ],
            },
            tableHeight: 0,
            typeList: [],
            storeList: []
        }
    },
    computed: {
        ...mapState({
            user: (state) => state.user, //
        }),
        typeTreeList () {
            let data1 = this.typeList.filter(item => item.callPlatform === 'PENG_YUE').map(item => {
                return {
                    title: item.name,
                    value: item.id,
                    selected: false,
                    checked: false,
                }
            })
            let data2 = this.typeList.filter(item => item.callPlatform === 'YI_WISE').map(item => {
                return {
                    title: item.name,
                    value: item.id,
                    selected: false,
                    checked: false,
                }
            })
            let data3 = []
            if (data1.length) {
                data3.push({
                    title: 'PENG_YUE',
                    expand: true,
                    value: 'PENG_YUE',
                    selected: false,
                    checked: false,
                    children: data1
                })
            }
            if (data2.length) {
                data3.push({
                    title: '一知智能',
                    expand: true,
                    value: 'YI_WISE',
                    selected: false,
                    checked: false,
                    children: data2
                })
            }
            let data4 = []
            if (data3.length) {
                data4.push({
                    title: '全部',
                    expand: true,
                    value: 'ALL',
                    selected: false,
                    checked: false,
                    children: data3
                })
            }
            return data4
        },
        tableColumns() {
            let columns = [
                {
                    title: '经销商',
                    minWidth: 140,
                    key: 'name',
                    align: 'center',
                },
                {
                    title: '可用话术',
                    minWidth: 340,
                    key: 'typeList',
                    align: 'left',
                    render: (h, params) => {
                        const array = []
                        const { row, index } = params
                        let typeList = row.typeList || []
                        typeList.forEach(item => {
                            array.push(h('div', {
                                style: {
                                },
                            }, item.name))
                        })
                        return h('Poptip', {
                            props: {
                                placement: 'right-end',
                                trigger: 'hover',
                                transfer: true,
                            }
                        }, [
                            h('div', {
                                style: {
                                    display: '-webkit-box',
                                    '-webkit-line-clamp': 3,
                                    '-webkit-box-orient': 'vertical',
                                    overflow: 'hidden',
                                    textOverflow: 'ellipsis',
                                }
                            }, array),
                            h('div', {
                                slot: 'content',
                                style: {
                                    maxHeight: '320px',
                                    overflowY: 'auto'
                                }
                            }, array)
                        ])
                    }
                },
                {
                    title: '操作',
                    align: 'center',
                    minWidth: 80,
                    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',
                                lineHeight: '17px',
                            },
                            on: {
                                click: (event) => {
                                    this.handleEdit(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.getTypeList()
        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)
            })
        },
        getStoreList () {
            this.$http.get(`/call/yiwise/api/tenancy/options`).then((response) => {
                const { code, data, msg } = response
                if (code === 1) {
                    this.storeList = data || []
                }
            })
        },
        handleSearch() {
            this.currentPage = 1
            this.initData()
        },
        initData() {
            this.$http.post(`/call/api/call-store/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,
                tenancyId: undefined,
                name: undefined,
                typeIdList: []
            }
            this.$refs['formValidate'].resetFields()
        },
        handleEdit (row) {
            this.showDialog = true
            this.formValidate = {
                id: row.id,
                tenancyId: row.tenancyId,
                name: row.name,
                typeIdList: (row.typeList || []).map(i => i.id),
            }
        },
        handleOk(name) {
            this.$refs[name].validate((valid) => {
                if (valid) {
                    this.btnLoading = true
                    this.$http.post(`/call/api/call-store/m/${this.formValidate.id ? 'update' : 'add'}`, {
                        ...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
                    })
                }
            })
        },
        getTypeList (name) {
            this.filterLoading = true
            this.$http.post(`/call/api/call-task-type/findListByPageAll?page=1&pageCount=1000`, {
                name
            }).then((response) => {
                const { code, data, msg } = response
                if (code === 1) {
                    this.typeList = (data && data.records) || []
                }
            }).finally(() => {
                this.filterLoading = false
            })
        },
    },
}
</script>
<style lang="less" scoped>
.store_page {
    .page_content {}
}
</style>
