<template>
    <div class="page">
        <LayoutTable notDel :data="tableData" :config="tableConfig">

          <el-button
              slot="table-head-left2"
              style="margin-left: 10px"
              type="primary"
              class="addclass"
              size="mini"
              @click="handleImport"
          >导入项目文件包
          </el-button>

          <el-button
              slot="table-head-left2"
              style="margin-left: 10px"
              type="primary"
              class="addclass"
              size="mini"
              @click="batchDistribute"
          >批量部署
          </el-button>
                    </LayoutTable>



        <drawer-show ref="drawerform" @ok="getData" />


      <!-- 项目导入对话框 -->
      <el-dialog
          :title="upload.title"
          :visible.sync="upload.open"
          width="400px"
          append-to-body
      >
        <el-upload
            ref="upload"
            :limit="1"
            accept=".zip,.tar.gz"
            :headers="upload.headers"
            :action="upload.url"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            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 slot="footer" class="dialog-footer">
          <el-button type="primary" class="addclass" @click="submitFileForm"
          >确 定</el-button
          >
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 项目引导导入对话框 -->
      <el-dialog
          :title="guide.title"
          :visible.sync="guide.open"
          width="400px"
          show-close=false
          close-on-click-modal=false
          append-to-body
      >
        <el-upload
            ref="guide"
            :limit="1"
            accept=".zip,.tar.gz"
            :headers="guide.headers"
            :action="guide.url"
            :disabled="guide.isUploading"
            :on-progress="handleGuideFileUploadProgress"
            :on-success="handleGuideFileSuccess"
            :auto-upload="false"
            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 slot="footer" class="dialog-footer">
          <el-button type="primary" class="addclass" @click="submitGuideFileForm"
          >确 定</el-button
          >
          <el-button @click="guide.open = false">取 消</el-button>
        </div>
      </el-dialog>



      <el-dialog
          :title="tree.title"
          :visible.sync="tree.open"
          width="40%"
          append-to-body
      >
      <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
      >

        <el-divider></el-divider>

        <div>
          <el-input placeholder="请输入内容" v-model="siteName">
            <template slot="prepend">站点名称</template>
          </el-input>
        </div>

        <el-divider></el-divider>

        <el-scrollbar style="height: 100%">
          <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>
        </el-scrollbar>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" class="addclass" @click="updateSiteConform"
          >确 定</el-button
          >
          <el-button @click="tree.open = false">取 消</el-button>
        </div>
      </el-dialog>

    </div>
</template>

<script>
    /** 表单弹出框模式需引入 */
    import drawerShow from "./drawershow";
    import table from "@/assets/mixins/table";
    import tree from "@/assets/mixins/tree";
    export default {
        name: "SetupProjectList",
        components: {
            drawerShow
        },
        mixins: [table,tree],
      mounted() {
        this.timer = setInterval(this.syncProjectStatus, 1000 * 60);
      },
        created() {
          //检测是否初始安装
          this.$get("/setup/project/check")
              .then((res) => {
                if (res.code == 1) {
                  console.log(res)
                  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.tree.open=true;
                        }else{

                        }
                      }else{
                        console.log("初始化基础项目！")
                        this.$post("/setup/project/projectDataInit", {},{isLoading:true})
                            .then((res) => {
                              if (res.code == 1) {
                                this.$message.success("基础项目应用部署启动成功！");
                                this.getData();
                              }
                            })
                            .catch((error) => {
                              this.$message.error(error.message);
                            });

                        //判断是否已经更新站点等信息
                      }
                  }else{
                    //弹框引导页面
                    this.guide.open = true;
                    console.log("弹出项目初始引导页")
                  }
                }
              })
              .catch((error) => {
                this.$message.error(error.message);
              });


