<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
            <el-form-item label="" prop="stage">
                <el-input
                    v-model="queryParams.stage"
                    placeholder="请输入期数"
                    clearable
                    size="small"
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="" prop="name">
                <el-input
                    v-model="queryParams.name"
                    placeholder="请输入平台"
                    clearable
                    size="small"
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                >新增</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 表格 -->
        <el-table :data="bookCityList">
            <el-table-column type="expand">
                <template slot-scope="props">
                    <el-form label-position="left" class="demo-table-expand" v-if="props.row.key1 !== ''">
                        <el-form-item :label="key" v-for="(val, key, index) in JSON.parse(props.row.key1)" :key="index">
                            <span>{{ val }}</span>
                        </el-form-item>
                    </el-form>
                </template>
            </el-table-column>
            <el-table-column label="期数" prop="stage" align="center"/>
            <el-table-column label="平台" prop="name" align="center"/>
            <el-table-column label="平台账号" prop="account" align="center"/>
            <el-table-column label="平台密码" prop="passWord" align="center"/>
            <el-table-column label="创建时间" prop="createTime" align="center"/>
            <el-table-column label="更新时间" prop="updateTime" align="center"/>
            <el-table-column label="备注" prop="remarks" align="center"/>
            <el-table-column label="操作" align="center" >
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleEdit(scope.row)"
                    >编辑</el-button>
                    <div style="display: inline-block;width: 10px"></div>
                    <el-popconfirm
                        title="确定删除吗？"
                        @confirm="handleDelete(scope.row)"
                    >
                        <el-button
                            slot="reference"
                            size="mini"
                            type="text"
                            icon="el-icon-delete"
                        >删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>    
        </el-table>
        <!-- 翻页 -->
        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />


        <!-- 新增弹窗 -->
        <el-dialog
            :title="isAdd ? '新增' : '编辑'" 
            :visible.sync="openEdit"
            width="450px"
            @close="dialogClose"
        >
            <el-form :model="queryPlatform" :rules="rules" ref="platForm" label-position="right" label-width="120px">
                <el-form-item label="期数" prop="stage">
                    <!-- <el-input
                        clearable
                        size="small"
                        v-model="queryPlatform.stage"
                    /> -->
                    <el-select v-model="queryPlatform.stage" placeholder="请选择" style="width: 100%" filterable>
                        <el-option
                            v-for="item in perodidAll"
                            :key="item.id"
                            :label="item.period"
                            :value="item.period">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="平台" prop="name">
                    <el-select v-model="queryPlatform.name" placeholder="请选择" @change="platFormChange" filterable style="width: 100%">
                        <el-option
                            v-for="item in platFormNames"
                            :key="item.id"
                            :label="item.label"
                            :value="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="平台账号" prop="account">
                    <el-input
                        clearable
                        size="small"
                        v-model="queryPlatform.account"
                    />
                </el-form-item>
                <el-form-item label="平台密码" prop="passWord">
                    <el-input
                        clearable
                        size="small"
                        v-model="queryPlatform.passWord"
                    />
                </el-form-item>
                <el-form-item :label="pf" :prop="queryPlatform.key1[pf]" v-for="(pf, index) in platFormName.value" :key="index">
                    <el-input
                        clearable
                        size="small"
                        v-model="queryPlatform.key1[pf]"
                    />
                </el-form-item>
                <el-form-item label="备注" prop="remarks">
                    <el-input
                        type="textarea"
                        clearable
                        size="small"
                        placeholder="请输入备注"
                        v-model="queryPlatform.remarks"
                    />
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="openEdit = false">取 消</el-button>
                <el-button type="primary" @click="submitPlat('platForm')">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import { addBookPlatInfo, getBookPlatInfo, delBookPlatInfo, editBookPlatInfo } from "@/api/accounts/bookCity";
