<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-control">
        <span>所属供应商：</span>
        <el-select
          v-model="listQuery.authUserId"
          placeholder="请选择供应商"
          clearable
          style="width: 200px"
          class="filter-item"
          @change="getList"
        >
          <template v-for="item in supplierList">
            <el-option :key="item.authUserId" :label="item.name" :value="item.authUserId" />
          </template>
        </el-select>
      </div>
      <div class="filter-control">
        <el-button type="primary" @click="getList">查询</el-button>
        <el-button type="primary" @click="addCardVisible = true">添加</el-button>
      </div>
    </div>
    <el-table v-loading="listLoading" style="width: 100%" header-row-class-name="tableHeader" :data="list" border fit>
      <el-table-column :index="indexMethod" label="序号" type="index" width="80" align="center" />
      <el-table-column label="授权牌模板" align="center" width="200px">
        <template slot-scope="{ row }">
          <el-tooltip effect="dark" content="点击查看全图" placement="top-start">
            <el-image :src="row.templateImage" :preview-src-list="[row.templateImage]" fit="cover" />
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="shopName" label="所属供应商" align="center" />
      <el-table-column label="操作" align="center" width="320px">
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="onChangeSupplier(row)">更换供应商</el-button>
          <el-button type="primary" size="mini" @click="onTempEdit(row)">编辑</el-button>
          <!-- 隐藏其一 -->
          <el-button v-if="row.status === 0" type="info" size="mini" @click="onTempStatusChange(row)">启用</el-button>
          <el-button v-else type="danger" size="mini" @click="onTempStatusChange(row)">停用</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 供应商列表 -->
    <el-dialog title="选择供应商" :visible.sync="selectSupplierVisible" width="66%" @close="onSelectSupplierClose">
      <supplier-list @cancel="selectSupplierVisible = false" @confirm="onSupplierConfirm('edit', $event)" />
    </el-dialog>
    <!-- 上传图片 -->
    <el-dialog title="添加授权牌模板" :visible.sync="addCardVisible" width="40%" @closed="onAddCardClose">
      <el-dialog width="66%" title="选择供应商" :visible.sync="addCardInnerVisible" append-to-body>
        <supplier-list @cancel="addCardInnerVisible = false" @confirm="onSupplierConfirm('add', $event)" />
      </el-dialog>
      <el-form ref="addCardForm" :model="formData" label-width="120px" :rules="rules">
        <el-form-item label="授权牌模板：" prop="templateImage">
          <el-input v-show="false" v-model="formData.templateImage" />
          <upload-image
            :limit="1"
            tip="建议尺寸：542px * 546px"
            :image-list="tempList"
            @success="uploadTempImageSuccess"
            @remove="handleLogoImageRemove"
          />
        </el-form-item>
        <el-form-item label="二维码位置：" prop="qrPosition">
          <el-input
            v-model="formData.qrPosition"
            placeholder="请输入二维码位置坐标，以英文逗号隔开，分别为二维码左上角X,Y轴坐标（例如：100,100）"
          />
        </el-form-item>
        <el-form-item label="二维码大小：" prop="qrSize">
          <el-input v-model.number="formData.qrSize" placeholder="请输入二维码大小（例如：53）" />
        </el-form-item>
        <el-form-item label="LOGO大小：" prop="logoSize">
          <el-input v-model="formData.logoSize" placeholder="请输入授权牌logo建议尺寸宽高（例如：212,98）" />
        </el-form-item>
        <el-form-item label="所属供应商：" prop="authUserId">
          <el-input v-show="false" v-model="formData.authUserId" />
          <div class="current-info">
            <span v-if="selectSupplier" class="supplier-name">{{ selectSupplier.name }}</span>
            <span class="supplier-change" @click="addCardInnerVisible = true">
              {{ selectSupplier ? '更换供应商' : '选择供应商' }}
            </span>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addCardVisible = false">取 消</el-button>
        <el-button type="primary" :loading="isLoading" @click="onConfirm">确定</el-button>
      </div>
    </el-dialog>
    <!-- 页码 -->
    <pagination
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList(listQuery)"
    />
  </div>
