<template>
  <div class="TemplateManagementLists">
    <div class="listContent">
        <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain size="mini" @click="searchData.page = 1;queryLists()">查询</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain :disabled="listsStatus === 1" size="mini" @click="addTemplate">新建模板</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain size="mini" @click="templateMigration" v-if="listsStatus === 0">模版迁移</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain size="mini" @click="removeMigration" v-if="listsStatus === 1">取消迁移</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain size="mini" @click="perform" v-if="listsStatus === 1">执行</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain size="mini" @click="performAll" v-if="listsStatus === 1">执行全部</el-button>
        </el-col>
        </el-row>
      <Alert show-icon closable v-if="listsStatus === 1">依次单击模板可进行多选模板</Alert>
      <FormItemComponent
        class="form"
        :formItemLists="formLists"
        :buttonType="false"
        @formChange="formChange"
      ></FormItemComponent>

      <StandardTable
        class="table"
        :currentPage="searchData.page"
        :pageSize="searchData.pageSize"
        :pageSizeOpts="[20,40,60,80]"
        :total="total"
        :showTable="false"
        :standardTableEvent="standardTableEvent"
      >
      </StandardTable>

      <div class="list">
        <FormItemComponent
          class="listsForm"
          :formItemLists="listsConfig"
          :buttonType="false"
          :readonly="listsStatus === 1"
        ></FormItemComponent>

        <div  class="noData" v-if="listsConfig.length == 0" >
          <span>
            暂无模版
          </span>
        </div>
      </div>
    </div>

    <!-- 模版迁移弹窗 -->
    <Modal
      v-model="migrationModel"
      title="模版迁移"
      mask
      :width="440"
      :mask-closable="false"
      >
      <div class="migrationModelContent">
        <p>
          <Input v-model="serverUrl"  placeholder="请输入目标服务器地址" style="width: 320px" />
        </p>
      </div>

      <p slot="footer">
        <Button :loading="performloading" @click="migrationModel = false">取消</Button>
        <Button :loading="performloading" type="primary" @click="performConfirm">确定</Button>
      </p>
    </Modal>
  </div>
</template>
<script>
import FormItemComponent from '@/components/FormItemComponent';
import ItemComponent from '@/components/ItemComponent';
import StandardTable from '@/components/StandardTable';
import listModalComponent from '@/components/listModalComponent'
import {
    getSearch,
    setMigrate
  } from '@/api/modeler.js'

// import router from '../config/router.config'

