<template>
  <div class="page-app-container">
    <el-row>
      <el-card class="box-card">
        <div slot="header" class="clearfix header-row">
          <span>{{ __('当前使用的模板') }}</span>
          <el-button
            type="primary"
            size="default"
            @click="createNewTemplate"
            class="create-btn"
          >
            {{ __('创建店铺模板') }}
          </el-button>
        </div>
        <div>
          <div style="width: 100%">
            <div class="usertemplate">
              <img
                :src="usePage.tpl_image"
                style="
                  left: 30px;
                  height: 296px;
                  width: 175px;
                  object-fit: fill;
                "
              />
            </div>
            <div class="usertemplateInfo">
              <span class="fontCls" style="margin-bottom: 35px; display: block">
                {{ __('模板名称') }}：{{ usePage.app_name }}
              </span>
              <el-button type="primary" @click="showEditApp(usePage)">
                {{ __('去装修') }}
              </el-button>
            </div>
          </div>
        </div>
      </el-card>
    </el-row>
    <el-row>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>{{ __('可选用的模板') }}</span>
        </div>
        <div>
          <ul class="ulCls" style="position: relative">
            <li v-for="(page, i) in list" :key="i" class="liCls">
              <div align="center" class="div_img_cls">
                <img
                  class="imgCls"
                  :src="page.tpl_image"
                  style="object-fit: fill"
                />
                <p class="fontCls">{{ page.app_name }}</p>
              </div>
              <div class="lightBtn">
                <div class="enableExit">
                  <div style="margin-bottom: 10px;">
                    <el-button
                      type="primary"
                      @click="setThemes(page.tpl_id, page.tpl_label, page.app_id)"
                    >
                      {{ __('启用') }}
                    </el-button>
                    <el-button type="primary" @click="showEditApp(page)">
                      {{ __('去装修') }}
                    </el-button>
                  </div>
                  <!-- 下拉菜单 -->
                  <el-dropdown size="large" @command="handleDropdownCommand(page, $event)">
                    <el-button type="primary">
                      {{ __('更多') }}<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="edit">
                        {{ __('编辑') }}
                      </el-dropdown-item>
                      <el-dropdown-item command="upload" v-if="page.is_pulish==0">
                        {{ __('发布') }}
                      </el-dropdown-item>
                      <el-dropdown-item command="pull" v-if="page.is_pulish==1">
                        {{ __('下架') }}
                      </el-dropdown-item>
                      <el-dropdown-item command="preview">
                        {{ __('预览') }}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              </div>
            </li>
          </ul>
        </div>
      </el-card>
    </el-row>
    <el-row>
      <el-card>
        <div slot="header" class="clearfix header-row">
          <span>{{ __('模板市场') }}</span>
          <!-- <el-button
            type="primary"
            size="default"
            @click="createNewTemplate"
            class="create-btn"
          >
            {{ __('查看更多模板') }}
          </el-button> -->
          <el-radio-group v-model="queryForm.appIndustry" @change="queryData">
            <el-radio-button v-for="item in shopModelOptions" :key="item.value" :label="item.value" >{{item.label}}</el-radio-button>
          </el-radio-group>
        </div>
        <div>
          <!-- <ul class="ulCls" style="position: relative">
            <li
              v-for="(page, i) in templateList.records"
              :key="i"
              class="liCls"
            >
              <div align="center" class="div_img_cls">
                <img
                  class="imgCls"
                  :src="page.tpl_image"
                  style="object-fit: fill"
                />
                <p class="fontCls">{{ page.app_name }}</p>
              </div>
              <div class="lightBtn">
                <div class="enableExit">
                  <el-button type="primary" @click="openCopy(page)">
                    {{ __('创建模板') }}
                  </el-button>
                  <el-button type="primary" @click="openPreview(page)">
                    {{ __('预览') }}
                  </el-button>
                </div>
              </div>
            </li>
          </ul> -->
          <ul class="ulCls">
            <li v-if="emptyPage" class="liCls">
              <div align="center" class="div_img_cls">
                <img
                  class="imgCls"
                  :src="emptyPage.tpl_image"
                  style="object-fit: fill"
                />
                <p class="fontCls">{{ emptyPage.tpl_name }}</p>
              </div>
              <div class="lightBtn">
                <div class="enableExit">
                  <el-button
                    type="primary"
                    @click="openCreateBlank"
                  >
                    {{ __('创建空白模板') }}
                  </el-button>
                </div>
              </div>
            </li>
            <template v-if="templateList.records.length > 0">
              <li v-for="(page, i) in templateList.records" :key="page.app_id || i" class="liCls">
                <div align="center" class="div_img_cls">
                  <img
                    class="imgCls"
                    :src="page.tpl_image"
                    style="object-fit: fill"
                  />
                  <p class="fontCls">{{ page.app_name }}</p>
                </div>
                <div class="lightBtn">
                  <div class="enableExit">
                    <el-button type="primary" @click="openCopy(page)">
                      {{ __('创建模板') }}
                    </el-button>
                    <el-button type="primary" @click="openPreview(page)">
                      {{ __('预览') }}
                    </el-button>
                  </div>
                </div>
              </li>
            </template>
            <li v-else class="empty-li">
              <el-empty 
                description="该分类暂无模板" 
              />
            </li>
          </ul>
        </div>
      </el-card>
      <el-pagination
            background
            :current-page="queryForm.pageNum"
            :layout="layout"
            :page-size="queryForm.pageSize"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
      />
    </el-row>
    <templateMenu ref="templateMenuRef"></templateMenu>
    <decoarationDetail ref="decoarationDetailRef" @editSuccess="refreshAllData"></decoarationDetail>
    <copyTemplate ref="copyTemplateRef" @copySuccess="refreshAllData"></copyTemplate>
    <createBlank ref="blankTemplateRef" @copySuccess="refreshAllData"></createBlank>
    <previewTemplate ref="previewTemplateRef"></previewTemplate>
  </div>
