<template>
  <a-row>
    <a-col class="theme-wrap">
      <a-col class="tag-wrap">
        <a-button type="link" v-for="(item,index) in templateTag" :key="item.tagValue"
                  @click="showTemplate(item.tagValue,index)" :class="{act:index==ins}">
          {{ item.tagName }}({{ item.templateCount }})
        </a-button>
      </a-col>
      <a-list
        :grid="{ gutter: 16, column: 4 }"
        :data-source="dataSource"
        :loading="loading"
        class="j-table-force-nowrap template_list" :style="{height:'100%'}">
        <a-list-item slot="renderItem" slot-scope="item, index">
          <a-card :title="item.name +'-'+item.templateTags_dictText" class="text-center">
            <div class="item" @mouseover="hoverThis()">
              <div class="Pic">
                <a class="img">
                  <img v-if="checkUrl(item.images)" v-lazy="domainUrl+'/sys/common/static/'+item.images"
                       :key="item.code" :alt="item.name" />
                  <img v-else v-lazy=item.images />
                </a>
                <template v-if="item.putaway == 1 && item.externalTemplate != 1 && item.developmentStatus != 1">
                  <div class="Content">
                    <a-button class="fl" block @click="visit(item)">模板预览</a-button>
                    <a-button v-has="'show:createSite'" type="primary" block class="fr" @click="createSite(item)">创建站点</a-button>
                  </div>
                </template>
                <template v-else-if="item.putaway == 1 && item.developmentStatus  == 1 && item.siteType == 3 && (item.externalTemplateUrl == null || item.externalTemplateUrl == '')">
                  <div class="Content">
                    <a-button type="primary" block @click="visitImage(item)">模板预览</a-button>
                  </div>
                </template>
                <template v-else-if="item.putaway == 1 && item.developmentStatus  == 1 && item.siteType == 3 && item.externalTemplateUrl != null && item.externalTemplateUrl != ''">
                  <div class="Content">
                    <a-button type="primary" block @click="visitOut(item)">模板预览</a-button>
                  </div>
                </template>
                <template v-else-if="item.putaway == 1 && item.externalTemplate == 1 && item.externalTemplateUrl != null">
                  <div class="Content">
                    <a-button type="primary" block @click="visitOut(item)">模板预览</a-button>
                  </div>
                </template>
                <template v-else-if="item.putaway == 1 && item.externalTemplate == 1 && (item.externalTemplateUrl == null || item.externalTemplateUrl == '')">
                  <div class="Content">
                    <a-button type="dashed" block>bb敬请期待</a-button>
                  </div>
                </template>
                <template v-else-if="item.putaway == 1 && item.developmentStatus  == 1 && item.siteType == 3">
                  <div class="Content">
                    <a-button type="dashed" block>{{item.externalTemplateUrl}}敬请期待 {{item.siteType}}</a-button>
                  </div>
                </template>
              </div>
              <div class="clear"></div>
            </div>
          </a-card>
        </a-list-item>
      </a-list>
      <a-modal
        v-model="modalVisible"
        :title="modalTitle"
        centered
        :confirm-loading="confirmLoading"
        @ok="handleOk"
        @cancel="handleCancel"
        :closable="false"
        :keyboard="false"
        :maskClosable="false"
        width="50%"
        :ok-button-props="okBtnStatus"
        :cancel-button-props="cancelBtnStatus"
        :okText="okText"
        :cancelText="cancelText"
      >
        <template v-if="showCreateSite">
          <a-spin :spinning="spinning" :tip="tipTitle">
            <a-form-model
              ref="createSiteForms"
              :model="createSiteForm"
              :rules="createSiteFormRules"
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
            >
              <a-form-model-item>
                我们将为您新建站点，稍后请移至“站群管理”对网站内容进行编辑<br />
                在建站完成后，需要您将域名解析到指定的CNAME将网站发布上线<br />
                您可在“站群管理”中查看建站进度和CNAME
              </a-form-model-item>
              <a-form-model-item ref="name" label="用户名称" prop="uid">
                <a-select v-model="createSiteForm.uid"
                          show-search
                          :filter-option="filterOption"
                          placeholder="请选择用户名称">
                  <a-select-option v-for="user in userList"
                                   :key="user.id"
                                   :value="user.id">
                    {{ user.realname }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item ref="name" label="站点名称" prop="name">
                <a-input v-model="createSiteForm.name" placeholder="请输入站点名称" />
              </a-form-model-item>
              <a-form-model-item ref="languageCode" label="站点语言" prop="languageCode">
                <j-search-select-tag placeholder="请选择站点语言" v-model="createSiteForm.languageCode"
                                     dict="adweb_language" />
              </a-form-model-item>
              <a-form-model-item ref="planId" label="营销方案" prop="planId">
                <a-row :gutter="8">
                  <a-col :span="21">
                    <j-search-select-tag
                      placeholder="请选择营销方案"
                      v-model="createSiteForm.planId"
                      dict="seo_market_plan,plan_name,id,status=1"
                    />
                  </a-col>
                  <a-col :span="3">
                    <router-link :to="{ path: '/deliver/serp/seoMarketPlan/list',query:{from:'themeList'}}">
                      <a-button type="primary" block>新增</a-button>
                    </router-link>
                  </a-col>
                </a-row>
              </a-form-model-item>

              <a-form-model-item label="赠送天数"  prop="giveDay" v-show="createSiteForm.planId!==undefined">
                <a-input-number :min="0" :max="1000" style="width: 100%;" placeholder="赠送天数" v-model="createSiteForm.giveDay" />
              </a-form-model-item>
              <a-form-model-item label="补偿天数"  prop="compensateDay" v-show="createSiteForm.planId!==undefined">
                <a-input-number :min="0" :max="1000" style="width: 100%;" placeholder="补偿天数" v-model="createSiteForm.compensateDay" />
              </a-form-model-item>
            </a-form-model>
          </a-spin>
        </template>

        <template v-if="showResult">
          <a-result
            status="success"
            title="站点创建完成!"
          >
          </a-result>
        </template>
      </a-modal>
      <a-modal
        :visible="visible"
        width="80%"
        @cancel="visitImageCancel"
        :footer="null"
        class="self_buy_modal"
      >
        <div slot="title">
            <div>
              <p class="ant-modal-title">
                模板预览
                <template v-if="(userRole.indexOf('admin')>-1 || userRole.indexOf('adweb_admin')>-1  || userRole.indexOf('adweb_seo_manager')>-1 || userRole.indexOf('adweb_site_manager')>-1) && modelText != null && modelText != ''">
                  <a :href="modelText" target="_blank" style="font-size: 14px;text-decoration: underline"><span>购买链接</span></a>
                </template>
              </p>

            </div>
        </div>

        <img alt="example" style="width: 100%" :src="theImage" />
      </a-modal>
    </a-col>
  </a-row>
</template>

<script>

import '/@/assets/less/TableExpand.less'
import '/@/assets/less/common.less'

import Qs from 'qs'
import { getAction, postAction} from '/@/api/manage/manage'
import $ from 'jquery'
import { useUserStore } from '/@/store/modules/user'

export default {
  name: 'AdwebThemeCList',
  components: {},
  data() {
    return {
      description: 'adweb_theme管理页面',
      // 表头
      columns: [
        {
          title: '站点名称',
          align: 'left',
          dataIndex: 'name'
        },
        {
          title: '图片路径',
          align: 'left',
          dataIndex: 'images',
          scopedSlots: { customRender: 'imgSlot' }
        }
      ],
      url: {
        list: '/adweb/adwebTheme/list',
        delete: '/adweb/adwebTheme/delete',
        deleteBatch: '/adweb/adwebTheme/deleteBatch',
        createSiteUrl: 'siteManage/createSite',
        addSiteLanguageUrl: 'siteManage/addSiteLanguage',
        getTemplateTagsUrl: '/adweb/adwebTheme/getTemplateTags',
        wpSiteCreateUrl: 'wpWebSite/addWebsite',
        getAdwebVipUrl: 'adweb/adwebSiteManage/getAdwebVip'
      },
      dictOptions: {},
      superFieldList: [],
      domainUrl: window._CONFIG['domianURL'],
      modalVisible: false,
      modalTitle: '',
      userRole: '',
      confirmLoading: false,
      showCreateSite: false,
      createSiteForm: {
        uid: undefined,
        source: '',
        name: '',
        languageCode: 'en',
        parentCode: '',
        planId: undefined,
        giveDay: 0,
        compensateDay: 0,
      },
      createSiteFormRules: {
        uid: [
          { required: true, message: '请选择用户名称', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入站点名称', trigger: 'blur' }
        ],
        languageCode: [{ required: true, message: '站点语言不能为空', trigger: 'change' }],
        planId: [
          { required: true, message: '请选择营销方案', trigger: 'blur' }
        ],
      },
      showResult: false,
      spinning: false,
      tipTitle: '',
      labelCol: { span: 3 },
      wrapperCol: { span: 21 },
      modalStatus: false,
      okBtnStatus: {},
      okText: '',
      cancelText: '',
      modelText: '',
      theImage: '',
      showResultForm: {},
      cancelBtnStatus: {},
      templateTag: [],
      ins: 0,
      dataSource: [],
      loading: false,
      isHeight: $(window).height() - 59 - 52 - 12 - 62 - 12 - 93,
      siteCreating: false,
      isWpSiteCreate: false,
      wpTemplateData: {
        name: '',
        tempId: '',
        domain: '',
        uid:'',
      },
      userList: [],
      visible:false
    }
  },
  created() {
    this.userRole = useUserStore().roleList
    this.getTemplateTags()
    this.getTemplateList(-1)
  },
  methods: {
    getTemplateTags() {
      let that = this
      let getTemplateTagsUrl = `${that.url.getTemplateTagsUrl}`
      getAction(getTemplateTagsUrl).then(function(res) {
        if (res.code == 200) {
          that.templateTag = res.result
        } else {
          that.$message.error('模板分类获取失败！')
        }
      })
    },
    checkUrl: function(val) {
      if (val != null) {
        if (val.substr(0, 7).toLowerCase() == 'http://' || val.substr(0, 8).toLowerCase() == 'https://') {
          return false
        } else {
          return true
        }
      } else {
        return false
      }
    },
    hoverThis() {
      $('.item').hover(
        function() {
          if ($(this).height() >= $(this).find('.Pic img').height()) {
            return
          } else {
            $(this).find('.Pic img').stop().animate({ top: $(this).height() - $(this).find('.Pic img').height() }, 5000)
          }
        },
        function() {
          $(this).find('.Pic img').stop().animate({ top: 0 }, 'fast')
        }
      )
    },
    //预览
    visit(data) {
      let that = this
      if (data.siteType === 1) {
        if(data.domainDev != null && data.domainDev != ''){
          return window.open(that.domainUrl + data.domainDev, '_blank')
        }else{
          that.visitImage(data)
        }
      }
      if (data.siteType === 3) {
        if(data.externalTemplateUrl != null && data.externalTemplateUrl != ''){
          return window.open(data.externalTemplateUrl, '_blank')
        }else{
          that.visitImage(data)
        }
      }
    },

    visitImage(data) {
      this.visible = true
      this.modelText = data.buyLinks;
      this.theImage = this.domainUrl+'/sys/common/static/' + data.images;
    },

    visitImageCancel() {
      this.visible = false
      this.modelText = '';
      this.theImage = ''
    },

    visitOut(data) {
      if(data.externalTemplateUrl != null && data.externalTemplateUrl != ''){
        return window.open(data.externalTemplateUrl, '_blank')
      }else{
        this.visitImage(data)
      }
    },

    cleanAllFormData() {
      let that = this
      that.confirmLoading = false
      that.templateInfo = {}
      that.spinning = false
      that.tipTitle = ''
      that.modalVisible = false
      that.modalTitle = ''
      that.modalCopyTemplateStatus = false
      that.copyTemplateForm = {
        name: ''
      }
      that.showCreateSite = false
      that.createSiteForm = {
        uid: undefined,
        languageCode: 'en',
        source: '',
        name: '',
        parentCode: '',
        planId: undefined,
        giveDay: 0,
        compensateDay: 0,
      }
      that.showResult = false
      that.okBtnStatus = {}
      that.cancelBtnStatus = {}
      that.ins = 0
      that.loading = false
    },

    //创建站点
    createSite(item) {
      let that = this
      that.getUserList()
      if (item.siteType === 3) {
        that.isWpSiteCreate = true
        that.wpTemplateData.tempId = item.id
      } else {
        that.createSiteForm.source = item.source
        that.createSiteForm.parentCode = item.code
        that.createSiteForm.id = item.id
        that.createSiteForm.languageCode = 'en'
      }
      that.modalVisible = true
      that.modalTitle = '创建站点'
      that.showCreateSite = true
      that.okText = '确定'
      that.cancelText = '取消'
    },

    createSiteData() {
      let that = this
      that.confirmLoading = false
      that.spinning = true
      that.tipTitle = '正在创建站点'
      let createSiteUrl = `${that.url.createSiteUrl}`
      that.okBtnStatus = { props: { disabled: true } }
      that.cancelBtnStatus = { props: { disabled: true } }
      postAction(createSiteUrl, Qs.stringify(that.createSiteForm), 1000 * 60 * 5).then(function(res) {
          that.spinning = false
          that.tipTitle = ''
          if (res.code == 200) {
            that.showCreateSite = false
            that.showResult = true
            that.modalTitle = '系统提示'
            that.okText = '预览站点'
            that.cancelText = '关闭'
            that.showCreateSite = false
            that.okBtnStatus = {}
            that.cancelBtnStatus = {}
            that.newCreateSiteInfo = res.data
          } else {
            that.cancelBtnStatus = {}
            that.$message.error('网站创建失败，请重试！')
          }
        }
      ).catch(function() {
        that.modalVisible = true
        that.$message.error('网络超时，请重试!')
      })
    },

    handleOk() {
      let that = this
      if (that.showCreateSite && !that.isWpSiteCreate) {
        that.$refs.createSiteForms.validate(valid => {
          if (valid) {
            that.createSiteData()
          } else {
            return false
          }
        })
      }
      if (that.showCreateSite && that.isWpSiteCreate) {
        that.$refs.createSiteForms.validate(valid => {
          if (valid) {
            that.wpSiteCreate(that.createSiteForm.name)
          } else {
            return false
          }
        })
      }
      if (that.showResult && !that.isWpSiteCreate) {
        that.toMySite()
      }
      if (that.showResult && that.isWpSiteCreate) {
        that.toMyWPSite()
      }
    },

    handleCancel() {
      let that = this
      that.cleanAllFormData()
    },

    toMySite() {
      let that = this
      return window.open(that.domainUrl + that.newCreateSiteInfo, '_blank')
    },

    //wp站点创建成功预览
    toMyWPSite() {
      let that = this
      return window.open('http://' + that.newCreateSiteInfo, '_blank')
    },
    showTemplate(tagId, i) {
      let that = this
      that.loading = true
      if (i == undefined) {
        that.ins = 0
      } else {
        that.ins = i
      }
      that.getTemplateList(tagId)
    },

    getTemplateList(tagId) {
      let that = this
      that.loading = true
      let listUrl = `${that.url.list}` + '?templateTags=' + tagId
      getAction(listUrl).then(function(res) {
        if (res.code == 200) {
          that.loading = false
          that.dataSource = res.result.records
        } else {
          that.loading = false
          that.$message.error('模板获取失败！')
        }
      })
    },

    //wp站点创建
    wpSiteCreate(siteName) {
      let that = this
      if(that.siteCreating){
        that.$message.warning('站点创建中，请勿重复点击！')
        return;
      }
      that.siteCreating = true
      that.confirmLoading = false
      that.spinning = true
      that.tipTitle = '正在创建站点'
      that.okBtnStatus = { props: { disabled: true } }
      that.cancelBtnStatus = { props: { disabled: true } }
      that.wpTemplateData.name = siteName
      that.wpTemplateData.uid = that.createSiteForm.uid
      that.wpTemplateData.planId = that.createSiteForm.planId
      that.wpTemplateData.giveDay = that.createSiteForm.giveDay
      that.wpTemplateData.compensateDay = that.createSiteForm.compensateDay
      postAction(that.url.wpSiteCreateUrl, Qs.stringify(that.wpTemplateData),1000 * 60 * 5).then(function(res) {
          if (res.code === 200 && res.result === 'ignore') {
            that.$message.error('您距离上个站点创建不足两分钟，请两分钟后再次尝试！')
            return;
          }
          if (res.code === 200) {
            that.showCreateSite = false
            that.showResult = true
            that.modalTitle = '系统提示'
            that.okText = '预览站点'
            that.cancelText = '关闭'
            that.showCreateSite = false
            that.okBtnStatus = {}
            that.cancelBtnStatus = {}
            that.newCreateSiteInfo = res.result
            that.wpSitePreviewUrl = ''
          } else {
            that.cancelBtnStatus = {}
            that.$message.error('网站创建失败，请重试！')
          }
        }
      ).catch(function() {
        that.modalVisible = true
        that.$message.error('网络超时，请重试!')
      }).finally(()=>{
        that.siteCreating = false
        that.spinning = false
        that.tipTitle = ''
      })

    },

    getUserList() {
      let that = this
      getAction(this.url.getAdwebVipUrl).then(function(res) {
        if (res.code == 200) {
          that.userList = res.result
        }
      })
    },

    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    }
  }
}
</script>
<style scoped lang="less">

.mt-20 {
  margin-top: 20px
}

.fl {
  float: left;
}

.fr {
  float: right;
}

.template-image {
  width: 100%;
  height: 300px;
}

.text-center {
  text-align: center;
}

.template_list /deep/ .ant-card-body {
  padding: 0;
}

.template_list .item {
  width: 100%;
  display: block;
  height: 467px;
  position: relative;
  transition: all 0.4s ease-out;
}

.template_list .item .Pic {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.template_list .item .Pic img {
  width: 100%;
  max-height: unset;
  position: absolute;
  top: 0;
  left: 0;
}

.template_list .item .Pic .Content {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  opacity: 0;
  position: absolute;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.4);
  top: 0;
  left: 0;
  font-size: 0;
  transition: all 0.4s ease-out;
  padding-bottom: 20px;
}

.template_list .item .Pic .Content button {
  margin: 0 10px;
}

.template_list .item:hover {
  box-shadow: 3px 3px 12px 2px #aaaaaad4;
}

.template_list .item:hover .Pic .Content {
  opacity: 1;
}

.tag-wrap .ant-btn.ant-btn-link.act{
  color:  @primary-color!important;
  background-color: #fff!important;
  font-weight: 600;
  border-bottom: 1px solid #fff;
}

.tag-wrap {
  margin-bottom: 12px;
}

.tag-wrap .ant-btn-link {
  color: #fff!important;
  width: 10%;
  margin: 5px 0.5%;
}

.template_list {
  overflow-y: scroll;
  overflow-x: hidden;
}

.ant-btn-link {
  margin-right: 10px;
}

img[lazy="error"], img[lazy="loading"] {
  top: calc(50% - 140px) !important;
  position: relative !important;
  margin: 0 auto;
  width: 240px !important;
}

.self_buy_modal{
  /deep/ .ant-modal-body{
    padding: 0;
  }
}
</style>
