<template>
  <div class="op-page build-page">
     <div class="top-btn-div">
       {{file?file.name:""}}
        <Upload ref="upload" accept=".zip" :show-upload-list="false" :action="uploadUrl" :before-upload="handleUpload" :format="docList"  :on-success="handleSuccess">
            <Button icon="ios-cloud-upload-outline">选择文件</Button>
        </Upload>
        <Button type="primary" class="btn" @click="upload" :loading="loadingStatus">开始上传</Button>
    </div>
    <cs-carousel :data="carouselData" class="center-carousel" :carouselSize="carouselSize">
      <template slot="form" scope="props">
        <div class="table-carousel">
          <div class="table-tip">
            <label>{{props.obj.name}}({{props.obj.version+","+props.obj.type}})</label>
            <div class="icon-menus">
             
               <Tooltip :content="props.obj.description!='null'?props.obj.description:'暂无描述信息'" placement="top">
                   <Icon type="ios-information-circle-outline" />
              </Tooltip>
              <Icon v-for="item in icons" :type="item.type" @click="clickIcon(props,item.action)"/>
              <Icon
                type="ios-trash-outline"
                @click="clickIcon(props,'delete')"
                v-if="props.obj.type!='deploy'&&props.obj.name!='ms-base'"
              />
            </div>
          </div>
          <Table :columns="columns" :data="props.obj.status" :height="height"></Table>
        </div>
      </template>
    </cs-carousel>
    <Modal v-model="modalFlag" title="参数配置" width="50" :mask-closable="false" @on-cancel="closeModal">
      <build-params @close-modal="closeModal" ref="modal"></build-params>
      <div slot="footer"></div>
    </Modal>
    <Modal v-model="logFlag" title="日志管理" width="80" :mask-closable="false" @on-cancel="closeLogModal">
      <build-log  ref="log"></build-log>
      <div slot="footer"></div>
    </Modal>
    <Modal v-model="serviceFlag" title="部署服务" width="50" :mask-closable="false" @on-cancel="closeModal">
      <build-service @close-modal="closeModal" ref="service" @get-data="getCarouselData"></build-service>
      <div slot="footer"></div>
    </Modal>
   <!-- <Modal v-model="deployFlag" title="组件升级" width="50" :mask-closable="false" @on-cancel="closeModal">
      <build-deploy @close-modal="closeModal" ref="deploy" @get-data="getCarouselData"></build-deploy>
      <div slot="footer"></div>
    </Modal>-->
    <Modal v-model="deployFlag" title="组件部署升级确认" width="50" :mask-closable="false" @on-cancel="closeModal">
      <!-- <p><span class="deploy-span">组件名称</span><span>升级部署信息</span></p>
      <p v-for="(value,key) in deployPreCheckInfo.compDeployInfo">
        <span class="deploy-span"><strong>{{key}}</strong></span>
        <span>{{value=='-1'?'已经是最新版本或更高版本，将不执行操作。':value}}</span>
      </p>
      <div slot="footer">
        <Button type="primary" class="btn" @click="deployOrUpgradeComponent" :disabled="!deployPreCheckInfo.needOperate">开始升级部署</Button>
        <Button type="primary" class="btn" @click="closeModal">取消</Button>
      </div> -->
       <build-deploy @close-modal="closeModal" ref="deploy"></build-deploy>
       <div slot="footer">
         <Button type="primary" class="btn" @click="deployOrUpgradeComponent" :disabled="!deployPreCheckInfo.needOperate">开始升级部署</Button>
         <Button type="primary" class="btn" @click="closeModal">取消</Button>
       </div>
    </Modal>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import BuildParams from "./build-params.vue";
import BuildLog from "./build-log.vue";
import BuildService from "./build-service.vue";
import BuildDeploy from "./build-deploy.vue";

