<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="100px" class="m-t-20">
            <el-row>
              <el-col :span="6">
                <el-form-item label="名称" prop="">
                  <el-input v-model="filter.name" style="width: 220px;" placeholder="请输入专利名称/公司名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="专利类型" prop="">
                  <el-select v-model="filter.patent_type" placeholder="请选择专利类型">
                    <el-option v-for="(item, index) in patentType" :key="index" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="公告时间" prop="">
                  <el-date-picker 
                    v-model="filter.publish_time" 
                    type="date" 
                    placeholder="请选择公告时间"
                    value-format="YYYY-MM-DD"
                    @change="changePublishTime">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="续费时间" prop="">
                  <el-date-picker 
                    v-model="filter.renewals_time" 
                    type="date" 
                    placeholder="请选择续费时间"
                    value-format="YYYY-MM-DD"
                    @change="changeRenewalsTime">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="项目负责人" prop="">
                  <el-cascader
                    v-model="depts"
                    :options="deptData"
                    :props="{
                      expandTrigger: 'hover',
                      value: 'dept_code',
                      label: 'dept_name',
                      children: 'children',
                    }"
                    @change="changeDept"
                  >
                  </el-cascader>
                  <el-select v-model="admin_ids" placeholder="请选择项目负责人" @change="selLeader">
                    <el-option v-for="(item, index) in adminData" :key="index" :label="item.staff_name" :value="item.staff_code"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="1">
                <el-form-item label="申请人" prop="">
                  <el-cascader
                    v-model="admins"
                    :options="deptData"
                    :props="{
                      expandTrigger: 'hover',
                      value: 'dept_code',
                      label: 'dept_name',
                      children: 'children',
                    }"
                    @change="changeDept1"
                  >
                  </el-cascader>
                  <el-select v-model="apply_man" placeholder="请选择申请人" @change="changeAdmin">
                    <el-option v-for="(item, index) in adminData1" :key="index" :label="item.staff_name" :value="item.staff_code"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4" :offset="3">
                <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="6" class="m-l-40">
              <el-button type="primary" @click="addClick">新增专利</el-button>
              <el-button class="m-l-10" type="primary" @click="downloadTemplate('')">下载专利交底模板</el-button>
            </el-col>
          </el-row>
          <el-table class="m-20" :data="tableData" style="width: auto;" border :header-cell-style="header_style">
            <el-table-column fixed prop="id" label="编码" width="80" align="center" />
            <el-table-column fixed prop="name" label="专利名称（型号）" width="180">
              <template #default="scope">
                <span @click="editClick(scope.row)" class="text_blue Cursor">{{scope.row.name}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="patent_type_id" label="专利类型" width="120" />
            <el-table-column prop="admin_ids" label="项目负责人" width="180" />
            <el-table-column prop="progress" label="申请进度" />
            <el-table-column prop="is_outcountry" label="是否涉及国外" width="120" align="center" />
            <el-table-column prop="worth_level" label="价值级别" width="100" align="center" />
            <el-table-column prop="org_ids" label="申请主体" />
            <el-table-column prop="apply_country" label="申请国家" width="100" align="center" />
            <el-table-column prop="" label="技术交底" align="center">
              <template #default="scope">
                <span class="text_blue Cursor" @click="downloadTemplate(scope.row.technical_disclosure)">下载</span>
              </template>
            </el-table-column>
            <el-table-column prop="" label="产品图片" width="180" align="center">
              <template #default="scope">
                <el-image :src="scope.row.production_image" style="width:50px; height:50px"></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="production_desc" label="产品功能简介" width="180" />
            <el-table-column prop="checkout_result" label="检索结果" width="180" />
            <el-table-column prop="apply_result" label="申请结果" width="300" />
            <el-table-column prop="apply_time" label="申请时间" width="120" />
            <el-table-column prop="publish_time" label="公告时间" width="120" />
            <el-table-column prop="renewals_time" label="续费时间" width="120" />
            <el-table-column prop="price" label="单价（￥）" align="center" />
            <el-table-column prop="num" label="数量" width="180" align="center" />
            <el-table-column prop="total_price" label="总计（￥）" width="180" align="center" />
            <el-table-column prop="" label="操作" width="180" align="center">
              <template #default="scope">
                <span @click="editClick(scope.row)" class="text_blue Cursor m-r-10">查看详情</span>
                <span @click="deleteClick(scope.row, scope.$index)" class="text_blue Cursor">删除</span>
              </template>
            </el-table-column>
          </el-table>
          <el-row class=" p-20">
            <el-pagination
              class="pagination"
              v-model="currentPage"
              :page-size="filter.size"
              layout="total, prev, pager, next"
              :total="total"
              @size-change="changePageSize"
              @current-change="changePage"
            >
            </el-pagination>
          </el-row>
        </el-col>
      </el-row>   
    </div>
  </main>
</template>

<script>
import { ElMessageBox } from 'element-plus'
import axios from 'axios'
export default {
  name: 'patent',
  data() {
    return {
      header_style: {
				'background-color': '#F5F7FA',
				'color': '#606266',
				'fontSize': '14px',
				'fontWeight': '600',
				'textAlign':'center',
			},
      form: {
        name: '',
        leader: [],
        progress: [],
        applyTime: '',
        bulletinTime: '',
        renewalTime: ''
      },
      tableData: [],
      currentPage: 1,
      total: 0,
      filter: {
        page: 1,
        size: 10,
        name: '',
        admin_ids: '',
        apply_man: '',
        patent_type: '',
        publish_time: '',
        renewals_time: ''
      },
      adminData: [],
      progress: [],
      patentType: [],
      url: '',
      name: '',
      admin_ids: '',
      apply_man: '',
      depts: [],
      admins: [],
      deptData: [],
      deptCodes: '',
      deptCodes1: '',
      adminData1: []
    }
  },
  created() {
    this.getListData()
    this.getAdminData()
    this.getUrl()
  },
  activated() {
    this.getList()
  },
  methods: {
    // 获取下载链接
    getUrl() {
      this.$http.get('patent/technicalDisclosureTemplate').then(res => {
        if(res.status == 200) {
          this.url = res.data.data.url
          this.name = res.data.data.name
        }
      })
    },
    //选择负责人
    changeDept(val) {
      this.deptCodes = val
      const dept_code = val[val.length - 1]
      this.$http.get('brand/getUserListByDeptCode', { dept_code: dept_code }).then(res => {
        if (res.status == 200) {
          this.adminData = res.data.data
        }
      })
    },
    selLeader(val) {
      let admin_ids = {dept: [], user: []}
      admin_ids.dept = this.deptCodes
      admin_ids.user.push(val)
      this.filter.admin_ids = JSON.stringify(admin_ids)
    },
    //申请人
    changeDept1(val) {
      this.deptCodes1 = val
      const dept_code = val[val.length - 1]
      this.$http.get('brand/getUserListByDeptCode', { dept_code: dept_code }).then(res => {
        if (res.status == 200) {
          this.adminData1 = res.data.data
        }
      })
    },
    changeAdmin(val) {
      let apply_ids = {dept: [], user: []}
      apply_ids.dept = this.deptCodes1
      apply_ids.user.push(val)
      this.filter.apply_man = JSON.stringify(apply_ids)
    },
    //选择进度
    selProgress(val) {
      this.filter.progress = val
    },
    // 申请时间
    changeApplyTime(val) {
      console.log(val)
      this.filter.apply_time = val
    },
    changePublishTime(val) {
      this.filter.publish_time = val
    },
    changeRenewalsTime(val) {
      this.filter.renewals_time = val
    },
    //搜索
    searchClick() {
      this.filter.page = 1
      this.filter.size = 10
      this.getList()
    },
    // 重置
    reset() {
      this.filter = {
        page: 1,
        size: 10,
        name: '',
        admin_ids: '',
        apply_man: '',
        progress: '',
        apply_time: '',
        publish_time: '',
        renewals_time: ''
      }
      this.depts = []
      this.admins = []
      this.admin_ids = ''
      this.apply_man = ''
      this.getList()
    },
    // 获取列表数据
    getListData() {
      this.$http.get('patent/constList').then(res => {
        if (res.status == 200) {
          const data = res.data.data
          this.progress = data.progress
          this.patentType = data.patent_type_id
        }
      })
    },
    // 获取项目负责人数据
    getAdminData() {
      this.$http.get('patent/getAllDeptList').then(res => {
        if (res.status == 200) {
          this.deptData = res.data.data
        }
      })
    },
    //专利list
    getList() {
      this.$http.get('patent/index', this.filter).then(res => {
        console.log(res)
        if (res.status == 200 ) {
          this.tableData = res.data.data.data
          this.total = res.data.data.count
        }
      })
    },
    // 改变每页请求条数
    changePageSize(size) {
        this.filter.size = size;
        this.getList();
    },
    // 翻页
    changePage(page) {
        this.filter.page = page;
        this.getList();
    },
    // 新增商标
    addClick() {
      this.$router.push({
        path: '/PIP/patent_add'
      })
    },
    // 编辑
    editClick(row) {
      this.$router.push({
        path: '/PIP/patent_edit',
        query: {
          id: row.id
        }
      })
    },
    // 删除
    deleteClick(row, index) {
      console.log(row, index)
      ElMessageBox.confirm('确认删除该专利？', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            this.$http.delete('patent/delete/id?id=' + row.id ).then(res => {
              if (res.status == 200) {
                this.getList()
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
          }
          done()
        }
      })
    },
    // 下载模板
    downloadTemplate(data) {
      this.$message({
        type: 'success',
        message: '正在下载，请稍后...'
      })
      let url = ''
      if (data == '') {
        url = this.url
      } else {
        url = data
      }
      axios.get(url, {
        responseType: 'blob',
        headers: {
          /*'X-Token': getToken(),*/
          'Content-Type': 'application/json;charset=utf-8'
        }
      }).then(res => {
        if (!res) {
          this.$message.error('下载模板文件失败')
          return false
        }
        const stream = res.data // 后端用stream返回Excel文件
        const blob = new Blob([stream])
        // 前端获取业务码，成功执行正常业务
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.href = href
        const timeStamp = new Date().toString()
        const url_arr = res.config.url.split('/')
        const nameStr = decodeURI(url_arr[url_arr.length - 1])
        console.log(nameStr)
        downloadElement.download = nameStr // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href) // 释放掉blob对象
      })
    }
  }
}
</script>

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