</template>

<script>
  import {
    getList,
    setThemes,
    listMarketPage,
    getBlankTpl,
    pageAppPublish
  } from '@/api/page/app'
  import { translateTitle as __ } from '@/utils/i18n'
  import templateMenu from '@/views/page/sellerApp/TemplateMenu.vue'
  import decoarationDetail from '@/views/page/sellerApp/DecorationDetail.vue'
  import copyTemplate from '@/views/page/sellerApp/copyTemplate.vue'
  import createBlank from '@/views/page/sellerApp/CreateBlankTemplate.vue'
  import previewTemplate from '@/views/page/sellerApp/previewTemplate.vue'
  export default {
    name: 'PageApp',
    components: { templateMenu, decoarationDetail,copyTemplate,previewTemplate,createBlank },
    data() {
      return {
        usePage: {},
        list: [],
        templateMenuRef: null,
        decoarationDetailRef: null,
        copyTemplateRef:null,
        blankTemplateRef:null,
        previewTemplateRef:null,
        templateList: { records: [] },
        emptyPage: null,
        app_market_images: null,
        queryForm:{
          pageNum:1,
          pageSize:10,
          appName:null,
          appIndustry:''
        },
        layout: 'total, sizes, prev, pager, next, jumper',
        total:0,
        shopModelOptions:[
          {
            value: '',
            label: this.__('全部'),
          },
          {
            value: '1',
            label: this.__('超市'),
          },
          {
            value: '2',
            label: this.__('数码家电'),
          },
          {
            value: '3',
            label: this.__('水果生鲜'),
          },
          {
            value: '4',
            label: this.__('烘焙甜品'),
          },
          {
            value: '5',
            label: this.__('社区团购'),
          },
          {
            value: '6',
            label: this.__('时尚美妆'),
          },
          {
            value: '7',
            label: this.__('婴儿服饰'),
          },
          {
            value: '8',
            label: this.__('家居'),
          },
          {
            value: '9',
            label: this.__('汽车'),
          },
          {
            value: '10',
            label: this.__('酒店旅游'),
          },
          {
            value: '11',
            label: this.__('鲜花绿植'),
          },
          {
            value: '12',
            label: this.__('医药健康'),
          },
          {
            value: '13',
            label: this.__('工业五金'),
          },
          {
            value: '14',
            label: this.__('节日模板'),
          },
          {
            value: '0',
            label: this.__('其他'),
          },
        ]
      }
    },
    created() {
      this.getAppPages()
      this.getListMarketPages()
      this.getBlankTplPage()
    },
    methods: {
      __,
      async getAppPages() {
        const { data, msg, status } = await getList()
        this.list = data.items
        this.usePage = data.current_tpl
      },
      showEditApp(page) {
        if (page.tpl_id === 107) {
          this.$router.push({
            path: '/appTemplate',
            query: {
              app_id: page.app_id,
              tpl_id: page.tpl_id,
              app_type: page.app_type,
            }, // 传递参数
          })
        } else {
          // 页面跳转
          this.$router.push({
            path: '/setupshop',
          })
        }
      },
      getUsePage(items) {
        for (let i = 0; i < items.length; i++) {
          if (items[i].app_is_use === 1) {
            this.usePage = items[i]
            break
          }
        }
      },
      async setThemes(tpl_id, tpl_label, app_id) {
        this.$baseConfirm(this.__('确定启用此模板风格？'), null, async () => {
          const { msg, status } = await setThemes({
            tpl_id: tpl_id,
            store_template: tpl_label,
            app_id: app_id,
          })
          if (200 == status) {
            this.$baseMessage(msg, 'success')
          } else {
            this.$baseMessage(msg, 'error')
          }
          this.getAppPages()
        })
      },
      createNewTemplate() {
        this.$refs.templateMenuRef?.open()
      },
      async getListMarketPages() {
        await this.fetchData();
      },
      async searchByType(){
        try {
          let data = await listMarketPage(this.queryForm);
          this.templateList = data && typeof data === 'object' ? data : { records: [] }
        } catch (error) {
          console.error('筛选模板失败：', error)
          this.templateList = { records: [] }
        }
      },
      async getBlankTplPage() {
        try {
          const { data, msg, status } = await getBlankTpl()
          if (status === 200) {
            this.emptyPage = data
          }
        } catch (error) {
          console.error('获取空白模板失败：', error)
        }
      },
      openDetailEdit(page) {
        this.$refs.decoarationDetailRef?.open(page)
      },
      openCopy(page) {
        this.$refs.copyTemplateRef?.open(page)
      },
      openCreateBlank(){ 
      this.$refs.blankTemplateRef?.open()
      },
      openPreview(page){
        this.$refs.previewTemplateRef?.open(page)
      },
      // 处理下拉菜单命令
      handleDropdownCommand(page, command) {
        switch(command) {
          case 'edit':
            this.openDetailEdit(page)
            break
          case 'upload':
            // 上传逻辑
            this.handleUpload(page,1)
            break
          case 'pull':
            this.handleUpload(page,0)
            break
          case 'preview':
            this.openPreview(page)
            break
        }
      },
      // 上传,下架处理方法
      async handleUpload(page,publishStatus) {
        const params={
          appId:page.app_id,
          isPublish:publishStatus
        }
        let res=await pageAppPublish(params)
        if(res.status==200){
          this.$message.success('操作成功！')
          this.refreshAllData()
        }
      },
      //操作后的刷新数据
      async refreshAllData() {
        await this.getAppPages() 
        await this.getListMarketPages() 
      },
      queryData(){
        this.queryForm.pageNum=1
        this.fetchData()
      },
      async fetchData(){
        const params = {
          ...this.queryForm,
          appIndustry: this.queryForm.appIndustry || '' 
        };
        const data = await listMarketPage(params);
        this.templateList = data && typeof data === 'object' ? data : { records: [] };  
        this.total = data.total
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.fetchData()
      },
    },
  }
