<template>
  <div style="height: 100%;background-color: white;padding: 10px;">
    <div style="display: flex;margin-bottom: 20px;">
      <el-input v-model="queryParams.productCategoryName" size="small" placeholder="请输入产品类别名称" style="width: 300px;margin-right: 10px;"></el-input>
      <el-input v-model="queryParams.createPersonName" size="small" placeholder="请输入创建人名称" style="width: 300px;margin-right: 10px;"></el-input>
      <el-button type="primary" size="small" @click="getList2">查询</el-button>
      <el-button type="primary" size="small" @click="handleAdd">新增类别</el-button>
    </div>
    <!-- 表格 -->
    <el-table
      :data="tableData"
      border
      header-row-class-name="custom-table-header"
      @sort-change="sortChange"
      style="width: 100%;margin-bottom: 10px;"
      row-key="id"
      :expand-row-keys="expands"
      @expand-change="expandBtn"
      >
      <!-- <el-table-column type="index" label="#" width="55" align="center">
        <template slot-scope="scope">
           <span>{{ (scope.$index + 1) + ((queryParams.current - 1) * queryParams.size) }}</span>
        </template>
      </el-table-column> -->
      <!-- type="expand"开启后展开行 -->
      <el-table-column type="expand" align="center"> 
        <template slot-scope="scope">

          <div>
            <products :categoryRow="scope.row" :patentNo="patentNo" v-bind="$attrs" v-on="$listeners"></products>
          </div>
          
        </template>
      </el-table-column>
      <el-table-column prop="productCategoryName" label="产品类别名称"   sortable="custom" align="center"> </el-table-column>
      <el-table-column prop="licenseRate" label="参考许可费率" sortable="custom" align="center" width="180"> </el-table-column>
      <el-table-column prop="createPersonName" label="创建人" sortable="custom" align="center"> </el-table-column>
      <!-- <el-table-column prop="pictures" label="图片" align="center"> 
        <template slot-scope="scope">
          <span v-for="url in scope.row.pictures">
            <img :src="$p + url.url" alt="" max-width="100"  max-height="100">
          </span>
        </template>
      </el-table-column> -->
      <el-table-column prop="remark" 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" trigger="click"  @command="handleCommand($event,scope.row)" @click="handleEdit(scope.row)">
            <p>编辑</p> 
            <el-dropdown-menu slot="dropdown" style="text-align: center;">
              <el-dropdown-item command="4">预览图片</el-dropdown-item>
              <el-dropdown-item command="1">趋势图</el-dropdown-item>
              <el-dropdown-item command="2">可视化</el-dropdown-item>
              <el-dropdown-item :divided="true" command="3" >
                <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>
    
    <!-- 新增、编辑弹窗 :close-on-click-modal="false"点击遮罩层阻止弹窗关闭 -->
    <el-dialog
      :title="title"
      :visible.sync="visible"
      width="500"
      :close-on-click-modal="false"
      :before-close="close">

      <el-form :rules="rules" ref="categoryForm" :model="categoryForm" label-width="80px">
        <el-form-item label="名称 " prop="productCategoryName">
          <el-input v-model="categoryForm.productCategoryName" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="参考许可费率 " prop="licenseRate">
          <el-input v-model="categoryForm.licenseRate" placeholder="请输入参考许可费率(参考许可费率介于0-1之间)"></el-input>
          <!-- <el-input-number v-model="categoryForm.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="categoryForm.url"></el-input> -->
          <el-upload ref="upload"  action="#" :auto-upload="false"  :on-change="handleChange"  list-type="picture" :show-file-list="false">
            <span v-if="categoryForm.pictures&&categoryForm.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>
              <!-- upload展示，preview-src-list大图展示 -->
                <el-image ref="image" style="width:100%;height: 100%;" :src="categoryForm.pictures[0].id?$p + categoryForm.pictures[0].url:categoryForm.pictures[0].url" :preview-src-list="categoryForm.pictures?categoryForm.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="categoryForm.remark" 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>
  </div>
</template>