/*          //获取区域树
          this.$get("/base/area/getListByParentId", {
            parentId: "0",
          })
              .then((res) => {
                if (res.code == 1) {
                  //this.info=res.data

                  this.areaData=res.data.result
                  console.log(this.areaData)
               // this.tree.open=true
                }
              })
              .catch((error) => {
                this.$message.error(error.message);
              });*/

        },
        methods: {
          handleNodeClick(node) {
            this.currentNode = node;
            this.areaCode=node.areaCode
            this.areaName=node.label
            console.log("node:",node)
          },

          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) => {
                  if (res.code == 1) {
                    this.$message.success("创建站点成功！");
                    this.getData();
                    this.tree.open = false;
                  }
                })
                .catch((error) => {
                  this.loading = false;
                  this.$message.error(error.message);
                });
          },

          /** 导入 */
          handleImport() {
            this.upload.title = "项目文件包导入";
            this.upload.open = true;
           // this.tree.open=true
            console.log(this.areaData)
          },
            /** 重写新增方法 */
            toAdd(row) {
                this.$refs.drawerform.add(row);
            },
            /** 重写编辑方法 */
            toEdit(row) {
                this.$refs.drawerform.edit(row);
            },
            /** 重写查看方法 */
            toView(row) {
                this.$refs.drawerform.view(row);
            },
          distribute(row) {
            this.$post("/setup/project/distribute", row,{isLoading:true})
                .then((res) => {
                  if (res.code == 1) {
                    //this.$message.success("项目部署成功！");
                    this.getData();
                  }
                })
                .catch((error) => {
                  this.$message.error(error.message);
                });
          },


          batchDistribute(row) {
              if(this.selection.length==0){
                this.$message.error("请勾选需要部署的项目！");
                return;
              }
            this.$post("/setup/project/batchDistribute", {
              idList: this.selection,
            },{isLoading:true})
                .then((res) => {
                  if (res.code == 1) {
                    this.$message.success("批量部署成功！");
                    this.getData();
                  }
                })
                .catch((error) => {
                  this.$message.error(error.message);
                });
          },

          updateArea(row) {
            //todo 更新子区域信息  前提条件 是基础服务已经运行
            this.$message.info("更新子区域信息  前提条件 是基础服务已经运行");

            this.$prompt('请输入子区域名称', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消'
            }).then(({ value }) => {

              let param={};
              param['name']=value;
              this.$post("/base/area/list", param)
                  .then((res) => {
                    if (res.code == 1) {
                      if(res.data.data&&res.data.data.length>0){
                        let area=res.data.data[0];
                        this.$confirm('是否更新当前'+area.name+'为子区域?', '提示', {
                          confirmButtonText: '确定',
                          cancelButtonText: '取消',
                          type: 'warning'
                        }).then(() => {

                           let param={};
                           param['areaCode']=area.areaCode;
                           param['id']=row.id;
                          this.$post("/setup/project/area/update", param)
                              .then((res) => {
                                if (res.code == 1) {
                                  this.$message.success("子区域更新成功！");
                                  this.getData();
                                }
                              })
                              .catch((error) => {
                                this.$message.error(error.message);
                              });
 /*
                          this.$message({
                            type: 'success',
                            message: '更新成功!'
                          });*/
                        }).catch(() => {
                          this.$message({
                            type: 'info',
                            message: '更新失败'
                          });
                        });

                      }
                    }
                  })
                  .catch((error) => {
                    this.$message.error(error.message);
                  });

            }).catch(() => {
              this.$message({
                type: 'info',
                message: '取消输入'
              });
            });

          },

          updateSite(row) {
              //todo 更新站点区域信息  前提条件 是基础服务与门户服务已经运行
           // this.$message.info("更新站点区域信息  前提条件 是基础服务与门户服务已经运行");
            this.tree.open = true
          },

          updateSiteApp(row) {
            //todo 更新站点应用，前提条件需要提交站点id
            this.$message.info("更新站点应用，前提条件需要提交站点id");
            let param={};
            param['areaCode']='';
            param['siteName']='';
            param['id']=row.id;
            this.$post("/setup/project/app/deploy", param)
                .then((res) => {
                  if (res.code == 1) {
                    this.$message.success("自助服务应用部署！");
                    this.getData();
                  }
                })
                .catch((error) => {
                  this.$message.error(error.message);
                });
          },

          updateSiteMatter(row) {
            this.$confirm('更新站点事项，需要服务器可访问外网?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {

              let param={};
              param['id']=row.id;
              this.$post("/setup/project/matter/update", param)
                  .then((res) => {
                    if (res.code == 1) {
                      this.$message.success(res.msg);
                    }
                  })
                  .catch((error) => {
                    this.$message.error(error.message);
                  });
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消更新'
              });
            });

          },

          /** 文件上传中处理 */
          handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
          },
          /** 文件上传成功处理 */
          handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
            this.getData();
          },
          /** 提交上传文件 */
          submitFileForm() {
            this.$refs.upload.submit();
          },

          /** 文件上传中处理 */
          handleGuideFileUploadProgress(event, file, fileList) {
            this.guide.isUploading = true;
          },
          /** 文件上传成功处理 */
          handleGuideFileSuccess(response, file, fileList) {
            this.guide.open = false;
            this.guide.isUploading = false;
            this.$refs.guide.clearFiles();
            this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
            console.log("response",response)
            //todo进行项目初始化安装
            if(response.code==1){
              this.$post("/setup/project/projectDataInit", {},{isLoading:true})
                  .then((res) => {
                    if (res.code == 1) {
                      this.$message.success("基础项目应用部署启动成功！");
                      this.getData();
                    }
                  })
                  .catch((error) => {
                    this.$message.error(error.message);
                  });
            }
          },

          /** 提交上传文件 */
          submitGuideFileForm() {
            this.$refs.guide.submit();
          },

          async loadNode(node, resolve) {
            if (node.areaLevel === 0) {
              return;
            }
            this.$get("/base/area/getListByParentId", {
              parentId: node.data.id,
            }).then(({ data }) => {
              resolve(data.result);
            });
          },

          syncProjectStatus() {
            this.$post("/setup/project/projectStatusUpdate", { })
                .then((res) => {
                  if (res.code == 1) {
                   this.getData()
                  }
                })
                .catch((error) => {

                });
          },

          start(row) {
            this.$post("/setup/project/start", row)
                .then((res) => {
                  if (res.code == 1) {
                    this.$message.success("项目应用启动成功,稍后更新项目状态!");
                  }
                })
                .catch((error) => {

                });
          },

        },
        data() {
            return {
              // 用户导入参数
              upload: {
                // 请求头
                headers:{
                  Authorization:''
                },
                // 是否显示弹出层（设备导入）
                open: false,
                // 弹出层标题（设备导入）
                title: "上传项目工程包",
                // 是否禁用上传
                isUploading: false,
                // 上传的地址
                url: "/m/setup/project/importProjectData",
              },

              guide: {
                // 是否显示弹出层（设备导入）
                open: false,
                // 弹出层标题（设备导入）
                title: "上传项目工程包",
                // 是否禁用上传
                isUploading: false,
                // 上传的地址
                url: "/m/setup/project/importProjectDataInit",
              },
              tree: {
                // 是否显示弹出层（设备导入）
                open: false,
                // 弹出层标题（设备导入）
                title: "选择区域创建站点"
              },
              timer: "",
              areaName: "",
              areaCode: "",
              siteName: "",
              siteCode: "",
              siteInfo: {},
              updateSiteId: null,
              updateSiteName: "",
              updateSiteCode: "",

                config: {
                    search: [
                    ],
                    columns: [
                      {
                        type: "selection",
                        align: "center",
                        reserveSelection: true,
                        width: 60,
                      },
                        {type: "index",label: "序号",width: 50},

                      {label: "所属站点", prop: "siteName",width: 120},

                        {label: "项目产品名称", prop: "name"},

                        {label: "项目产品编码", prop: "projectCode"},

                      /*    {label: "项目部署地址", prop: "projectPath"},

                  {label: "项目shell地址", prop: "projectShell"},*/

  /*                      {label: "项目源文件地址", prop: "sourceProject"},

                        {label: "数据库地址", prop: "dbHost"},

                        {label: "数据库端口", prop: "dbPort"},*/

           /*             {label: "数据库用户", prop: "dbUser"},

                        {label: "数据库密码", prop: "dbPassword"},

                        {label: "数据库名称", prop: "dbName"},*/


                        {label: "项目类型", prop: "projectType",formatter: this.formatter},

                        {label: "项目状态", prop: "projectStatus",formatter: this.formatterStatus},

                        {label: "备注",width: 200, prop: "remark"},
                        {
                            label: "操作",
                            width: 280,
                            formatter: row => {
                                return (

                                    <div>
                                      <table-buttons
                                          noAdd
                                          noDel
                                          noView
                                          row={row}
                                          onEdit={this.toEdit}
                                          onView={this.toView}
                                          onDel={this.toDel}
                                      />
                                      <span> </span>
                                      <el-button
                                          size="mini"
                                          type="text"
                                          icon="el-icon-open"
                                          onClick={() => {
                                            this.distribute(row);
                                          }}
                                      >
                                        部署
                                      </el-button>

                                      <span> </span>

                                      {row.projectType === 1&&row.projectStatus>1&&row.projectStatus<4 ? (
                                          <el-button
                                              size="mini"
                                              type="text"
                                              icon="el-icon-open"
                                              onClick={() => {
                                                this.start(row);
                                              }}
                                          >
                                            启动项目
                                          </el-button>
                                      ) : (
                                          ""
                                      )}

                                      <span> </span>


                                      {row.projectCode === 'base-manager' ? (
                                          <el-button
                                              size="mini"
                                              type="text"
                                              icon="el-icon-open"
                                              onClick={() => {
                                                this.updateSite(row);
                                              }}
                                          >
                                            创建站点
                                          </el-button>
                                      ) : (
                                          ""
                                      )}

                                      <span> </span>

                                      {row.projectCode === 'base-manager' ? (
                                          <el-button
                                              size="mini"
                                              type="text"
                                              icon="el-icon-open"
                                              onClick={() => {
                                                this.updateSiteMatter(row);
                                              }}
                                          >
                                            站点事项更新
                                          </el-button>
                                      ) : (
                                          ""
                                      )}


                                    </div>

                            );
                            }
                        }
                    ]
                }
            };
        }
    };
</script>


