<template>
    <div class="main">
        <div class="bg">
            <div class="steps">
                <div :class="index == active ? 'step active' : 'step'" v-for="(item, index) in tabList" :key="item">{{
                    item }}
                </div>
            </div>
            <!-- 第一步 -->
            <div v-show="active == 0">
                <div class="label">
                    上传
                </div>
                <div class="line"></div>
                <div class="upload">
                    <el-upload ref="nowupload" :limit="1" accept=".zip,.tar.gz" :headers="upload.headers"
                        :action="upload.url" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress"
                        :on-success="handleFileSuccess" :auto-upload="false" :file-list="fileList" drag>
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">
                            将文件拖到此处，或
                            <em>点击上传</em>
                        </div>
                        <div class="el-upload_tip" style="color: red" slot="tip">
                            提示：仅允许导入“zip”或“.tar.gz”格式压缩文件！
                        </div>
                    </el-upload>
                </div>
                <div class="line"></div>
                <el-button type="primary" @click="submitFileForm" :loading="loading">下一步</el-button>
            </div>
            <!-- 第二步 -->
            <div v-show="active == 1">
                <div class="label">创建站点</div>
                <div class="line"></div>
                
                <div style="margin:20px 0;">
                    <span style="font-size: 14px">
                        <b>当前选择区域:</b>
                        (<el-link style="margin-left: 10px;margin-bottom: 5px" type="primary" class="addclass"
                            :underline="false">
                            {{ areaName }}
                        </el-link>
                        区域编码：{{ areaCode }} )
                    </span>
                </div>
                <div class="tree">
                    <el-tree size="mini" ref="areaTree" :data="areaData" id="el-tree" node-key="id" indent="4"
                        :props="treeProps" :load="loadNode" lazy highlight-current :expand-on-click-node="false"
                        :render-content="renderContent" @node-click="handleNodeClick">
                    </el-tree>
                </div>
                <div class="elinput" style="margin:20px 0;">
                    <el-input placeholder="请输入内容" v-model="siteName">
                        <template slot="prepend">站点名称</template>
                    </el-input>
                </div>
                <div class="line"></div>
                <el-button type="primary" @click="active = 0">上一步</el-button>
                <el-button type="primary" @click="updateSiteConform" :loading="loading">下一步</el-button>
            </div>
            <!-- 第三步 -->            
            <div v-show="active == 2">
                <div style="height: 500px; overflow: auto; margin-bottom:20px">
                    <div class="layout-table">
                        <div class="table-body">
                            <el-table
                                size='small'
                                ref="steptable"
                                :data="tableData.data"
                                @selection-change="handleSelectionChange"
                            >
                                <el-table-column
                                    v-for='column in config.columns'
                                    :key='column.prop'
                                    :type="column.type"
                                    :prop="column.prop"
                                    :label="column.label"
                                    :width="column.width"
                                    :formatter='column.formatter'
                                    :selectable="handleSelectableMethod"
                                >

                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                </div>
                <el-button type="primary" @click="batchDistribute">下一步</el-button>
            </div>
            <!-- 第四步 -->
            <div v-show="active == 3">
                <div class="label">ip配置</div>
                <div class="line"></div>
                <el-form :model="ippzForm" :rules="ippzRules" ref="ippzForm"  label-width="80px">
                    <el-form-item prop="clientToServerIp">
                        <div class="elinput">
                            <el-input placeholder="请输入设备通讯ip,不能输入端口号" v-model="ippzForm.clientToServerIp">
                                <template slot="prepend">
                                    <div style="width:80px;text-align: center;">设备通讯ip</div>
                                </template>
                            </el-input>
                        </div>
                    </el-form-item>  
                    <el-form-item prop="domain">  
                        <div class="elinput">
                            <el-input placeholder="请输入域名" v-model="ippzForm.domain">
                                <template slot="prepend">
                                    <div style="width:80px;text-align: center;">
                                        域名
                                    </div>
                                    </template>
                            </el-input>
                        </div>
                    </el-form-item>  
                    <el-form-item prop="innerServerIp">
                    <div class="elinput">
                        <el-input placeholder="请输入内网ip,不能输入端口号" v-model="ippzForm.innerServerIp">
                            <template slot="prepend">
                                <div style="width:80px;text-align: center;">
                                    内网ip
                                </div>
                            </template>
                        </el-input>
                    </div>
                    </el-form-item>  
                    <div style="margin: 40px 0;"></div>
                    <div class="line"></div>
                    <el-button type="primary" @click="active = 2">上一步</el-button>
                    <el-button type="primary" @click="submitJCForm('ippzForm')" :loading="loading">下一步</el-button>
                </el-form>
            </div>
            <!-- 第五步 -->
            <div v-show="active == 4">
                <div class="label">完成</div>
                <div class="line"></div>
                <div class="wancheng">
                    <div class="cgtext">
                        欢迎您，模块文件安装成功！站点已创建成功！
                    </div>
                    <div class="cgtext">
                        请点击下面的按钮进入选中网页进行操作！
                    </div>
                </div>
                <div class="line"></div>
                <el-button type="primary" @click="gotoMh">门户网站</el-button>
                <!-- <el-button type="primary" @click="gotoSet">项目部署管理</el-button> -->
            </div>

        </div>
    </div>
