<template>
    <div class="config_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="name" icon="ios-search" placeholder="请输入" clearable @on-change="handleSearch" />
                </div>
                <div class="filter_item">
                    <label>话术模板：</label>
                    <Select class="w240" v-model="apiTaskId" :clearable="true" placeholder="全部" @on-change="handleSearch">
                        <Option v-for="item in existOptions" :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="500">
            <div slot="header">
                <p>{{ formValidate.id ? '编辑配置' : '新增配置' }}</p>
            </div>
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="140">
                <FormItem :label="`话术名称：`" prop="name">
                    <Input v-model="formValidate.name" :maxlength="11" placeholder="请输入"></Input>
                </FormItem>
                <FormItem label="经销商：" prop="tenancyId">
                    <Select v-model="formValidate.tenancyId" transfer @on-change="changeTenancy">
                        <Option v-for="item in storeList" :key="item.id" :value="item.id" :label="item.name">{{item.name}}</Option>
                    </Select>
                </FormItem>
                <FormItem label="话术模板：" prop="apiTaskId">
                    <Select v-model="formValidate.apiTaskId" transfer @on-change="changeDialogFlow">
                        <Option v-for="item in dialogFlowList" :key="item.id" :value="item.id" :label="item.name">{{item.name}}</Option>
                    </Select>
                </FormItem>
                <FormItem label="短信模板：" prop="smsTemplateId">
                    <Select v-model="formValidate.smsTemplateId" transfer @on-change="changeSmsTemplate">
                        <Option v-for="item in smsTemplateList" :key="item.id" :value="item.id" :label="item.name">{{item.name}}</Option>
                    </Select>
                </FormItem>
                <template v-if="formValidate.callParameter">
                    <FormItem v-for="(value, key) in formValidate.callParameter" :label="`$（${key}）：`" :key="key" :prop="`callParameter.${key}`" :rules="{required: true, message: `请输入${key}变量`, trigger: 'blur'}">
                        <Input v-model="formValidate.callParameter[key]" placeholder="请输入" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }"></Input>
                    </FormItem>
                </template>
            </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 } 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,
                name: undefined,
                smsTemplateId: undefined,
                tenancyId: undefined,
                apiTaskId: undefined,
                callParameter: undefined
            },
            ruleValidate: {
                name: [
                    { type: 'string', required: true, message: '请输入', trigger: 'blur' }
                ],
                tenancyId: [
                    { type: 'number', required: true, message: '请选择', trigger: 'change' }
                ],
                apiTaskId: [
                    { type: 'number', required: true, message: '请选择', trigger: 'change' }
                ],
                smsTemplateId: [
                    { type: 'number', required: true, message: '请选择', trigger: 'change' }
                ],
            },
            name: null,
            tableHeight: 0,
            dialogFlowList: [],
            storeList: [],
            smsTemplateList: [],
            storeId: null,
            existOptions: [],
            apiTaskId: null
        }
    },
    computed: {
        ...mapState({
            user: (state) => state.user, //
        }),
        tableColumns() {
            let columns = [
                {
                    title: '话术名称',
                    minWidth: 120,
                    key: 'name',
                    align: 'left',
                },
                {
                    title: '经销商',
                    minWidth: 120,
                    key: 'tenancyName',
                    align: 'center',
                },
                {
                    title: '话术模板',
                    minWidth: 180,
                    key: 'dialogFlowName',
                    align: 'center'
                },
                {
                    title: '操作',
                    align: 'center',
                    minWidth: 130,
                    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)
                                }
                            }
                        }, '编辑'))
                        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
        }
    },
    watch: {
        showDialog (val) {
            if (val) {
                this.dialogFlowList = []
                this.smsTemplateList = []
            }
        }
    },
    created () {
        this.handleCalcTableHeight()
        const resize = debounce(() => {
            this.handleCalcTableHeight()
        }, 300)
        window.addEventListener('resize', resize)
        this.$once('hook:beforeDestroy', () => {
            window.removeEventListener('resize', resize)
        })
        this.getExistOptions()
        this.getStoreList()
        this.initData()
    },
    methods: {
        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()
        },
        getExistOptions () {
            this.$http.get(`/call/yiwise/api/tenancy/dialogFlow/exist-options`).then((response) => {
                const { code, data, msg } = response
                if (code === 1) {
                    this.existOptions = data || []
                }
            })
        },
        getStoreList () {
            this.$http.get(`/call/yiwise/api/tenancy/options`).then((response) => {
                const { code, data, msg } = response
                if (code === 1) {
                    this.storeList = data || []
                }
            })
        },
        getDialogFlowList () {
            this.$http.get(`/call/yiwise/api/tenancy/dialogFlow/options`, {
                params: {
                    tenancyId: this.formValidate.tenancyId
                }
            }).then((response) => {
                const { code, data, msg } = response
                if (code === 1) {
                    this.dialogFlowList = data || []
                }
            })
        },
        getSmsTemplateList () {
            this.$http.get(`/call/yiwise/api/tenancy/smsTemplate/options`, {
                params: {
                    tenancyId: this.formValidate.tenancyId
                }
            }).then((response) => {
                const { code, data, msg } = response
                if (code === 1) {
                    this.smsTemplateList = data || []
                }
            })
        },
        getVariables () {
            this.$http.get(`/call/yiwise/api/tenancy/dialogFlow/variables`, {
                params: {
                    dialogFlowId: this.formValidate.apiTaskId,
                    smsTemplateId: this.formValidate.smsTemplateId,
                    tenancyId: this.formValidate.tenancyId
                }
            }).then((response) => {
                let { data, code, msg } = response
                if (code === 1) {
                    let variablesList = data || []
                    this.formValidate.callParameter = variablesList.length ? variablesList.reduce((acc, key) => {
                        acc[key] = (this.formValidate.callParameter && this.formValidate.callParameter[key]) || ''
                        return acc
                    }, {}) : undefined
                } else {
                    this.$Notice.warning({
                        desc: msg
                    })
                }
            })
        },
        changeTenancy () {
            if (this.formValidate.tenancyId) {
                this.getDialogFlowList()
                this.getSmsTemplateList()
            }
            if (this.formValidate.tenancyId && this.formValidate.apiTaskId && this.formValidate.smsTemplateId) {
                this.getVariables()
            }
        },
        changeDialogFlow () {
            if (this.formValidate.tenancyId && this.formValidate.apiTaskId && this.formValidate.smsTemplateId) {
                this.getVariables()
            }
        },
        changeSmsTemplate() {
            if (this.formValidate.tenancyId && this.formValidate.apiTaskId && this.formValidate.smsTemplateId) {
                this.getVariables()
            }
        },
        initData() {
            this.$http.get(`/call/yiwise/api/tenancy/callTaskType/page`, {
                params: {
                    name: this.name,
                    apiTaskId: this.apiTaskId,
                    page: this.currentPage,
                    pageCount: this.pageSize
                }
            }).then((response) => {
                let { data, code, msg } = response
                if (code === 1) {
                    this.tableData = data.records
                    this.total = data.total
                } else {
                    this.$Notice.warning({
                        desc: msg
                    })
                }
            })
        },
        getDetail () {
            this.$http.get(`/call/yiwise/api/tenancy/callTaskType/detail`, {
                params: {
                    callTaskTypeId: this.formValidate.id
                }
            }).then((response) => {
                const { code, data, msg } = response
                if (code === 1) {
                    const { id, name, smsTemplateId, tenancyId, apiTaskId, callParameter } = data
                    this.formValidate = {
                        id: id || undefined,
                        name: name || undefined,
                        smsTemplateId: Number(smsTemplateId) || undefined,
                        tenancyId: Number(tenancyId) || undefined,
                        apiTaskId: Number(apiTaskId) || undefined,
                        callParameter: (callParameter ? JSON.parse(callParameter) : undefined)
                    }
                    if (this.formValidate.tenancyId) {
                        this.getDialogFlowList()
                        this.getSmsTemplateList()
                    }
                    if (this.formValidate.tenancyId && this.formValidate.apiTaskId && this.formValidate.smsTemplateId) {
                        this.getVariables()
                    }
                }
            })
        },
        handleAdd() {
            this.showDialog = true
            this.formValidate = {
                id: undefined,
                name: undefined,
                smsTemplateId: undefined,
                tenancyId: undefined,
                apiTaskId: undefined,
                callParameter: undefined
            }
            this.$refs['formValidate'].resetFields()
        },
        handleEdit(row) {
            this.showDialog = true
            this.$refs['formValidate'].resetFields()
            this.formValidate = {
                id: row.id,
                name: row.name,
                smsTemplateId: row.smsTemplateId || undefined,
                tenancyId: row.tenancyId || undefined,
                apiTaskId: row.apiTaskId || undefined,
                callParameter: undefined
            }
            if (this.formValidate.id) {
                this.getDetail()
            }
            if (this.formValidate.tenancyId) {
                this.getDialogFlowList()
                this.getSmsTemplateList()
            }
            if (this.formValidate.tenancyId && this.formValidate.apiTaskId && this.formValidate.smsTemplateId) {
                this.getVariables()
            }
        },
        handleOk(name) {
            this.$refs[name].validate((valid) => {
                if (valid) {
                    this.btnLoading = true
                    this.$http.post(`/call/api/call-task-type/save`, {
                        id: this.formValidate.id || undefined,
                        name: this.formValidate.name,
                        smsTemplateId: this.formValidate.smsTemplateId,
                        tenancyId: this.formValidate.tenancyId,
                        apiTaskId: this.formValidate.apiTaskId,
                        callParameter: JSON.stringify(this.formValidate.callParameter || {}),
                        dialogFlowName: this.dialogFlowList.filter(i => i.id === this.formValidate.apiTaskId)[0].name
                    }).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/call-task-type/delete?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>
.config_page {
    .w240{
        width: 240px !important;
    }
    .page_content {}
}
</style>
