<template>
  <div class="app-container">
    <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
      <el-tab-pane label="商品列表" name="first" />
      <el-tab-pane label="宣传图" name="second" />
      <template v-if="activeName === 'first'">
        <div class="filter-container">
          <div class="filter-control">
            <span>商品ID:</span>
            <el-input
              v-model="listQuery.productId"
              placeholder="商品ID"
              clearable
              @input="e => (listQuery.productId= checkedInput(e,1))"
              @keyup.enter.native="getList"
              @clear="getList"
            />
          </div>
          <div class="filter-control">
            <span>商品名称:</span>
            <el-input
              v-model="listQuery.productName"
              placeholder="商品名称"
              clearable
              @input="e => (listQuery.productName= checkedInput(e,2))"
              @keyup.enter.native="getList"
              @clear="getList"
            />
          </div>
          <div class="filter-control">
            <span>供应商:</span>
            <el-input
              v-model="listQuery.shopName"
              placeholder="供应商"
              clearable
              @keyup.enter.native="getList"
              @clear="getList"
            />
          </div>
          <div class="filter-control">
            <span>优惠状态:</span>
            <el-select v-model="listQuery.status" style="width:120px;" clearable @change="getList">
              <el-option value="" label="请选择" />
              <el-option :value="0" label="已上架" />
              <el-option :value="1" label="已下架" />
            </el-select>
          </div>
          <div class="filter-control">
            <el-button type="primary" @click="getList">查询</el-button>
            <el-button type="primary" @click="proDialogVisible =true">添加</el-button>
          </div>
        </div>
        <el-table v-loading="isLoading" :data="tableData" border style="width: 100%">
          <el-table-column prop="productId" label="商品ID" align="center" />
          <el-table-column prop="coupon" label="商品图片" align="center">
            <template v-if="row.productId" slot-scope="{ row }">
              <el-popover
                placement="top-start"
                title=""
                width="180"
                trigger="hover"
              >
                <img :src="row.productImage" alt="" style="width:100px;height:100px;">
                <img slot="reference" :src="row.productImage" alt="" style="width:50px;height:50px;">
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="商品名称" align="center" />
          <el-table-column prop="shopName" label="供应商" align="center" width="250" />
          <el-table-column prop="price" label="机构价" align="center" />
          <el-table-column prop="discount" label="会员折扣" align="center">
            <template slot-scope="{ row }">
              {{ row.priceType === 1 ? row.discount+'%' : '---' }}
            </template>
          </el-table-column>
          <el-table-column prop="discountPrice" label="会员价" align="center">
            <template slot-scope="{ row }">
              ￥{{ row.priceType === 2 ? row.discountPrice : row.price * row.discount * 0.01 }}
            </template>
          </el-table-column>
          <el-table-column label="排序" width="80" align="center">
            <template slot-scope="{row}">
              <el-input v-model="row.sort" maxlength="4" minlength="1" @blur="handleOnInputBlur(row)" />
            </template>
          </el-table-column>
          <el-table-column prop="status" label="优惠状态" align="center" width="100">
            <template slot-scope="{ row }">
              <span v-if="row.status === 0" class="el-span-zero">
                已上架
              </span>
              <span v-else class="el-span-one">
                已下架
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="addTime" label="添加时间" align="center" width="100" />
          <el-table-column label="操作" align="center" width="180">
            <template slot-scope="{ row }">
              <el-button type="primary" size="mini" @click="handleEdit(row.id)">编辑</el-button>
              <el-button type="danger" size="mini" @click="handeleDelPro(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 页码 -->
        <pagination
          :total="total"
          :page-sizes="[20]"
          :page-size="20"
          :page.sync="listQuery.pageNum"
          :limit.sync="listQuery.pageSize"
        />
        <!--  选择商品弹窗 -->
        <pro-dialog v-if="proDialogVisible" ref="proDialog" @confirm="handleAddProductConfirm" @cancel="handleCancel" />
        <!-- 商品编辑弹窗 -->
        <pro-edit v-if="proEditVisible" ref="proEdit" :pro-id="handleProId" @confirm="handleEditConfirm" @cancel="handleEditCancel" />
      </template>
      <template v-else>
        <div class="club-container" style="width: 100%;height: 650px;padding-top: 40px;">
          <el-form ref="submitForm" class="doctor-edit-form" label-width="140px" :model="formData" :rules="rules">
            <el-form-item label="PC端:" prop="doctorImage">
              <div class="form-label-tip">宣传图</div>
              <el-input v-show="false" v-model="formData.pcImage" />
              <upload-image
                tip="提示：建议图片分辨率1920px*510px"
                :image-list="pcImageList"
                :before-upload="beforeDoctorImageUpload"
                @success="uploadDoctorImageSuccess"
                @remove="handleDoctorImageRemove"
              />
            </el-form-item>
            <el-form-item label="小程序端:" prop="banner">
              <div class="form-label-tip">宣传图</div>
              <el-input v-show="false" v-model="formData.appletsImage" />
              <upload-image
                tip="提示：建议图片分辨率351px*170px"
                :image-list="appletsImageList"
                :before-upload="beforeBannerUpload"
                @success="uploadBannerSuccess"
                @remove="handleBannerRemove"
              />
            </el-form-item>
          </el-form>
          <div class="submit-btn" style="padding-left: 137px;">
            <el-button type="primary" :disabled="disabled" @click="submitSave">保存</el-button>
          </div>
        </div>
      </template>
    </el-tabs>
  </div>