</template>

<script>
import tree from "@/assets/mixins/tree";
import axios from "axios";
import {
  formatter
} from "@/assets/utils/table";
// import table from "@/assets/mixins/table";
export default {
    // mixins: [table,tree],
    mixins: [tree],
    data() {
        return {
            // 表单
            ippzForm: {
                clientToServerIp:"",//设备通讯ip
                domain:"", //域名
                innerServerIp:""//内网ip
            },
            // 表单验证
            ippzRules: {
                clientToServerIp: [
                    { required: true, message: '请输入设备通讯ip', trigger: 'blur' },
                    {
                        pattern:/^((2[0-4]\d.)|(25[0-5].)|(1\d{2}.)|(\d{1,2}.))((2[0-5]{2}.)|(1\d{2}.)|(\d{1,2}.){2})((1\d{2})|(2[0-5]{2})|(\d{1,2}))/,    //正则校验不用字符串
                        message: "请填写正确的设备通讯ip", trigger: "blur"
                    }

                ],
                domain: [
                    { required: true, message: '请输入域名', trigger: 'blur' }
                ],
                innerServerIp: [
                    { required: true, message: '请输入内网ip', trigger: 'blur' },
                    {
                        pattern:/^((2[0-4]\d.)|(25[0-5].)|(1\d{2}.)|(\d{1,2}.))((2[0-5]{2}.)|(1\d{2}.)|(\d{1,2}.){2})((1\d{2})|(2[0-5]{2})|(\d{1,2}))/,    //正则校验不用字符串
                        message: "请填写正确的内网ip", trigger: "blur"
                    }
                ]
            },
            // 用户导入参数
            upload: {
                // 请求头
                headers: {
                    Authorization: ''
                },
                // 是否显示弹出层（设备导入）
                open: false,
                // 弹出层标题（设备导入）
                title: "上传项目工程包",
                // 是否禁用上传
                isUploading: false,
                // 上传的地址
                url: "/m/setup/project/importProjectData",
            },
            areaName: "",
            areaCode: "",
            siteName: "",
            active: 0,
            tabList: [
                "1、项目文件包导入",
                "2、创建站点",
                "3、部署",
                "4、基础配置",
                "5、完成"
            ],
            loading: false,
            fileList: [],
            config: {
                columns: [
                    {
                        type: "selection",
                        align: "center",
                        reserveSelection: true,
                        width: 60,
                        props:"gouxuan"
                    },
                    {type: "index", prop: "xuhao",label: "序号",width: 50},
                    {label: "所属站点", prop: "siteName",width: 120},
                    {label: "项目产品名称", prop: "name"},
                    {label: "项目产品编码", prop: "projectCode"},
                    {label: "项目类型", prop: "projectType",formatter: this.formatter},
                    {label: "项目状态", prop: "projectStatus",formatter: this.formatterStatus},
                    {label: "备注",width: 200, prop: "remark"}
                ],
            },
            source: axios.CancelToken.source(),
            tableData: {
                // 表格数据
                loading: true, // ajax请求状态
                dict: {},
                result: [],
                pageInfo: {},
            },
            loadingTimer: null,
            selection: [], // 表格内置的多选
            nowTabdataStatus:1
        }
    },
    methods: {
        // 上传资源包
        objInstall() {
            //检测是否初始安装
            this.$get("/setup/project/check")
                .then((res) => {
                    if (res.code == 1) {
                        let reBool = res.data.resource //是否上传资源包
                        let projectBool = res.data.project //是否部署完成
                        let siteCode = res.data.siteCode //是否选择站点
                        if (reBool) {
                            if (projectBool) {
                                console.log("项目部署成功！")
                                if (!siteCode || siteCode === '' || siteCode === 'undefined') {
                                    //选择站点
                                    this.active = 1
                                } else {
                                    //全部完成进入后台系统
                                    this.$router.push("/setup/project/list")
                                }
                            } else {
                                //有资源未部署重新上传
                                this.active = 0
                            }
                        } else {
                            //资源上传
                            this.active = 0
                        }
                    }
                })
                .catch((error) => {
                    this.$message.error(error.message);
                });
        },
        // 以下第四部分
        submitJCForm(formName){
            let that = this
            this.$refs[formName].validate((vaild)=>{
                if (vaild) {
                    that.$post("/setup/project/serverIp/update", {
                        ...that.ippzForm
                    }).then((res) => {
                        if (res.code == 1) {
                            // 跳转到下一页
                            that.active = 4
                        }else{
                            that.$message.warning(res.msg);
                        }
                    }).catch((err)=>{
                        that.$message.warning("请输入正确的表单内容！");
                    })
                } else {
                    that.$message.warning("请输入正确的表单内容！");
                    return false;
                }
            })
        },

        // 以下第三部分
        // 默认拉取数据
        async getData() {
            this.tableData.loading = true;
            this.$post('/setup/project/list', {}, {
                cancelToken: this.source.token,
            })
                .then(({ data }) => {
                    this.tableData = Object.assign({}, this.tableData, data)
                    this.nowTabdataStatus = 1
                })
                .catch((error) => {
                if (error.message == "自动取消ajax操作") return;
                this.$message.error(error.message);
                })
                .then((data) => {
                clearTimeout(this.loadingTimer);
                this.loadingTimer = setTimeout(() => {
                    this.tableData.loading = false;
                }, 300);
                });
        },
        // 刷新状态
        syncProjectStatus() {
            this.$post("/setup/project/projectStatusUpdate", { })
                .then((res) => {
                    if (res.code == 1) {
                    this.getData()
                    }
                })
        }, 
        // 格式转换
        formatterStatus(row, column, val) {
            const content = formatter(this.tableData, column, val);
            if (content) {
                if (val == "0") {
                return (
                    <el-tag type={"warning"} size="mini">
                    {content}
                    </el-tag>
                );
                } else if (val == "1") {
                return (
                    <el-tag type={"danger"} size="mini">
                    {content}
                    </el-tag>
                );
                } else if (val == "2") {
                return (
                    <el-tag type={"success"} size="mini">
                    {content}
                    </el-tag>
                );
                } else {
                return <el-tag size="mini">{content}</el-tag>;
                }
            } else {
                return val;
            }
        },
        // 格式化单元格数据
        formatter(row, column, val) {
            const content = formatter(this.tableData, column, val);
            return content ? (
                <el-tag type={"info"} size="mini">
                {content}
                </el-tag>
            ) : val ? (
                val
            ) : (
                "--"
            );
        },
        // 多选表格行
        handleSelectionChange(val) {
            this.selection = val.map((i) => i.id);
        },
        // 表格勾选部署
        handleSelectableMethod(row, index) {
            if(row.projectStatus==1){
                return true;
            }else{
                if(this.nowTabdataStatus){
                    this.$refs.steptable.toggleRowSelection(row,true)
                    if(index==this.tableData.data.length-1){
                        this.nowTabdataStatus = 0
                    }
                    
                }
                return false;
            }
        },
        // 点击部署
        batchDistribute(){
            let setlist = this.tableData.data.filter((item)=>{
                return item.projectStatus != 1
            }).map((item)=>{
                return item.id
            })
            let arr = this.selection.filter((item)=>{
                return setlist.indexOf(item) === -1
            })

            this.$post("/setup/project/batchDistribute", {
              idList: arr,
            },{isLoading:true})
                .then((res) => {
                  if (res.code == 1) {
                    this.$message.success("批量部署成功！");
                    this.active = 3
                  }
                })
                .catch((error) => {
                  this.$message.error(error.message);
                });
        },
        // 以下第四部分
        gotoMh() {
            window.location.href = process.env.VUE_APP_PORTAL_URL
        },
        gotoSet() {
            this.$router.push("/setup/project/list")
        },
        // 以下第二部分
        updateSiteConform() {
            if (this.areaCode === '' || this.areaCode === 'undefined') {
                this.$message.error("请选择需要创建站点的区域！");
                return;
            }

            if (this.siteName === '' || this.siteName === 'undefined') {
                this.$message.error("请选择需要创建站点的名称！");
                return;
            }
            this.loading = true;
            this.$post("/setup/project/site/updateSite", {
                areaCode: this.areaCode,
                siteName: this.siteName,
            }, { isLoading: true })
                .then((res) => {
                    this.loading = false;
                    if (res.code == 1) {
                        this.active = 2
                        this.getData();
                    }
                })
                .catch((error) => {
                    this.loading = false;
                    this.$message.error(error.message);
                });
        },
        async loadNode(node, resolve) {
            if (node.areaLevel === 0) {
                return;
            }
            this.$get("/base/area/getListByParentId", {
                parentId: node.data.id,
            }).then(({ data }) => {
                resolve(data.result);
            });
        },
        handleNodeClick(node) {
            this.currentNode = node;
            this.areaCode = node.areaCode
            this.areaName = node.label
        },
        // 以下第一部分
        /** 提交上传文件 */
        submitFileForm() {
            if (this.$refs.nowupload.uploadFiles.length) {
                this.loading = true
                this.$refs.nowupload.submit();
            } else {
                this.$message.error("请上传文件！");
            }
        },
        /** 文件上传中处理 */
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        /** 文件上传成功处理 */
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.nowupload.clearFiles();
            if (response.code == 1) {
                // 资源包上传完成后，进行部署
                this.$post("/setup/project/projectDataInit", {}, { isLoading: true })
                    .then((res) => {
                        if (res.code == 1) {
                            // 部署成功选择站点
                            this.active = 1
                            this.loading = false
                        }
                    })
                    .catch((error) => {
                        this.$message.error(error.message);
                    });
            } else {
                this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
            }
        },



    },
    created() {
        this.objInstall()
        // this.changePath()
    },      
    mounted() {
        this.timer = setInterval(this.syncProjectStatus, 1000*60);
        this.getData();
    },
}
</script>