@Component({
  components: {
    BuildParams,
    BuildLog,
    BuildService,
    BuildDeploy
  }
})
export default class Build extends Vue {
  height : number = 0;
  carouselData : Array<any> = [];
  modalFlag : boolean = false;
  logFlag : boolean = false;
  serviceFlag : boolean = false;
  deployFlag : boolean = false;
  loadingStatus : boolean = false;
  clickStartFlag : boolean = false;
  calculateHeightFlag : boolean = false;
  docList : Array<any>  = ['zip'];
  deployPreCheckInfo:any={};
  file : any =null;
  uploadUrl : String = this.$msPrefix.config +'/api/v1/comp/deploy/preCheck';
  deployUrl:String = this.$msPrefix.config +'/api/v1/comp/deploy/component';
  icons : Array<any> = [
    { type: "ios-add-circle-outline", action: "add" },
    // { type: "ios-cloud-upload-outline", action: "upload" }
  ];
  timer : any =null;
  actions: Array<any> = [
    [
      { icon: "ios-play", action: "start", label: "启动", type: "info",loading:false,notDisabled:true },
      {
        icon: "ios-settings",
        action: "manage",
        label: "配置",
        type: "primary",notDisabled:true
      },
      { icon: "md-trash", action: "delete", label: "删除", type: "error",loading:false },
      {
        icon: "ios-list-box-outline",
        action: "log",
        label: "日志",
        type: "success",loading:false,notDisabled:true
      }
    ],
    [
      { icon: "ios-pause", action: "pause", label: "停止", type: "warning",loading:false ,notDisabled:true},
      {
        icon: "ios-settings",
        action: "manage",
        label: "配置",
        type: "primary",loading:false,notDisabled:true
      },
      { icon: "md-trash", action: "delete", label: "删除", type: "error",loading:false },
      {
        icon: "ios-list-box-outline",
        action: "log",
        label: "日志",
        type: "success",loading:false,notDisabled:true
      }
    ],
      [
          { icon: "ios-playstation", action: "start", label: "启动中", type: "info",loading:true,disabled:true},
          {
              icon: "ios-settings",
              action: "manage",
              label: "配置",
              type: "primary",notDisabled:true
          },
          { icon: "md-trash", action: "delete", label: "删除", type: "error",loading:false,disabled:true },
          {
              icon: "ios-list-box-outline",
              action: "log",
              label: "日志",
              type: "success",loading:false,notDisabled:true
          }
      ],
      [
          { icon: "ios-sync", action: "start", label: "同步中", type: "info",loading:true ,disabled:true},
          {
              icon: "ios-settings",
              action: "manage",
              label: "配置",
              type: "primary",notDisabled:true
          },
          { icon: "md-trash", action: "delete", label: "删除", type: "error",loading:false,disabled:true },
          {
              icon: "ios-list-box-outline",
              action: "log",
              label: "日志",
              type: "success",loading:false,notDisabled:true
          }
      ]
  ];
  columns: Array<any> = [
    {
      key: "profile",
      title: "组件地址",
      align: "center",
      minWidth: 120,
      render: (h, params) => {
        return h(
          "span",
          {},
          params.row.componentKey.profile +
            "(" +
            params.row.ip +
            ":" +
            params.row.port +
            ")"
        );
      }
    },

    {
      key: "status",
      title: "状态",
      align: "center",
      width: 70
    },
    {
      title: "操作",
      key: "action",
      width: 280,
      align: "left",
      render: (h, params) => {
        let statusMap = {
          UP: 1,
          DOWN: 0,
          STARTING:2,
          SYNCING:3
        };
        let clickEvent = this.clickEvent;
        return h("div", [
          h("CsButton", {
            props: {
              actions: params.row.actions,
              click: clickEvent,
              data: params.row,
              size: "small",
              styleCss: "marginRight:5px",
              disabled: params.row.componentKey.profile=="default"
            }
          })
        ]);
      }
    }
  ];

handleUpload(file){
  if(!file.name.endsWith(".zip")){
    this.$tools.message('warning','文件 ' + file.name + ' 是不被允许的格式, 请上传 zip格式文件')
  }else{
     this.file=file;
  }
  return false;
}
save() {
    let config = {
      headers: {
        "Content-Type": "multipart/form-data"
      }
    };
    let formData = new FormData();
    formData.append("file", this.file);

    this.getApiData('post',this.uploadUrl,formData,res=>{
       this.deployFlag=true;
        this.deployPreCheckInfo=res.data;
        this.file=null;
        (this.$refs.deploy as any).setTableData(this.deployPreCheckInfo)
    },err=>{
        this.file=null;
    },config)
  }

upload () {
  if(this.file==null){
    this.$tools.message('warning','请先上传zip格式部署包');return;
  }
  this.loadingStatus = true;
  this.save();
  }
handleFormatError(file){
  this.$tools.message('warning','文件 ' + file.name + ' 是不被允许的格式, 请上传 zip格式文件')
}
handleSuccess(res, file){
    setTimeout(()=>{
      (this.$refs.upload as any).clearFiles()
    },500);
    if(res.code==-1){
      this.$tools.message('error',res.msg);
    }else{
      //this.getCarouselData()
    }
  }