</template>
<script>
import UploadImage from '@/components/UploadImage'
import SupplierList from './components/supplier-list.vue'
import { authTempSave, fetchAuthTempList } from '@/api/system'
import { fetchSupplierList } from '@/api/supplier'
import { objectCover } from '@/utils'
export default {
  components: {
    UploadImage,
    SupplierList
  },
  data() {
    const validateQrPosition = (rule, value, callback) => {
      if (!value) return callback()
      if (value.split(',').length === 2) {
        return callback()
      }
      callback(new Error('二维码坐标格式不正确，请改为（X坐标,Y坐标） => (100,100)'))
    }

    const validateLogoSize = (rule, value, callback) => {
      if (!value) return callback()
      if (value.split(',').length === 2) {
        return callback()
      }
      callback(new Error('logo建议尺寸格式不正确，请改为（宽,高）格式'))
    }

    return {
      listLoading: false,
      isLoading: false,
      listQuery: {
        listType: 1,
        authUserId: '',
        pageSize: 15,
        pageNum: 1
      },
      list: [],
      total: 0,
      supplierList: [],
      formData: {
        templateImage: '',
        authUserId: '',
        qrPosition: '',
        qrSize: '',
        logoSize: ''
      },
      addCardVisible: false,
      addCardInnerVisible: false,
      selectSupplierVisible: false,
      selectSupplier: null,
      // 授权牌模板列表
      tempList: [],
      // 需要更换供应商的授权牌
      currentCard: null,
      rules: {
        templateImage: [{ required: true, message: '请上传授权牌模板', trigger: ['change'] }],
        authUserId: [{ required: true, message: '请选择供应商', trigger: ['change'] }],
        qrPosition: [{ validator: validateQrPosition, trigger: ['blur'] }],
        qrSize: [{ required: true, message: '请填写二维码大小', trigger: ['blur'] }],
        logoSize: [
          { required: true, message: '请输入授权牌logo建议尺寸宽高', trigger: ['blur'] },
          { validator: validateLogoSize, trigger: ['blur'] }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.fetchSupplierList()
  },
  methods: {
    // 获取授权牌模板列表
    getList() {
      this.list = []
      this.listQuery.pageNum = 1
      this.fetchAuthTempList(this.listQuery)
    },

    // 获取授权牌模板列表
    async fetchAuthTempList() {
      this.listLoading = true
      try {
        const res = await fetchAuthTempList(this.listQuery)
        this.list = res.data.list
        this.total = res.data.total
        this.listLoading = false
      } catch (error) {
        console.log(error)
      }
    },

    // 编辑授权牌模板
    onTempEdit(row) {
      this.formData.templateId = row.templateId
      this.formData.authUserId = row.authUserId
      this.formData.qrPosition = row.qrPosition
      this.formData.qrSize = row.qrSize
      this.formData.logoSize = row.logoSize
      this.formData.templateImage = row.templateImage
      if (row.templateImage) {
        this.tempList = [{ name: '授权牌模板', url: row.templateImage }]
      }
      this.addCardVisible = true
    },

    // 获取供应商列表
    async fetchSupplierList() {
      try {
        const res = await fetchSupplierList({
          listType: 1,
          infoId: '', // 品牌id
          linkMan: '', // 联系人
          mobile: '', // 手机号
          pageNum: 1, // 页码
          pageSize: 1000, // 分页大小
          shopName: '', // 供应商名称
          shopType: '', // 供应商类型
          loginAccount: '' // 登录账号
        })
        this.supplierList = res.data.list
      } catch (error) {
        console.log(error)
      }
    },

    // 选中供应商
    onSupplierConfirm(type, e) {
      type === 'add' ? (this.addCardInnerVisible = false) : (this.selectSupplierVisible = false)
      this.selectSupplier = e
      this.formData.authUserId = e.authUserId
      if (type === 'edit') {
        this.onChangeSupplierSubmit()
      }
    },

    // 修改供应商操作
    onChangeSupplier(row) {
      this.currentCard = row
      this.selectSupplierVisible = true
    },

    // 修改模板启用状态
    onTempStatusChange(row) {
      row.status = row.status === 0 ? 1 : 0
      this.authTempSave(row)
    },

    // 修改供应商提交
    onChangeSupplierSubmit() {
      this.currentCard.authUserId = this.formData.authUserId
      this.authTempSave(this.currentCard)
    },

    // 修改授权牌供应商弹窗关闭
    onSelectSupplierClose() {
      this.onAddCardClose()
    },

    // 添加授权牌弹窗关闭
    onAddCardClose() {
      this.selectSupplier = null
      this.formData.templateId = ''
      this.formData.authUserId = ''
      this.formData.qrPosition = ''
      this.formData.qrSize = ''
      this.formData.logoSize = ''
      this.formData.templateImage = ''
      this.tempList = []
      this.$refs.addCardForm?.clearValidate()
    },

    // 添加授权牌提交
    async onConfirm() {
      try {
        this.isLoading = true
        await this.$refs.addCardForm.validate()
        await this.authTempSave(this.formData)
      } catch (error) {
        console.log(error)
      } finally {
        this.isLoading = false
      }
    },

    // 授权牌信息保存
    async authTempSave(data) {
      const submitData = objectCover(
        {
          templateId: '',
          templateImage: '',
          authUserId: '',
          status: 1,
          qrPosition: '',
          logoSize: '',
          qrSize: ''
        },
        data
      )
      try {
        await authTempSave(submitData)
        this.$message.success('操作成功')
        this.getList()
        this.addCardVisible = false
      } catch (error) {
        console.log(error)
      }
    },

    // 授权牌模板上传
    uploadTempImageSuccess({ response, file, fileList }) {
      this.tempList = fileList
      this.formData.templateImage = response.data
    },
    handleLogoImageRemove({ file, fileList }) {
      this.tempList = fileList
      this.formData.templateImage = ''
    },

    // 表格序号
    indexMethod(index) {
      return index + this.listQuery.pageSize * (this.listQuery.pageNum - 1) + 1
    }
  }
}
</script>
<style lang="scss" scoped>
.el-image {
  max-width: 120px;
  max-height: 30px;
  display: block;
  margin: 0 auto;
}

.current-info {
  font-size: 14px;
  .supplier-name {
    color: #333;
    margin-right: 6px;
  }
  .supplier-change {
    color: #409eff;
    text-decoration: underline;
    cursor: pointer;
  }
}
</style>