</template>
<script>
import { fetchFindProductList, updateSort, saveAdsImage, getAdsImage } from '@/api/member/member'
import { delSvipProduct, saveSvipProduct } from '@/api/member/member'
import UploadImage from '@/components/UploadImage'
import ProDialog from './components/pro-dialog'
import ProEdit from './components/pro-edit'
export default {
  name: 'MemberProduct',
  components: { UploadImage, ProDialog, ProEdit },
  data() {
    return {
      activeName: 'first',
      listQuery: {
        productId: null,
        productName: '',
        shopName: '',
        status: '',
        pageNum: 0,
        pageSize: 20
      },
      formData: {
        pcImage: '',
        appletsImage: ''
      },
      // PC端宣传图
      pcImageList: [],
      // 小程序端宣传图
      appletsImageList: [],
      rules: {
        pcImage: [{ required: true, message: '请上传PC端宣传图', trigger: 'change' }],
        appletsImage: [{ required: true, message: '请上传小程序端宣传图', trigger: 'change' }]
      },
      // 超级会员商品列表
      total: 0,
      isLoading: true,
      tableData: [],
      proDialogVisible: false,
      proEditVisible: false,
      handleProId: null
    }
  },
  computed: {
    disabled() {
      return !(this.formData.pcImage !== '' > 0 && this.formData.appletsImage !== '')
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      this.isLoading = true
      const res = await fetchFindProductList(this.listQuery)
      this.tableData = res.data.results
      this.total = res.data.totalRecord
      this.isLoading = false
    },
    handleOnInputBlur(row) {
      // 更新排序
      updateSort({ id: row.id, sort: row.sort }).then(response => {
        this.$message({
          message: '操作成功',
          type: 'success',
          duration: 1000
        })
        this.getList()
      })
    },
    // tab切换
    handleClick(tab, event) {
      if (tab.name === 'second') {
        this.getAdsImageData()
      }
    },
    async getAdsImageData() {
      try {
        this.pcImageList = []
        this.appletsImageList = []
        const res = await getAdsImage(this.formData)
        console.log('res', res.data)
        this.formData.pcImage = res.data.pcImage
        this.formData.appletsImage = res.data.appletsImage
        this.pcImageList.push({ url: res.data.pcImage, name: 'doctor' })
        this.appletsImageList.push({ url: res.data.appletsImage, name: 'doctor' })
        console.log('pcImageList', this.pcImageList)
        console.log('appletsImageList', this.appletsImageList)
      } catch (error) {
        console.log(error)
      }
    },
    async submitSave() {
      // 保存
      try {
        console.log('formData', this.formData)
        await saveAdsImage(this.formData)
        this.$message.success('保存成功')
        setTimeout(() => {
          this.getAdsImageData()
        }, 2000)
      } catch (error) {
        console.log(error)
      }
    },
    // PC端宣传图上传
    uploadDoctorImageSuccess({ response, file, fileList }) {
      this.pcImageList = fileList
      this.formData.pcImage = response.data
    },
    handleDoctorImageRemove({ file, fileList }) {
      this.pcImageList = fileList
      this.formData.pcImage = ''
    },
    beforeDoctorImageUpload(file) {
      const flag = file.size / 1024 / 1024 < 2
      if (!flag) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return flag
    },
    // 小程序端宣传图上传
    uploadBannerSuccess({ response, file, fileList }) {
      this.appletsImageList = fileList
      this.formData.appletsImage = fileList.length || ''
    },
    handleBannerRemove({ file, fileList }) {
      this.appletsImageList = fileList
      this.formData.appletsImage = fileList.length || ''
    },
    beforeBannerUpload(file) {
      const flag = file.size / 1024 / 1024 < 2
      if (!flag) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return flag
    },
    async handeleDelPro(id) {
      await this.$confirm('确认要删除该商品吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      this.delSvipProductSubmit(id)
    },
    async delSvipProductSubmit(id) {
      try {
        await delSvipProduct(id)
        this.$message.success('操作成功')
        this.getList()
      } catch (error) {
        console.log(error)
      }
    },
    async handleAddProductConfirm(productId) {
      // 确认添加商品
      try {
        await saveSvipProduct({ productId: productId })
        this.$message.success('添加成功')
        this.handleCancel()
        this.getList()
      } catch (error) {
        console.log(error)
      }
    },
    handleCancel() {
      // 取消选择添加商品
      this.proDialogVisible = false
      this.$refs.proDialog.visible = false
    },
    handleEdit(id) {
      // 编辑商品
      this.handleProId = id
      this.proEditVisible = true
    },
    handleEditCancel() {
      // 取消编辑商品
      this.proEditVisible = false
      this.$refs.proEdit.visible = false
    },
    async handleEditConfirm(data) {
      // 保存编辑商品
      console.log('data', data)
      try {
        await saveSvipProduct(data)
        this.$message.success('操作成功')
        this.handleEditCancel()
        this.getList()
      } catch (error) {
        console.log(error)
      }
    },
    checkedInput(event, type) {
      let pattern = ''
      switch (type) {
        case 1:
          pattern = /[^\d]/g
          break
        case 2:
          pattern = /[^u4E00-u9FA5|d|a-zA-Z|rns,.?!，。？！…—&$=()-+/*{}[]]|s/g
          break
      }
      return event.replace(pattern, '')
    }
  }
}
</script>

<style>
.el-span-zero {
  color: #0bd81c;
}
.el-span-one {
  color: #ff353f;
}
</style>