<style lang="less" scoped>
.active {
    color: rgb(232, 245, 24);
}

// 第三部分
/deep/ .table-body{
    margin-left:0 !important;
}
// 第四部分
// 第五部分
.wancheng {
    margin-bottom: 350px;

    .cgtext {
        line-height: 30px;
    }
}

// 第二部分
.tree {
    width: 80%;
    height: 300px;
    overflow-y: auto;
    background: #ffffff;
}

.elinput {
    width: 70%;
}

// 第一部分
/deep/ .el-upload__text {
    font-size: 20px !important;
}

/deep/ .el-icon-upload {
    font-size: 97px !important;
    margin: 80px 0 40px !important;
}

/deep/.el-upload-dragger {
    width: 500px !important;
    height: 280px !important;
}

.upload {
    // width: 365px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 60px 0 80px;
}

.line {
    background: #00b2f5;
    width: 100%;
    height: 1px;
    margin: 20px 0;
}

.label {
    color: #333333;
    font-weight: 600;
    font-size: 14px;
}

.steps {
    display: flex;
    align-items: center;
    justify-content: space-around;
    color: #ffffff;
    font-weight: 600;
    font-size: 18px;
    background: linear-gradient(90deg, #029ad6 0%, #00b2f5 50%, #029ad6 100%);
    height: 50px;
    margin-bottom: 30px;
}

.bg {
    border-radius: 8px;
    background: rgba(255, 255, 255, .95);
    box-sizing: border-box;
    padding: 20px 30px;
    width: 100%;
    height: 100%;
}

.main {
    height: 100%;
    background: linear-gradient(90deg, #1845c6 0%, #2999ff 100%);
    padding: 32px 40px;
}
</style>