import { getPeriodAll } from "@/api/accounts/period";
export default {
    name: 'bookCity',
    data() {
        return {
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                name: null,
                stage: null
            },
            showSearch: true,
            bookCityList: [],
            total: 0,
            queryPlatform: {
                stage: '',    //期数
                name: '',     //平台名称
                account: '',  //平台账号
                passWord: '', //密码
                key1: {},     
                remarks: ''    //备注
            },
            openEdit: false,
            rules: {
                stage: [
                    { required: true, message: '请输入期数', trigger: 'blur' }
                ],
                name: [
                    { required: true, message: '请选择平台', trigger: 'change' }
                ],
                account: [
                    { required: true, message: '请输入平台账号', trigger: 'blur' }
                ],
                passWord: [
                    { required: true, message: '请输入平台账号', trigger: 'blur' }
                ]
            },
            // 所有平台及key
            platFormNames: [
                {
                    label: '花生',
                    id: 1,
                    value: ["apiKey","apiSecurity"]
                },
                {
                    label: '文鼎',
                    id: 2,
                    value: ["consumerkey", "secretkey", "siteid"]
                },
                {
                    label: '阳光',
                    id: 3,
                    value: ["Client_id","Token"]
                },
                {
                    label: '悠书阁',
                    id: 4,
                    value: ["secert_key"]
                },
                {
                    label: '阅文',
                    id: 5,
                    value: ["secretkey"]
                },
                {
                    label: '掌读',
                    id: 6,
                    value: ["appsecret"]
                },
                {
                    label: '七悦',
                    id: 7,
                    value: ["AccessKey"]
                },
                {
                    label: '掌中云',
                    id: 8,
                    value: ["APIkey","APISecret"]
                },
            ],
            // 保存key1 
            platFormName: {
                label: '',
                value: []
            },
            // 是否新增
            isAdd: true,
            perodidAll: []
        }
    },
    created() {
        this.getList()
        this.getPeroid()
    },
    methods: {
        /** 获取所有分期平台 */
        getPeroid() {
            getPeriodAll().then(response => {
                this.perodidAll = response.data
            });
        },
        /** 新增 */
        handleAdd() {
            this.openEdit = true
            this.isAdd = true
        },
        /** 搜索 */
        handleQuery() {
            this.getList()
        },
        /** 搜索条件重置 */
        resetQuery() {
            this.resetForm("queryForm");
            this.getList()
        },
        /** 获取列表数据 */
        getList() {
            getBookPlatInfo(this.queryParams).then(response => {
                let data = response.data
                this.total = data.total
                let records = data.records
                this.bookCityList = records
            })
        },
        /** 表格编辑 */
        handleEdit(value) {
            this.resetQpf()
            this.isAdd = false
            this.openEdit = true
            console.log(value)
            let { stage, name, account, passWord, key1, remarks, id } = value
            key1 = JSON.parse(key1)
            console.log(key1)
            this.queryPlatform = { stage, name, account, passWord, key1, remarks, id }
            let filterArr = this.platFormNames.filter((item)=> {
                return item.label === name
            })
            this.platFormName = filterArr[0]
        },
        /** 删除平台 */
        handleDelete(value) {
            delBookPlatInfo(value.id).then(response => {
                if(response.data){
                    this.msgSuccess("删除成功");
                    this.getList()
                }else{
                    console.error(response)
                }
            })
        },
        /** 保存 */
        submitPlat(formName) {
            console.log(this.queryPlatform)
            let { key1 } = this.queryPlatform
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if(this.isAdd){
                        addBookPlatInfo({ ...this.queryPlatform, key1: JSON.stringify(key1) }).then(response => {
                            if(response.data){
                                this.openEdit = false
                                this.msgSuccess("新增成功");
                                this.getList()
                                this.resetQpf()
                            }else{
                                console.error(response)
                            }
                        })
                    }else {
                        console.log(this.queryPlatform)
                        editBookPlatInfo({ ...this.queryPlatform, key1: JSON.stringify(key1) }).then(response => {
                            if(response.data){
                                this.openEdit = false
                                this.msgSuccess("修改成功");
                                this.getList()
                                this.resetQpf()
                            }else{
                                console.error(response)
                            }
                        })
                    }
                    
                } else {
                    return false;
                }
            });
        },
        /** 重置添加编辑字段 */
        resetQpf() {
            this.queryPlatform = {  //重置
                stage: '',    //期数
                name: '',     //平台名称
                account: '',  //平台账号
                passWord: '', //密码
                key1: {},     
                remarks: ''    //备注
            }
        },
        /** 平台选中触发 */
        platFormChange(e) {
            let filterArr = this.platFormNames.filter((item)=> {
                return item.label === e
            })
            this.platFormName = filterArr[0]
            let {label, value} = this.platFormName
            this.queryPlatform = {
                ...this.queryPlatform,
                key1: {}
            }
            value.forEach((item) => {
                this.$set(this.queryPlatform.key1, item, '')
            })
        },
        /** 关闭弹窗触发 */
        dialogClose() {
            if(!this.isAdd){
                this.resetQpf()
                this.platFormName = {
                    label: '',
                    value: []
                }
            }
        }
    }
}
</script>

<style lang="scss">
    .demo-table-expand {
        font-size: 0;
        label {
            width: 90px;
            color: #99a9bf;
        }
        .el-form-item {
            margin-right: 0;
            margin-bottom: 0;
            width: 50%;
        }
    }
</style>