<template>
  <main class="m-20">
    <div class="wrap text-black">
      <!--顶部搜索-->
      <el-row class="bg_white searchBox">
        <el-col :span="24">
          <el-form ref="form" :model="filter" label-width="115px" :content="this.filter" class="m-t-20"
            @keydown.enter.native="searchClick">
            <el-row>
              <el-col :span="5">
                <el-form-item label="商标名称" prop="">
                  <el-input v-model="filter.brand_name" maxlength="50" limit style="width:230px;" placeholder="请输入商标名称">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="注册号" prop="">
                  <el-input v-model="filter.reg_code" maxlength="50" style="width:230px;" placeholder="请输入注册号">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="申请号" prop="">
                  <el-input v-model="filter.apply_code" maxlength="50" style="width:230px;" placeholder="请输入申请号">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="国家/地区" prop="">
                  <el-input v-model="filter.register_country" maxlength="50" style="width:200px;"
                    placeholder="请输入国家/地区">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="申请人" prop="">
                  <el-input v-model="filter.apply_name" maxlength="50" style="width:200px;" placeholder="请输入申请人姓名">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="申请日期" prop="">
                  <el-input v-model="filter.apply_time" maxlength="50" style="width:230px;" placeholder="请输入申请日期">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="注册日期" prop="">
                  <el-input v-model="filter.reg_time" maxlength="50" style="width:230px;" placeholder="请输入注册日期">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="有效期" prop="">
                  <el-input v-model="filter.validity_time" maxlength="50" style="width:230px;" placeholder="请输入有效期">
                  </el-input>
                </el-form-item>

              </el-col>
              <el-col :span="4">
                <el-form-item label="核定商品/服务组别" prop="">
                  <el-input v-model="filter.serve_group" maxlength="50" style="width:200px;" placeholder="请核定商品/服务组别">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="申请人地址" prop="">
                  <el-input v-model="filter.apply_addr" maxlength="50" style="width:200px;" placeholder="请输入申请人地址">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="申请人英文名称" prop="">
                  <el-input v-model="filter.apply_name_en" maxlength="50" style="width:230px;" placeholder="请输入申请人英文名称">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="申请人英文地址" prop="">
                  <el-input v-model="filter.apply_addr_en" maxlength="50" style="width:230px;" placeholder="请输入申请人英文地址">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="类别" prop="">
                  <el-input v-model="filter.cate" maxlength="50" style="width:230px;" placeholder="请输入类别"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="商标状态" prop="">
                  <el-input v-model="filter.brand_status" maxlength="50" style="width:200px;" placeholder="请输入商标状态">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="代理机构" prop="">
                  <el-input v-model="filter.agent_org" maxlength="50" style="width:200px;" placeholder="请输入代理机构">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="22">
              </el-col>
              <el-col :span="2" style="float:right;margin:0 0 20px 0;">
                <el-button type="primary" @click="searchClick">搜索</el-button>
                <el-button type="primary" @click="reset">重置</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
      <!--table-->
      <el-row class="bg_white m-t-20">
        <el-col :span="24">
          <el-row class="m-t-20">
            <el-col :span="24" class="m-l-40">
              <el-button type="primary" @click="addClick" class="cus-point">新增商标</el-button>
              <el-button class="m-l-10 cus-point" type="primary" @click="actiontype('a')">下载导入模板</el-button>
              <el-button class="m-l-10 cus-point" type="primary" @click="actiontype('b')">批量导出</el-button>
              <el-button class="m-l-10 cus-point" type="primary" @click="actiontype('c')">批量导入</el-button>
              <el-button class="m-l-10 cus-point" type="primary" @click="downloadCert">批量下载证书</el-button>
            </el-col>
          </el-row>
          <el-table class="m-20" :data="tableData" style="width: auto;" max-height="650" border
            :header-cell-style="header_style">
            <el-table-column fixed prop="id" label="编码" width="100" align="center">
              <template #default="scope">
                <span @click="editAndAddBrand(scope.row)" class="text_blue Cursor">{{scope.row.id}}</span>
              </template>
            </el-table-column>
            <el-table-column fixed prop="brand_name" label="商标名称" width="100" />
            <el-table-column fixed prop="brand_logo" label="商标" width="100">
              <template #default="scope">
                <div v-if="scope.row.brand_logo">
                  <img :src="scope.row.brand_logo" style="width:80px;" />
                </div>
                <div v-if="!scope.row.brand_logo && scope.row.brand_name">
                  <span>{{scope.row.brand_name}}</span>
                </div>
                <div v-if="!scope.row.brand_logo && !scope.row.brand_name"></div>
              </template>
            </el-table-column>
            <el-table-column fixed prop="brand_cate" label="商标类型" width="100" />
            <el-table-column fixed prop="register_country" label="国家/地区" width="120" align="center" />
            <el-table-column fixed prop="apply_code" label="申请号" width="140" />
            <el-table-column fixed prop="reg_code" label="注册号" width="140" />
            <el-table-column prop="cate" label="类别" width="120" />
            <el-table-column prop="apply_time" label="申请时间" width="120" />
            <el-table-column prop="publish_time" label="公告时间" width="120" />
            <el-table-column prop="reg_time" label="注册日期" width="120" />
            <el-table-column prop="validity_time" label="有效期至" width="120" />
            <el-table-column prop="apply_name" label="申请人" width="120" />
            <el-table-column prop="apply_addr" label="申请人地址" width="200">
              <template #default="scope">
                <el-popover effect="light" trigger="hover" placement="top" width="auto">
                  <template #default>
                    <div> {{ scope.row.apply_addr }}</div>
                  </template>
                  <template #reference>
                    <el-tag>{{ scope.row.apply_addr }}</el-tag>
                  </template>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="agent_org" label="代理机构" width="120">
              <template #default="scope">
                <el-popover effect="light" trigger="hover" placement="top" width="auto">
                  <template #default>
                    <div> {{ scope.row.agent_org }}</div>
                  </template>
                  <template #reference>
                    <el-tag>{{ scope.row.agent_org }}</el-tag>
                  </template>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="brand_status" label="商标状态" width="120" />
            <el-table-column prop="register_name" label="原注册人" width="120" />
            <el-table-column prop="apply_name_en" label="申请人英文名称" width="120" />
            <el-table-column prop="apply_addr_en" label="申请人英文地址" width="380" />
            <el-table-column prop="serve_group" label="核定商品/服务组别" width="120">
              <template #default="scope">
                <el-popover effect="light" trigger="hover" placement="top" width="500px">
                  <template #default>
                    <div> {{ scope.row.serve_group }}</div>
                  </template>
                  <template #reference>
                    <el-tag>{{ scope.row.serve_group }}</el-tag>
                  </template>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="goods_serve" class="text-ovhid" label="核定商品/服务" width="1000">
              <template #default="scope">
                <el-popover effect="light" trigger="hover" placement="top" width="500px">
                  <template #default>
                    <div> {{ scope.row.goods_serve }}</div>
                  </template>
                  <template #reference>
                    <el-tag>{{ scope.row.goods_serve }}</el-tag>
                  </template>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="cert" label="证书" width="160">
              <template #default="scope">
                <el-upload ref="upload" :action="api_upload_url" name="file" :show-file-list="false"
                  :with-credentials="true"
                  :on-success=" (response, file, fileList) => handlezsSuccess(response, file, fileList,scope.row )"
                  accept=".jpg, .pdf" :file-list="fileList" style="float: left;">
                  <el-button size="small" type="primary">上传</el-button>
                </el-upload>
                <el-button class="m-l-10" type="primary" style="float: left;" size="small"
                  @click="downFileBtn(scope.row)">下载</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-row class="p-20">
            <el-pagination class="pagination" v-model="currentPage" :page-size="filter.size"
              :page-sizes="[10, 20, 50, 100]" :total="total" @size-change="changePageSize" @current-change="changePage"
              layout="total, sizes, prev, pager, next, jumper">
            </el-pagination>
          </el-row>
        </el-col>
      </el-row>
    </div>
    <!--模板下载-->
    <el-dialog v-model="modelDownload" :show-close="true" append-to-body width="350px" custom-class="del-style"
      title="请选择模板">
      <div v-if='actiontag !== "c"'>
        <el-button type="primary" @click="terApplyDown(0)">国内商标申请</el-button>
        <el-button type="primary" @click="terApplyDown(1)">海外商标申请</el-button>
      </div>
      <div v-else>
        <el-button style="border: 0;padding:0">
          <el-upload action :auto-upload="false" :multiple="false" :show-file-list="false" :on-change="uploadBygn"
            style="float: left;" ccept=".xlsx, .xls">
            <el-button type="primary" style="margin-right:10px">国内商标申请</el-button>
          </el-upload>
          <el-upload action :auto-upload="false" :multiple="false" :show-file-list="false" :on-change="uploadByhw"
            style="float: left;">
            <el-button type="primary">海外商标申请</el-button>
          </el-upload>
        </el-button>
      </div>
    </el-dialog>

  </main>