  deployOrUpgradeComponent(){
      this.getApiData("post", this.deployUrl, this.deployPreCheckInfo, res => {
          if(res.rtnCode==0){
              this.loadingStatus = false;
              this.deployFlag=false;
              this.getCarouselData()
              this.$tools.message("info","操作成功，请启动或重启对应组件的服务生效！")
          }else{
              this.$tools.message('error',res.msg);
          }
      })
  }
  clickEvent(name: string, obj: any,index : number, action : any) {
    this[name](obj, action);
  }
  clickIcon(props, action) {
    if(action=='add'){
      (this.$refs.service as any).receiveData(props.obj);
      this.serviceFlag=!0;
    }else if(action=='delete'){
      this.deleteComponent(props.obj)
    }else if(action=='upload'){
      this.upgradeComponent(props.obj)
    }
  }
  upgradeComponent(obj){
    this.deployFlag=!0;
  }
  deleteComponentSuccessBack(){
    this.getCarouselData();
  }
  deleteComponent(obj){
    this.$tools.deleteEntity(this,this.$msPrefix.config +"/api/v1/comp/"+obj.id,this.deleteComponentSuccessBack);
  }
  get carouselSize() {
    let num = Math.floor((9 * document.body.clientWidth) / 2560);
    let size = 0;
    if (num >= 4) {
      size = 4;
    }
    if (num >= 6) {
      size = 6;
    }
    if (num >= 9) {
      size = 9;
    }
    return size;
  }
  getCarouselData() {
    let url = this.$msPrefix.config + "/api/v1/comp/list";
    this.getApiData("get", url, {}, res => {
      if(this.clickStartFlag){return;}
      if (res.data.length > 0) {
        this.carouselData=[];
        res.data.forEach(item => {
          if (item.status.length > 0) {
            item.status.forEach(element => {
              element.componentId = item.id;
               let statusMap = {
                UP: 1,
                DOWN: 0,
                STARTING:2,
                SYNCING:3
              };
              element.actions=_.cloneDeep(this.actions[statusMap[element.status]])
            });
          }
        });
        this.carouselData=res.data;
        this.$nextTick(()=>{
          if(!this.calculateHeightFlag){
            this.height=jq(".table-carousel .ivu-table-wrapper").height();
            this.calculateHeightFlag=!0;
          }
        })
      }
    });
  }

  pause(obj,action) {
    this.$Modal.confirm({
        title: '提示',
        content: '停止将会导致服务不可用，确定停止？',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          action.loading=true;
          if(obj.loading){this.$tools.message('info','服务正在停止中，请稍等')}
          this.getApiData(
            "get",
            this.$msPrefix.config + "/api/v1/comp/stop/" + obj.ip + "/" + obj.port,
            {},
            res => {
              setTimeout(()=>{
                action.loading=false;
                this.getCarouselData();
              },3000)
            },err=>{
              action.loading=false;
            }
          );
        },
        onCancel: () => {
          this.$tools.message('info','已取消启动')
        }
    })


  }

  start(obj,action) {
    console.error(111,obj,action);
    this.clickStartFlag=true;
    action.loading=true;
    this.getApiData("get",this.$msPrefix.config + "/api/v1/comp/startup/" +obj.componentId +"?profile=" +obj.componentKey.profile,{},
        res => {
          obj.status="STARTING";
          obj.actions=this.actions[2];
          this.$tools.message('info','启动服务需要大约1分钟左右的时间，可以点击日志查看启动状态')
          setTimeout(()=>{
            //action.loading=false;
            this.clickStartFlag=false;
          },15000)
        },err=>{
          this.clickStartFlag=false;
          action.loading=false;
        }
      );


    
  }

  manage(obj) {
    this.modalFlag = !0;
    (this.$refs.modal as any).getRunningParams(_.cloneDeep(obj));
  }

  log(obj) {
    this.logFlag = !0;
    (this.$refs.log as any).showLogDialogHandler(obj);
  }

  closeModal() {
    this.modalFlag = !1;
    this.serviceFlag = !1;
    this.deployFlag = !1;
    (this.$refs.modal as any).activeIndex="0";
    (this.$refs.modal as any).editIndex=-1;
    (this.$refs.service as any).resetField();
    this.loadingStatus=false;
  }
  
  closeLogModal() {
    this.logFlag = !1;
    (this.$refs.log as any).logContent = "";
    clearInterval((this.$refs.log as any).logInterval);
    (this.$refs.log as any).activeIndex="0";
    (this.$refs.log as any).showHistory=!1;
     (this.$refs.log as any).resetField();
   (this.$refs.log as any).serviceLogPosMap={}
  }
  deleteSuccessBack() {
    this.getCarouselData();
  }
  delete(obj) {
    this.$tools.deleteEntity(
      this,
      this.$msPrefix.config +
        "/api/v1/comp/delete/componentInstance/" +
        obj.componentKey.applicationName +
        "/" +
        obj.componentKey.profile,
      this.deleteSuccessBack
    );
  }

  mounted() {
    this.getCarouselData();
    clearInterval(this.timer);
    this.timer=setInterval(()=>{
        this.getCarouselData();
    },6000)
  }
  //退出页面需要清空掉定时器
  beforeRouteLeave(to, from, next) {
     clearInterval(this.timer);
     next();
  }
}
</script>