<template>
  <div style="margin: 20px;">
    <div style="display: flex;margin-bottom: 20px;">
      <el-input v-model="queryParams.productName"  size="small" placeholder="请输入产品名称" style="width: 300px;margin-right: 10px;"></el-input>
      <el-input v-model="queryParams.companyName"  size="small" placeholder="请输入产品所属公司名称" style="width: 300px;margin-right: 10px;"></el-input>
      <el-button type="primary" size="small" @click="getList2">查询</el-button>
      <el-dropdown @command="handleCommandAdd">
        <el-button type="primary" size="small">
          新增产品<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="1">新增本公司产品</el-dropdown-item>
          <el-dropdown-item command="2">新增外公司产品</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <!-- 表格 -->
    <el-table
      :data="tableData"
      border
      header-row-class-name="custom-table-header"
      @sort-change="sortChange"
      style="width: 100%">
      <!-- type="expand"开启后展开行 -->
      <el-table-column prop="productName" label="产品名称" sortable="custom" align="center">
          <template slot-scope="scope">
            <div class="items">
              <el-link v-if="sign == 1" @click="rowClick(scope.row)">{{scope.row.productName}}  </el-link>
              <span v-else>{{scope.row.productName}} </span>
            </div>
          </template>  
      </el-table-column>
      <el-table-column prop="marketTime" label="上市时间" sortable="custom" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.marketTime?scope.row.marketTime.slice(0,10):'' }}</span>
        </template>
       </el-table-column>
      <el-table-column prop="companyName" label="所属公司或租户名称" align="center"> </el-table-column>
      <el-table-column prop="licenseRate" label="参考许可费率" sortable="custom" align="center" width="180"> </el-table-column>
      <!-- <el-table-column prop="pictures" label="产品图片" align="center"> </el-table-column> -->
      <el-table-column prop="productExplain" label="产品说明" align="center"> </el-table-column>
      <el-table-column label="操作" width="180" align="center"> 
        <template slot-scope="scope">
          <!-- <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button> -->
          <el-dropdown split-button type="primary" size="small" @command="handleCommand($event,scope.row)" @click="handleEdit(scope.row)">
            <p>编辑</p> 
            <el-dropdown-menu slot="dropdown" style="text-align: center;">
              <el-dropdown-item command="7">预览图片</el-dropdown-item>
              <el-dropdown-item command="1">产品架构</el-dropdown-item>
              <el-dropdown-item command="2">产品的营销数据</el-dropdown-item>
              <el-dropdown-item command="3">营销数据的趋势图</el-dropdown-item>
              <el-dropdown-item command="4">专利布局可视化</el-dropdown-item>
              <el-dropdown-item command="5">相关专利</el-dropdown-item>
              <el-dropdown-item :divided="true" command="6"> <span style="color: red;">删除</span> </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div style="display: flex;justify-content: center;">
      <el-pagination
        background
        layout="total,prev, pager, next,jumper"
        :total="total"
        @current-change="handleCurrentChange"
        :current-page="queryParams.current" :page-size="queryParams.size">
      </el-pagination>
    </div>
    
    <!-- 新增、编辑弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="visible"
      width="500"
      :close-on-click-modal="false"
      append-to-body
      :before-close="close">

      <el-form :rules="rules" ref="productForm" :model="productForm" label-width="100px">
        <el-form-item label="所属产品类别 " prop="productCategoryName">
          <el-input v-model="productForm.productCategoryName" disabled placeholder="请输入所属产品类别"></el-input>
        </el-form-item>
        <el-form-item label="产品名称 " prop="productName">
          <el-input v-model="productForm.productName" placeholder="请输入产品名称"></el-input>
        </el-form-item>
        <el-form-item label="上市时间 " prop="marketTime">
          <!-- <el-input v-model="productForm.marketTime" placeholder="请输入上市时间"></el-input> -->
          <el-date-picker
            v-model="productForm.marketTime"
            type="date"
            placeholder="请选择上市时间"
            value-format="yyyy-MM-dd"
            style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="所属公司 " prop="companyName">
          <el-input v-model="productForm.companyName" :disabled="productForm.tenantId?true:false" placeholder="请输入所属公司或租户名称"></el-input>
        </el-form-item>
       
        <el-form-item label="参考许可费率 " prop="licenseRates">
          <el-input v-model="productForm.licenseRates" placeholder="请输入参考许可费率(参考许可费率介于0-1之间)"></el-input>
          <!-- <el-input-number v-model="productForm.licenseRate" :precision="2" :step="0.05" :max="1" :min="0" placeholder="请输入许可费率" style="width: 100%;"></el-input-number> -->
        </el-form-item>
        <el-form-item label="图片 ">
          <!-- <el-input v-model="productForm.pictures"></el-input> -->
          <el-upload ref="upload"  action="#" :auto-upload="false"  :on-change="handleChange"  list-type="picture" :show-file-list="false">
          <span v-if="productForm.pictures && productForm.pictures.length>0" class="avatar">
            <span class="deleteImg">
             <span> 
              <i class="el-icon-zoom-in" @click.stop="handlePictureCardPreview"></i>
              <i class="el-icon-delete" @click.stop="handleRemove"></i></span>
            </span>
            <el-image ref="image" style="width:100%;height: 100%;" :src="productForm.pictures[0].id? $p + productForm.pictures[0].url:productForm.pictures[0].url" :preview-src-list="productForm.pictures?productForm.pictures.map(item=>{return item.id? $p + item.url:item.url}):[]"></el-image>
          </span>
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        </el-form-item>
        <el-form-item label="产品说明 ">
          <el-input v-model="productForm.productExplain" type="textarea" placeholder="请输入产品说明"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="sure">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="MarketVisible" width="1200px" :close-on-click-modal="false">
      <div>
        <Marketing-Data :row="rowData"></Marketing-Data>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MarketingData from './marketingData.vue'