</script>
<style>
  .clearfix {
    font-size: 18px;
  }

  /* 头部行样式 */
  .header-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .usertemplate {
    float: left;
    display: inline-block;
    margin-left: 30px;
    padding: 10px;
    background: #fff;
    width: 195px;
    height: 316px;
  }

  .usertemplateInfo {
    margin-left: 20px;
    float: left;
    display: inline-block;
    width: 195px;
    height: 316px;
  }

  .ulCls {
    list-style: none;
  }

  .ulCls li {
    position: relative;
    float: left;
    width: 195px;
    margin: 0 20px 30px;
    background-color: #fafafa;
  }

  .liCls {
    float: left;
    width: 195px;
  }

  div_img_cls {
    height: 328px;
    border: 1px solid #ccc;
  }

  .imgCls {
    width: 165px;
    height: 328px;
  }

  .fontCls {
    color: #979898;
    font-weight: bold;
  }

  .lightBtn {
    position: absolute;
    opacity: 0;
    top: 0;
    width: 100%;
    height: 328px;
  }

  .lightBtn:hover {
    opacity: 1;
    background-color: rgba(151, 152, 152, 0.5);
    -webkit-transition: all 0.5s;
    transition: all 0.5s;
  }

  .lightBtn:hover .enableExit {
    -webkit-transition: all 0.5s;
    transition: all 0.5s;
    -webkit-transform: translateY(150%);
    transform: translateY(150%);
  }

  .enableExit {
    position: relative;
    top: 30%;
    width: 100%;
    margin-top: -15px;
    text-align: center;
  }

  /* 下拉菜单样式调整 */
  .el-dropdown {
    display: inline-block;
  }
</style>