import {  mapMutations,mapState } from 'vuex';
export default {
  name:'TemplateManagementLists',
  components:{FormItemComponent,StandardTable},
  data () {
    return {
      // 状态  0为搜索状态，1为模版迁移状态
      listsStatus:0,
      //表单配置
      formLists:[
        {
          row:1,
          col:1,
          component:ItemComponent,
          item:{
            type:'input',
            title:'模型名称',
            filed:'name',
            event:{
              'keydown': (event) => {
                if(event.keyCode === 13){
                  this.searchData.page = 1
                  this.queryLists()
                }
              }
            }
          }
        },
        {
          row:1,
          col:1,
          component:ItemComponent,
          item:{
            type:'select',
            title:'模版状态',
            filed:'status',
            options: [
              { value: 1, label: '已发布'},
              { value: 0, label: '未发布'},
              { value: 2, label: '已停用'}
            ],
            props:{
              multiple: true,
              multipleType: true
            },
            value:[0,1]
          }
        },
        {
          row:1,
          col:1,
          component:ItemComponent,
          item:{
            type:'DatePicker',
            title:'创建时间',
            filed:'createTime',
            value:[]
          }
        }
      ],
      //查询条件
      searchData:{
        page:1,
        pageSize:20,
        createTime:[],
        status: [0,1]
      },

      //分页数据
      total:0,
      standardTableEvent:{
        'on-change':(page) => {
          this.searchData.page = page
          this.queryLists()
        },
        'on-page-size-change':(pageSize) => {
          this.searchData.page = 1
          this.searchData.pageSize = pageSize
          this.queryLists()
        }
      },
      listsConfig:[  //列表数据
      ],

      // 迁移数据
      selectModal:[],  //选中的迁移模版
      migrationModel:false, //控制模版迁移弹窗
      serverUrl:null,  //目标服务地址
      migrationType:null,  //0为执行  1为执行全部
      performloading:false

    }
  },
  computed:{
    ...mapState({
      currentMenu:(state) =>{
        return  state.currentMenu
      }
    })
  },
  watch:{
    listsStatus () {
      if(this.listsStatus === 0){
        this.selectModal = []
      }
    }
  },
  methods:{
    ...mapMutations(['currentChange','changeKeepAliveArray']),
    formChange (data) {  //表单数据修改时，修改searchData数据
      if(data.status){
        this.formLists[0].item.value = data.name
        this.formLists[1].item.value = data.status
        this.formLists[2].item.value = data.createTime
        // this.formLists = this.formLists.concat([])
      }
      this.searchData = Object.assign({},this.searchData,data)
      if(Object.prototype.toString.call(this.searchData.status) === '[object Array]' && this.searchData.status.length === 0){
        delete this.searchData.searchStatus
        delete this.searchData.status
      }

      this.queryLists()
    },
    queryLists () {  //查询列表
      if(this.searchData.status && this.searchData.status.indexOf('bSelect-all') >= 0){
        this.searchData.searchStatus = []
      }else{
        this.searchData.searchStatus = this.searchData.status
      }

      if(this.searchData.createTime && this.searchData.createTime[0] && this.searchData.createTime[1]){
        this.searchData.startTime = new Date(this.searchData.createTime[0]).format('yyyy-MM-dd hh:mm')
        this.searchData.endTime = new Date(this.searchData.createTime[1]).format('yyyy-MM-dd hh:mm')
      }else{
        this.searchData.startTime = ''
        this.searchData.endTime = ''
      }
      let obj = Object.assign({},this.searchData)
      delete obj.createTime
      delete obj.status
      getSearch(obj).then((res) => {
        if(res.resultCode !== 0){
          return
        }
        let data = res.data
        this.total = data.total

        this.listsConfig = data.records.reduce((arr,item) => {
          let items = {
            event:{
              queryLists:() => {
                this.queryLists()
              }
            }
          }
          items = Object.assign(items,item)
          arr.push({
            row:1,
            col:1,
            component:listModalComponent,
            item:items
          })
          return arr
        },[])
      });
    },
    addTemplate () {  //新建模版
      this.changeKeepAliveArray(['modeler'])
      this.$router.push({ path: '/tool/activiti/TemplateManagementNew/-1' })
      this.currentChange({
        path:'/tool/activiti/modeler'
      });
    },
    templateMigration () { //模版迁移
      this.listsStatus = 1
    },
    removeMigration () {  //取消迁移
      this.listsStatus = 0
    },
    modalClick (event) {  //模版点击
      let value = event.detail.value
      let items = event.detail.items
      if(value){
        this.selectModal.push(items.id)
      }else{
        this.selectModal.splice(this.selectModal.findIndex(item => item === items.id), 1)
      }
    },
    perform () {  //执行迁移
      if(this.selectModal.length === 0){
        this.$Modal.fcWarning({
          title:'警告',
          content:'请选择需要迁移的模版!',
          mask:true
        })
        return
      }
      this.migrationType = 0
      this.serverUrl = null
      this.migrationModel = true

    },
    performAll () {  //迁移全部
      this.migrationType = 1
      this.serverUrl = null
      this.migrationModel = true
    },
    performConfirm () {  //模版迁移确认
      let obj = {}
      if(!(this.serverUrl.startsWith('http://') || this.serverUrl.startsWith('https://'))){
        this.$Modal.fcWarning({
          title:'警告',
          content:'目标服务器地址必须以http://或者https://开头',
          mask:true
        })
        return
      }
      this.performloading = true
      if(this.migrationType === 0){  //执行选中模版
        obj = {
          moduleIds:this.selectModal.join(',')
        }
      }else{  //执行所有模版
        if(this.searchData.createTime && this.searchData.createTime[0] && this.searchData.createTime[1]){
          this.searchData.startTime = new Date(this.searchData.createTime[0]).format('yyyy-MM-dd hh:mm')
          this.searchData.endTime = new Date(this.searchData.createTime[1]).format('yyyy-MM-dd hh:mm')
        }else{
          this.searchData.startTime = ''
          this.searchData.endTime = ''
        }

        obj = Object.assign({},this.searchData)
      }

      obj.url = this.serverUrl
      setMigrate(obj).then((res) => {
          if(res.resultCode === 0){
            this.$Modal.fcSuccess({
              title:'成功',
              content:res.resultMsg,
              onOk: () => {
                this.queryLists()
                this.listsStatus = 0
                this.migrationModel = false
                this.performloading = false
              }
            })

          }else{
            this.$Modal.fcError({
              title:'错误',
              content:res.resultMsg,
              onOk: () => {
                this.performloading = false
              }
            })
          }
        })
    }
  },
  created () {
    //判断首页跳转状态，修改查询条件
    let status = Number(this.$route.query.status)
    if(status){
      this.searchData.status = [status]
      this.formLists[1].item.value = [status]
      this.formLists = this.formLists.concat([])
      console.log(this.formLists,8888888)
    }
    this.queryLists()
  },
  mounted () {
    // 监听modal的点击事件
    window.addEventListener('modalClick',this.modalClick)
  },
  beforeDestroy () {
    window.removeEventListener('modalClick', this.modalClick);
  },
  activated () {
    this.queryLists()
  }
}
</script>
<style lang="scss" >
.TemplateManagementLists{
  display: flex;
  flex-direction: column;
  .listContent{
    background: white;
    flex: 1;
    padding: 16px;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .title{
      font-size:18px;
      font-family:PingFangSC-Medium;
      font-weight:500;
      color:rgba(81,90,110,1);
      line-height:24px;
      margin-bottom: 16px;
    }

    .buttonLists{
      margin-bottom: 10px;
      >button{
        width: 90px;
        margin-right: 10px;
      }
    }
    .form{
      margin-bottom: 16px;
    }

    .list{
      flex: 1;
      margin-right: -16px;
      overflow: auto;
      position: relative;
      .listsForm{
        border: none;
        padding: 0;
        margin-left: 5px;
        margin-top: 5px;

        .FormItemComponent-item{
          margin-right: 16px;
          margin-bottom: 20px;
        }
      }

      .noData{
        position: absolute;
        top: 50%;
        left: 50%;
        width: 280px;
        height: 292px;
        margin-top: -146px;
        margin-left: -140px;
        // background-image: url('../assets/img/nodata.png');
        background-size: cover;

        >span{
          position: absolute;
          bottom: 40px;
          left: 20px;
          display: inline-block;
          width: 240px;
          height: 40px;
          text-align: center;
        }
      }
    }

  }
}

.migrationModelContent{
  height: 115px;
  padding: 30px 44px 17px 44px;
  box-sizing: border-box;
}
</style>