import { commonMethods } from './mixins'
export default {
  props:['categoryRow','clientName','sign','patentNo'],
  components:{
    MarketingData
  },
  mixins:[commonMethods],
  data() {
    const licenseRateRule = (rule , value ,callback)=>{
      if(value){
         if (!isNaN(value)) {
          if (value>=0 && value<=1) {
            this.productForm.licenseRates=value
            this.productForm.licenseRate=this.productForm.licenseRates
            callback()
          } else {
            callback(new Error('输入错误，参考许可费率介于0-1之间'))
          }
        } else {
          callback(new Error('输入错误，参考许可费率介于0-1之间'))
        }
      }else{
        callback()
      }
    }
    return {
      input: '',
      rowData:{},
      left:'left',
      tableData: [],
      productForm:{},
      visible: false,
      MarketVisible:false,
      title: null,
      queryParams: {
        productCategoryId : this.categoryRow.id,
        patentNo:this.patentNo?this.patentNo[0]:null,
        // licenseRate : this.categoryRow.licenseRate,
        orderBy:'',//排序名称
        orderType:'',//排序类型
        size: 10,
        current:1,
      },
      total:0,
      file:[],
      rules: {
        // productCategoryName:[{ required: true, message: '请输入产品类别名称', trigger: 'change' },],
        productName:[{ required: true, message: '请输入产品名称', trigger: 'blur' },],
        licenseRates:[{ required: false, validator:licenseRateRule, trigger: 'blur' },],
      }
    }
  },
  computed: {
    userinfo() {
      return this.$store.state.user.userinfo
    }
  },
  watch:{
    patentNo(val){
      this.queryParams.patentNo = val[0]
      this.getList()
    }
  },
  mounted() { 
    this.getList()
  },
  methods: {
    rowClick (row) {
      this.$emit('productId', row.id)
    },
    //查询
    getList() { 
      this.$api.queryProducts(this.queryParams).then(res => {
        if (res.code==200) {
          this.tableData = res.data.list
          this.total=res.data.totalSizes
        }
      })
    },
    getList2() {
      this.queryParams.current = 1
      this.getList();
    },
    // 排序
    sortChange(row) {
      switch (row.order) {
        case "ascending":
          // this.queryParams.orderType = 
          this.queryParams.orderBy = row.prop
          this.getList()
          break;
        case "descending":
          // this.queryParams.orderType = 
          this.queryParams.orderBy = row.prop
          this.getList()
          break;
        default:
          break;
      }
    },
    // 新增产品
    handleCommandAdd(command) {
       //产品类别
      this.productForm.productCategoryId = this.categoryRow.id
      this.productForm.productCategoryName = this.categoryRow.productCategoryName
      this.productForm.patentNo = this.queryParams.patentNo
      this.$set(this.productForm,'licenseRates',this.categoryRow.licenseRate)
      this.productForm.licenseRate = this.categoryRow.licenseRate
      switch (command) {
        case '1':
          this.title = '新增本公司产品'
          // 获取所属租户公司
          this.productForm.companyName=this.userinfo.tenantName
          this.productForm.tenantId=this.userinfo.tenantId
          this.visible=true
          break;
        case '2':
          this.title = '新增外公司产品'
          this.$set(this.productForm,'companyName',this.clientName)
          this.visible=true
          break;
      
        default:
          break;
      }
     
    },
    // 编辑
    handleEdit(row) { 
      this.title = '编辑产品'
      this.productForm = JSON.parse(JSON.stringify(row))
      this.$set(this.productForm,'licenseRates',this.productForm.licenseRate)
      this.productForm.productCategoryName = this.categoryRow.productCategoryName
      this.visible=true
    },
    // 编辑右侧菜单项
    handleCommand(ev,row) { 
      switch (ev) {
        case '1':// 产品的架构
          this.frameworkIndex(row)
          break;
        case '2': // 产品的营销数据
          this.rowData = row
          this.title = row.productName+'营销数据'
          this.MarketVisible = true
          break;
        case '3':
          this.showTrend(row,2)
          // 产品趋势图
          break;
        case '4':
          this.getMind(row,2)
          // 产品可视化
          break;
        case '5':
          // 产品相关价值专利
          this.relatedPatentsIndex(row)
          break;
        case '6':
          this.$confirm('此操作将永久删除该产品, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            this.$api.deleteProducts({id:row.id}).then(res => {
              if (res.code == 200) {
                if (this.tableData.length == 1 && this.queryParams.current != 1) {
                  this.queryParams.current -= 1
                }
                this.getList()
                this.$message.success("删除产品成功")
              }
            })
          }).catch(() => {
            this.$message.info("已取消删除")
          });
          break;
        case '7':// 图片预览
          if (row.pictures && row.pictures.length>0) {
              var item = row.pictures[0]//图片每条信息
              var FileUrl = this.$p + row.pictures[0].url//每张图片的url
              var isPicture = 1
              const router = this.$router.resolve({
                    path: '/checkFile',
                    query: {
                        row: JSON.stringify(item),
                        FileUrl: FileUrl,
                        isPicture:isPicture,
                    }
                })
              window.open(router.href, '_blank');
          } else {
            this.$message.info("暂无图片，请先上传图片再进行预览！")
          }
          break;
      
        default:
          break;
      }
    },
    
    frameworkIndex(row) {
      const router = this.$router.resolve({
        path: '/frameworkIndex',
      })
      this.$s.setSession('productRow',row)
      window.open(router.href, '_blank');
    },
    relatedPatentsIndex(row) {
      const router = this.$router.resolve({
        path: '/relatedPatentsIndex',
        query: {
          id:row.id,
          name:row.productName
        }
      })
      // this.$s.setSession('patentsProductRow',row)
      window.open(router.href, '_blank');
    },
    // 弹窗确定
    sure() {
      this.$refs.productForm.validate(valid => {
        if (valid) {
          
          var formData = new FormData()
          if (this.file) {
            for (var i = 0; i < this.file.length; i++) {
              formData.append("files", this.file[i]);
            }
          }
          formData.append('jsons', JSON.stringify(this.productForm))

          if (this.productForm.id) {
            this.$api.updateProducts(formData).then(res => {
              if (res.code == 200) {
                this.$message.success("编辑产品成功")
                this.getList()
                this.close()
              }
            })
          } else {
             this.$api.addNewProducts(formData).then(res => {
              if (res.code == 200) {
                this.$message.success("新增产品成功")
                this.getList()
                this.close()
              }
            })
          }
         
        }
      })
      
      
    },
    // 弹窗关闭
    close() {
      this.productForm = {}
      this.file = []
      this.$refs.upload.clearFiles()
      this.visible = false
    },
    // 分页
    handleCurrentChange(val) {
      this.queryParams.current = val
      this.getList()
    },
    // 许可费率事件//优化
    // inpBlur(val) {
    //   console.log(val)
    //   if (val) {
    //     if (!isNaN(val)) {
    //       if (val >= 0 && val <= 1) {
    //         this.productForm.licenseRate = val
    //       } else {
    //         if (val > 1) {
    //           this.productForm.licenseRate = 1
    //           this.productForm.licenseRates = 1
    //         }
    //         if (val < 0) {
    //           this.productForm.licenseRate = 0
    //           this.productForm.licenseRates = 0
    //         }
    //       }
    //     } else {
    //       this.productForm.licenseRates = this.productForm.licenseRate?this.productForm.licenseRate:''
    //     }
    //   }
      
    // },
    // 上传图片
    handlePictureCardPreview(file) {
        this.$refs.image.showViewer = true
    },
    handleRemove() {
      this.file = []
        this.productForm.pictures = []
    },
    handleChange(file, fileList) {
      this.$set(this.productForm,'pictures', [{url:file.url}])
      this.file=[file.raw]
    },
   
  },
}
</script>

<style lang="scss" scoped>
.avatar-uploader-icon {
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
 .avatar {
  
  position: relative;
    width: 148px;
    height: 148px;
    display: block;
  }
  .avatar:hover .deleteImg {
    display: block;
}
.deleteImg {
  display: none;
  font-size: 30px;
  width: 148px;
  height: 148px;
  background-color:black;
	opacity: 0.6; 
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  margin: auto;
  z-index: 999;
}
.deleteImg span i{
  margin-left: 10px;
  color: #fff;
}
.deleteImg span{
  display: flex;
  align-items:center;/*垂直居中*/
  justify-content: center;/*水平居中*/
  width:100%;
  height:100%;
}
</style>