</template>

<script>
import { ElMessageBox } from 'element-plus'
import axios from 'axios'
export default {
  name: 'trademark',
  data () {
    return {
      fileList: [], //上传的文件列表
      actiontag: '',
      header_style: {
        'background-color': '#F5F7FA',
        'color': '#606266',
        'fontSize': '14px',
        'fontWeight': '600',
        'textAlign': 'center',
      },
      form: {
        name: '',
        apply_name: '',
        leader: [],
        progress: [],
        applyTime: '',
        bulletinTime: '',
        renewalTime: ''
      },
      modelDown: false,
      modelDownload: false,
      tableData: [],
      currentPage: 1,
      total: 0,
      filter: {
        page: 1,
        size: 10,
        brand_name: '',
        brand_logo: '',
        reg_code: '',
        apply_code: '',
        register_country: '',
        apply_time: '',
        reg_time: '',
        validity_time: '',
        apply_name: '',
        apply_addr: '',
        agent_org: '',
        goods_serve: '',
        brand_status: '',
        apply_name_en: '',
        apply_addr_en: '',
        serve_group: '',
        cate: '',
      },
      trademarkTitle: '',
      adminData: [],
      progress: [],
      category: [],
      url: '',
      name: '',
      depts: [],
      admins: [],
      admin_ids: '',
      apply_man: '',
      deptCodes: '',
      deptCodes1: '',
      adminData1: []
    }
  },
  computed: {
    //上传文件地址
    api_upload_url () {
      return process.env.VUE_APP_API_BASEURL + 'admin/upload/fileLocal'
    }
  },
  created () {
    this.getList()
  },
  activated () {
    this.getList()
  },
  methods: {
    // 限制文件格式
    fileUpload (file) {
      this.beforeAvatarUpload(file, 'zs')
    },

    //单条证书文件上传成功时
    handlezsSuccess (res, file, list, item) {
      if (res) {
        console.log('单条证书文件上传成功时', res, item)
        if (res.status == 200) {
          res.data.id = item.id
          this.$http.post('brand/uploadCert', res.data).then(res => {
            this.$message.success('上传成功')
          })
        }
      }
    },
    //单位件下载
    downFileBtn (item) {
      console.log(item, '55444444')
      this.$http.get('brand/downloadCert', {
        brand_name: this.filter.brand_name,
        reg_code: this.filter.reg_code,
        apply_time: this.filter.apply_time,
        apply_code: this.filter.apply_code,
        validity_time: this.filter.validity_time,
        apply_name: this.filter.apply_name,
        register_country: this.filter.register_country,
        goods_serve: this.filter.goods_serve,
        agent_org: this.filter.agent_org,
        apply_addr_en: this.filter.apply_addr_en,
        apply_addr: this.filter.apply_addr,
        cate: this.filter.cate,
        brand_status: this.filter.brand_status,
        id: item.id,
        api: 1
      }).then(res => {
        if (res.errno === 200) {
          this.downloadCategory(item)
        } else {
          this.$message.error(res.errmsg)
        }
      })
    },
    //点击动作区分 actiontag
    actiontype (val) {
      //判断有数据的时候执行导出，无数据的时候弹出暂无数据
      if (this.tableData.length > 0) {
        this.modelDownload = true
        this.actiontag = val
      }
      else {
        this.$message.error('数据为空')
      }
    },
    //批量下载证书
    downloadCert () {
      //批量下载循环检测
      this.tableData.forEach(item => {
        this.downFileBtn(item)
      })
    },
    //文件校验方法
    beforeAvatarUpload (file, type) {
      // 通过split方法和fileArr方法获取到文件的后缀名
      let fileArr = file.name.split('.')
      let suffix = fileArr[fileArr.length - 1]
      //只能导入.xls和.xlsx文件
      if (type != 'zs') {
        if (!/(xls|xlsx)/i.test(suffix)) {
          this.$message.error('文件格式不正确,仅excel文件')
          this.loading.close()
          return false
        }
      } else {
        if (!/(jpg|pdf)/i.test(suffix)) {
          this.$message.error('文件格式不正确,仅支持PDF、JPG文件格式')
          this.loading.close()
          return false
        }
      }
      //不能导入大小超过2Mb的文件
      if (file.size > (type == 'zs' ? 2 : 5) * 1024 * 1024) {
        this.$message('文件过大，请上传小于' + (type == 'zs' ? 2 : 5) + 'MB的文件〜')
        this.loading.close()
        return false
      }
      return true
    },
    // 表格证书上传
    uploadByzs (file) {
      this.uploadByJsqd(file, 'zs')
    },
    //批量导入_国外
    uploadBygn (file) {
      this.uploadByJsqd(file, 'cn')
    },
    //批量导入_海外
    uploadByhw (file) {
      this.uploadByJsqd(file, 'oth')
    },
    //批量导入
    uploadByJsqd (file, type) {
      this.loading = this.$loading({
        lock: true,
        text: '此操作需要一段时间请耐心等待...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      //判断是否符合beforeAvatarUpload方法中的条件
      if (this.beforeAvatarUpload(file, type)) {
        this.fileList.name = file.name
        this.fileList.url = ''
        var formdata = new FormData()
        formdata.append('file', file.raw)
        formdata.append('temp_type', type)
        this.$http.post('brand/import', formdata).then(res => {
          if (res.errno == 200) {
            this.$message({
              message: '导入成功',
              type: 'success'
            })
            this.getList() //调用表格方法，刷新页面
          } else {
            let str = ''
            if (res.data.length > 0) {
              res.data.forEach(it => {
                str = str + '<span>' + it + '</span><br>'
              })
            }
            this.$alert('<div style="max-height:450px;overflow:auto">' + res.errmsg + '</br>' + str + '</div>', '导入失败提示', {
              confirmButtonText: '确定',
              customClass: 'msgbox',
              dangerouslyUseHTMLString: true
            })
          }
          // 导出新老sku 导出预加载
          this.loading.close()
        })
      }
    },
    //批量导出
    exportlist (type) {
      // 导出新老sku 导出预加载
      this.loading = this.$loading({
        lock: true,
        text: '此操作需要一段时间请耐心等待...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const apiVersion = process.env.VUE_APP_API_VERSION.replace(/\./g, '_')
      axios
        .get(
          process.env.VUE_APP_API_BASEURL + apiVersion + '/' + 'brand/export?brand_name=' + this.filter.brand_name + '&reg_code=' + this.filter.reg_code + '&apply_time=' + this.filter.apply_time + '&apply_code=' + this.filter.apply_code + '&register_country=' + this.filter.register_country + '&reg_time=' + this.filter.reg_time + '&validity_time=' + this.filter.validity_time + '&apply_name=' + this.filter.apply_name + '&apply_addr=' + this.filter.apply_addr + '&agent_org=' + this.filter.agent_org + '&goods_serve=' + this.filter.goods_serve + '&brand_status=' + this.filter.brand_status + '&apply_name_en=' + this.filter.apply_name_en + '&apply_addr_en=' + this.filter.apply_addr_en + '&cate=' + this.filter.cate + (type ? '&temp_type=oth' : '&temp_type=cn'),
          {
            responseType: 'blob',
            headers: {
              'Content-Type': 'application/json;charset=utf-8'
            }
          }
        )
        .then(res => {
          if (!res) {
            this.$message.error('文件导出失败')
            return false
          }
          let a = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel",
          });
          let url = window.URL.createObjectURL(blob)
          a.setAttribute("href", url)
          a.setAttribute("download", type ? "海外.xlsx" : '国内.xlsx')
          a.click()
          this.loading.close()
        })
    },
    //下载导入模板
    urldownload (url) {
      var downloadPath = url
      console.log('获得地址数据:', downloadPath)
      var downloadLink = document.createElement('a')
      downloadLink.style.display = 'none' // 使其隐藏
      downloadLink.href = downloadPath
      downloadLink.download = ''
      downloadLink.click()
      document.body.removeChild(downloadLink)
    },
    //国内商标文件下载
    terApplyDown (val) {
      //下载导入模板
      if (this.actiontag === 'a') {
        this.$http.get('brand/downloadTemplate').then(res => {
          if (res.errno === 200) {
            if (val == 0) {
              this.urldownload(res.data.domestic)
            }
            if (val == 1) {
              this.urldownload(res.data.overseas)
            }
          }
        })
      }
      //批量导出
      if (this.actiontag === 'b') {
        this.exportlist(val)
      }
    },
    //搜索
    searchClick () {
      this.filter.page = 1
      this.filter.size = 20
      this.getList()
    },
    // 重置
    reset () {
      this.filter = {
        page: 1,
        size: 10,
        brand_name: '',
        reg_code: '',
        apply_code: '',
        register_country: '',
        apply_time: '',
        reg_time: '',
        validity_time: '',
        apply_name: '',
        apply_addr: '',
        agent_org: '',
        goods_serve: '',
        brand_status: '',
        apply_name_en: '',
        apply_addr_en: '',
        cate: '',
      }
      this.depts = []
      this.admins = []
      this.admin_ids = ''
      this.apply_man = ''
      this.getList()
    },
    //列表数据
    getList () {
      this.$http.get('brand/list', this.filter).then(res => {
        console.log(res)
        if (res.errno == 200) {
          this.tableData = res.data.data
          this.total = res.data.total
        }
      })
    },
    // 改变每页请求条数
    changePageSize (size) {
      this.filter.size = size;
      this.getList();
    },
    // 翻页
    changePage (page) {
      this.filter.page = page;
      this.getList();
    },
    // 新增商标
    addClick () {
      this.$router.push({
        path: '/PIP/trademark_add'
      })
    },
    // 编辑
    editAndAddBrand (row) {
      this.$router.push({
        path: '/PIP/trademark_edit',
        query: {
          id: row.id
        }
      })
    },
    // 批量下载证书请求
    downloadCategory (item) {
      console.log(item, '11')
      // 导出新老sku 导出预加载
      this.loading = this.$loading({
        lock: true,
        text: '此操作需要一段时间请耐心等待...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const apiVersion = process.env.VUE_APP_API_VERSION.replace(/\./g, '_')
      axios
        .get(
          process.env.VUE_APP_API_BASEURL + apiVersion + '/' + 'brand/downloadCert?brand_name=' + this.filter.brand_name + '&reg_code=' + this.filter.reg_code + '&apply_time=' + this.filter.apply_time + '&apply_code=' + this.filter.apply_code + '&register_country=' + this.filter.register_country + '&reg_time=' + this.filter.reg_time + '&validity_time=' + this.filter.validity_time + '&apply_name=' + this.filter.apply_name + '&apply_addr=' + this.filter.apply_addr + '&agent_org=' + this.filter.agent_org + '&goods_serve=' + this.filter.goods_serve + '&brand_status=' + this.filter.brand_status + '&apply_name_en=' + this.filter.apply_name_en + '&apply_addr_en=' + this.filter.apply_addr_en + '&cate=' + this.filter.cate + (item && item.id ? '&id=' + item.id : '') + '&api=0',
          {
            responseType: 'blob',
            headers: {
              /*'X-Token': getToken(),*/
              'Content-Type': 'application/json;charset=utf-8'
            }
          }
        )
        .then((res, err) => {
          console.log(res, err, 'res')
          if (!res) {
            this.$message.error('下载文件失败')
            return false
          }

          let a = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel",
          });
          let url = window.URL.createObjectURL(blob)
          a.setAttribute("href", url)
          a.setAttribute("download", '证书.zip')
          a.click()
          this.loading.close()
        })
      this.loading.close()
    }
  }
}
</script>

<style scoped>
.wrap {
  width: auto;
}

::v-deep(.el-dialog__header) {
  margin-top: 100%;
}
::v-deep(.el-form-item) {
  margin-bottom: 10px;
}
::v-deep(.el-table .cell) {
  word-break: break-all;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}
.cus-point {
  cursor: pointer;
}
::v-deep(.el-form-item__label) {
  line-height: 18px;
  padding: 12px 12px 0 0;
  font-size: 12px;
}
::v-deep(.el-button) {
  min-height: 34px;
  padding: 6px 15px !important;
}
::v-deep(.el-tag) {
  white-space: inherit;
  border: 0;
  background: none;
  line-height: 20px;
  color: #666;
  word-break: break-all;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  height: auto;
}
</style>