<script>
import products from '@/views/product/components/products.vue'
import { commonMethods } from './mixins'
export default {
  components: {
    products
  },
  mixins:[commonMethods],
  props:['patentNo'],
  data() {
    const licenseRateRule = (rule , value ,callback)=>{
      if(value){
         if (!isNaN(value)) {
          if (value>=0 && value<=1) {
            this.categoryForm.licenseRateA=value
            this.categoryForm.licenseRate=this.categoryForm.licenseRateA
            callback()
          } else {
            // if (value>1) {
            //   this.categoryForm.licenseRate=1
            // } else {
            //   this.categoryForm.licenseRate=0
            // }
            callback(new Error('输入错误，参考许可费率介于0-1之间'))
          }
        } else {
          // this.categoryForm.licenseRate=this.categoryForm.licenseRateA
          callback(new Error('输入错误，参考许可费率介于0-1之间'))
        }
      }else{
        callback()
      }
    }
    return {
      input: '',
      left:'left',
      tableData: [],
      categoryForm:{},
      visible: false,
      title: null,
      queryParams: {
        orderBy:'',//排序名称
        orderType:'',//排序类型
        size: 10,
        current:1,
      },
      total:0,
      file:[],
      expands:[],
      rules: {
        productCategoryName:[{ required: true, message: '请输入名称', trigger: 'blur' },],
        licenseRate:[{ required: false, validator:licenseRateRule, trigger: 'blur' },],
      },
    }
  },
  // computed: {
  //   userinfo() {
  //     return this.$store.state.user.userinfo
  //   }
  // },
  mounted() { 
    this.getList()
   
    // console.log(this.userinfo.tenantName);
  },
  methods: {
    //查询
    getList() { 
      this.queryParams.patentNo = this.patentNo?this.patentNo[0]:null
      this.$api.queryProductCategorys(this.queryParams).then(res => {
        if (res.code==200) {
          this.tableData = res.data.list
          this.total = res.data.totalSizes
          if (this.expands.length==0) {
            this.expands.push(this.tableData[0].id)
          }
        }
      })
    },
    getList2() {
      this.queryParams.current=1
      this.getList()
    },
    // 展开table当前行
    expandBtn(row) {
      if (row) {
        this.expands=[row.id]
      } 
    },
    // 排序
    sortChange(row) {
      // console.log(row);
    },
    // 新增
    handleAdd() { 
      this.title = '新增类别'
      this.visible=true
    },
    // 编辑
    handleEdit(row) { 
      this.title = '编辑类别'
      this.categoryForm = JSON.parse(JSON.stringify(row))
      this.visible=true
    },
    // 编辑右侧菜单项
    handleCommand(ev, row) { 
     
      switch (ev) {
        case '1':
          this.showTrend(row,1)
          // 趋势图
          break;
        case '2':
          this.getMind(row,1)
          // 可视化
          break;
        case '3':
          this.$confirm('此操作将永久删除该类别, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            // console.log(ev, row);
            this.$api.deleteProductCategorys({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 '4':// 图片预览
          if (row.pictures && row.pictures.length>0) {
            var item = row.pictures[0]
              var FileUrl = this.$p + row.pictures[0].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;
      }
    },
    // 弹窗确定
    sure() {
      this.$refs.categoryForm.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.categoryForm))
          // console.log(formData);
          if (this.categoryForm.id) {
            this.$api.updateProductCategorys(formData).then(res => {
              if (res.code == 200) {
                this.$message.success("编辑产品类别成功")
                this.getList()
                this.close()
              }
            })
          } else {
             this.$api.addNewProductCategorys(formData).then(res => {
              if (res.code == 200) {
                this.$message.success("新增产品类别成功")
                this.getList()
                this.close()
              }
            })
          }
         
        }
      })
      
      
    },
    // 弹窗关闭
    close() {
      this.visible = false
      this.$refs.upload.clearFiles()
      this.categoryForm = {}
      this.file=[]
    },
    // 分页
    handleCurrentChange(val) {
      this.queryParams.current = val
      this.getList()
    },
    // licenseRateChange(val) {
    //   if (val) {
    //      if (!isNaN(val)) {
    //       if (val>=0 && val<=1) {
    //         this.categoryForm.licenseRateA=val
    //         this.categoryForm.licenseRate=this.categoryForm.licenseRateA
    //       } else {
    //         if (val>1) {
    //           this.categoryForm.licenseRate=1
    //         } else {
    //           this.categoryForm.licenseRate=0
    //         }
    //       }
    //     } else {
    //       this.categoryForm.licenseRate=this.categoryForm.licenseRateA
    //     }
    //   }
    // },
    // 上传图片//showViewer显示查看器
    handlePictureCardPreview(file) {
        this.$refs.image.showViewer = true
    },
    handleRemove() {
      this.file = []
      this.categoryForm.pictures = []//直接清空适用于单张图片
    },
    handleChange(file, fileList) {
      // console.log(file, fileList);
      this.$set(this.categoryForm,'pictures', [{url:file.url}])
      // this.categoryForm.pictures = [file.url]
      // this.file.push(file.raw)
      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>