<template>
  <div class="app-container">
    <el-row :gutter="24">
      <el-col :span="4">
        <el-card style="height: 100%; min-height: 100vh;">
        <div style="marginTop:20px;margin-left: 10px;">
         <el-tree
           :data="productNameList"
           v-model="table.getdataListParm.parammaps.categoryId"
           :props="defaultProps"
           @node-click="handleNodeClick"
           style="font-size: 26px;" 
            :disabled="false"
         ></el-tree>
       </div>
      </el-card>
      </el-col>
      <el-col :span="20">
    <div class="operation">
      <el-button v-if="isRoleEdit" class="success" style="float: left;margin-right:10px;" @click="form_add">添加</el-button>

      <!-- <el-button v-if="isRoleEdit" class="import" style="float: right;" @click="form_inport">导入</el-button>
      <el-dropdown style="float: right;margin-right: 10px;">
        <el-button class="export">导出</el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="form_export(1)">导出模板</el-dropdown-item>
          <el-dropdown-item @click.native="form_export(2)">导出数据</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown> -->
    </div>

    <div class="search">
      <!-- <el-select v-model="table.getdataListParm.parammaps.categoryId" placeholder="产品类别" class="filter-item" style="width: 120px;" clearable>
        <el-option v-for="(item,index) in productNameList" :key="index" :label="item.name" :value="item.id" />
      </el-select> -->
      <tree-select
            v-model="table.getdataListParm.parammaps.categoryId"
            class="typeSelect"
            :height="300"
            :width="250"
            clearable
            :data="productNameList"
            :placeholder="placeholder"
            style="display: inline-block"
            :default-props="defaultProps"
            :node-key="nodeKey"
            :checked-keys="defaultCheckedKeysSelect"
            @popoverHide="popoverHideSelect"
            :disabled="false"
          />


      <el-input v-model="table.getdataListParm.parammaps.pname" placeholder="产品名称" style="width: 180px;" class="filter-item" clearable />
      <el-input v-model="table.getdataListParm.parammaps.pcode" placeholder="产品编码" style="width: 180px;" class="filter-item" clearable />
      <el-input v-model="table.getdataListParm.parammaps.model" placeholder="产品型号" style="width: 180px;" class="filter-item" clearable />
      <el-input v-model="table.getdataListParm.parammaps.Specifications" placeholder="产品规格" style="width: 180px;" class="filter-item" clearable />

      <el-button class="successBorder" @click="form_search">查询</el-button>
      <el-button class="successBorder" @click="form_clear">重置</el-button>
    </div>

    <div class="table">
      <el-table :key="table.tableKey" v-loading="table.listLoading" element-loading-text="给我一点时间" :data="table.list" border fit highlight-current-row style="width: 100%;" :row-style="rowStyle" :cell-style="cellStyle" class="elTable table-fixed">
        <!-- <el-table-column type="selection" align="center" width="50" /> -->
        <el-table-column label="序号" align="center" type="index" width="50px">
          <template slot-scope="scope">
            <span>{{ scope.$index + (table.pageNum-1) * table.pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品类别" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.cname }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品编码" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.pcode }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品名称" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.pname }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品型号" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.model }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品规格" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.Specifications }}</span>
          </template>
        </el-table-column>

        <el-table-column label="产品图片" min-width="150px" align="center">
            <template slot-scope="scope">
              <el-popover placement="right" title="" trigger="hover">
                <img
                       slot="reference"
                       :src="scope.row.imagePath"
                       style="height: 100px; width: 100px"
                     />
                     <!-- 悬停时显示的内容 -->
                     <img
                       :src="scope.row.imagePath"
                       style="height: 200px; width: 200px"
                     />
              </el-popover>
            </template>
          </el-table-column>

        <el-table-column label="备注" min-width="150px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.remark }}</span>
          </template>
        </el-table-column>
        <el-table-column label="顺序" width="100px" header-align="center" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.sort }}</span>
          </template>
        </el-table-column>
        <el-table-column label="启用" min-width="80px" header-align="center" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.enable" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" @change="change_enable(scope.$index, scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <!-- <el-button v-if="isRoleEdit" class="miniSuccess" @click="form_edit(row)">编辑</el-button>
            <el-button v-if="isRoleEdit" class="miniDanger" @click="form_delete(row)">删除</el-button> -->

            <el-button class="miniSuccess" @click="form_edit(row)">编辑</el-button>
            <el-button class="miniDanger" @click="form_delete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="table.total>=0" :total="table.total" :page.sync="table.getdataListParm.offset" :limit.sync="table.getdataListParm.pagecount" @pagination="get_table_data" />
    </div>

    <!-- 新增/编辑 -->
    <el-dialog :title="textMap[create.dialogStatus]" :visible.sync="create.dialogFormVisible" :close-on-click-modal="false" width="40%">
      <div class="app-add">
        <el-form ref="temp" :rules="create.rules" :model="create.temp" label-position="right" label-width="150px" style="width: 80%;margin:0 auto 50px">

          <el-form-item label="产品类别：" style="width: 400px;" class="filter-item" prop="categoryId">
            <tree-select
                class="typeSelect"
                :height="300"
                :width="250"
                size="small"
                clearable
                :data="productNameList"
                :placeholder="placeholder"
                style="display:inline-block;"
                :default-props="defaultProps"
                :node-key="nodeKey"
                :checked-keys="defaultCheckedKeys"
                @popoverHide="popoverHide"
                :disabled="disabled"
              />
          </el-form-item>


          <el-form-item label="产品编码：" prop="pcode">
            <el-input ref="pname" v-model="create.temp.pcode" class="filter-item" style="width: 100%;" />
          </el-form-item>

          <el-form-item label="产品名称：" prop="pname">
            <el-input ref="pname" v-model="create.temp.pname" class="filter-item" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="产品型号：" prop="model">
            <el-input ref="model" v-model="create.temp.model" class="filter-item" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="产品规格：" prop="Specifications">
            <el-input ref="Specifications" v-model="create.temp.Specifications" class="filter-item" style="width: 100%;" />
          </el-form-item>

          <el-form-item label="备注：" prop="remark">
            <el-input ref="remark"  class="filter-item" v-model="create.temp.remark" />
          </el-form-item>

          <el-form-item label="顺序：" prop="sort">
            <el-input ref="sort"  class="filter-item" v-model="create.temp.sort" />
          </el-form-item>
          <el-form-item label="启用：" prop="enable">
            <el-switch ref="enable"   class="filter-item" v-model="create.temp.enable" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" />
          </el-form-item>


          <el-form-item label="产品图片:">
            <el-upload  id="uploadPic"
          :action="uploadImageUrl"
         :limit='1'
         :file-list="fileList"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-change="(file, fileList) => handlePicChange(file, fileList)"
          :on-success="(response, file, fileList) => handlePicSuccess(response, file, fileList)"
          :headers="headers"
               :disabled="isView"
          :on-remove="(file, fileList) => handlePicRemove(file, fileList)"
        >
          <i slot="default" class="el-icon-plus"></i>
        </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
        </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="cancelClose" @click="create.dialogFormVisible = false;defaultCheckedKeys = [];this.dialogImageUrl  = '';get_table_data()">关闭</el-button>
          <el-button v-if="create.dialogStatus==='create' || create.dialogStatus==='update'" class="success" @click="create.dialogStatus==='create'?add_dialog_save():form_edit_save();this.dialogImageUrl  = '';">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </el-col>
  </el-row>
  </div>
</template>

<script>
import { GetDataByName, PostDataByName, failproccess, ExecDataByConfig, GetDataByNames, checkButtons, calculativeWidth,transData } from '@/api/common'
import { isIntegerZero } from '@/utils/validate'
import Cookies from 'js-cookie' 
import TreeSelect from '@/components/TreeSelect'; 
import { parseTime } from '@/utils/index.js'
import Pagination from '@/components/Pagination'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'

export default {
  name: 'ProductList',
  components: { Pagination,TreeSelect },
  data() {
    return {
      handlePictureCardPreview(file) {
              this.dialogImageUrl = file.url;
              this.dialogVisible = true;
      },

      dialogImageUrl: '',
                 dialogVisible: false,
                 uploadImageUrl: process.env.VUE_APP_BASE_API + 'authdata/uploaderimage',
                 //图片请求头
 headers: { optname: 'insertcustompic', id: 1,token: getToken()},
      isRoleEdit: [],
      productNameList: [], // 产品类别下拉框
      placeholder: '请选择上级分类',
      defaultProps: {
        children: 'children',
        label: 'name', // 根据实际字段名调整
      },
      disabled: false, // 是否禁用
      nodeKey: 'id', // 节点的唯一标识字段
      defaultCheckedKeys: [],
      defaultCheckedKeysSelect :[],
      fileList: [],
      //表格请求参数~
      table: {
        getdataListParm: {
          name: 'getProducts',
          page: 1,
          offset: 1,
          pagecount: parseInt(Cookies.get('pagecount')),
          returntype: 'Map',
          parammaps: {
            categoryId: '',
            pname: '',
            model: '',
            Specifications: '',
            pcode:'',
          }
        },
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true,
        temp: {}
      },

      // 新增/编辑
      create: {
        dialogFormVisible: false,
        dialogStatus: '',
        temp: {
          categoryId: '',
          pname: '',
          model: '',
          Specifications: '',
          remark: '',
          sort: '',
          enable: 1,
          pcode:'',
          pImage:'',
        },
        rules: {
          pname: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }],
          model: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }],
          Specifications: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }],
          sort: [{ validator: isIntegerZero, trigger: 'blur' }],
          pcode: [{ type: 'string', required: true, message: '必填', trigger: 'blur' }]
        },
      },
      textMap: {
        create: '添加',
        update: '编辑'
      },

      requestParam: {},

      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' }
    }
  },
  computed: {
      // 设置请求头
      headers() {
        return {
          // 设置token
          token: getToken()
        }
      }
    },
  created() {
    this.get_table_data()

    this.get_select_list()

    // this.get_auto_buttons()
  },

  methods: {
    handlePicChange(file, fileList) {

},
    handlePicRemove(file, fileList) {
              console.log(file, fileList);
                console.log(fileList.length);
              if (fileList.length == 1) {
                document.getElementById('uploadPic').lastChild.style.display = "none"
              } else {
                document.getElementById('uploadPic').lastChild.style.display = "inline-block"
      }
    },
    handlePicSuccess(response, file, fileList) {
                  
      if (fileList.length == 1) {
        document.getElementById('uploadPic').lastChild.style.display = "none"
      } else {
        document.getElementById('uploadPic').lastChild.style.display = "inline-block"
      }
      this.$set(this.create.temp, 'pImage', response.execresult.LastInsertId);
    },
    andlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    
    popoverHideSelect(checkedIds, checkedData) {
      if (checkedIds !== null) {
        this.table.getdataListParm.parammaps.categoryId = checkedData.id;
      } else {
        this.table.getdataListParm.parammaps.categoryId ='';
      }
    },

    handleNodeClick(data, node) {
       this.table.getdataListParm.parammaps.categoryId = data.id;
       this.get_table_data_left();
      },

    popoverHide(checkedIds, checkedData) {
      console.log(checkedIds, checkedData);
      if (checkedData == null) {
        this.$set(this.create.temp, 'pcode', ''); 
        this.create.temp.categoryId = '';
      }else{
        this.$set(this.create.temp, 'pcode', checkedData.code); 
      this.create.temp.categoryId = checkedData.id;
      }
    },

    //获取按钮权限
    get_auto_buttons() {
      const Edit = 'DungScores'
      const isRoleEdit = checkButtons(JSON.parse(sessionStorage.getItem('buttons')), Edit)
      this.isRoleEdit = isRoleEdit
    },

    //获取所有下拉框的内容
    get_select_list() {
      GetDataByName({ name: 'getCategorySelect', offset: 0, pagecount: 0, parammaps: {} }, ).then(response => {
        this.productNameList = response.data.list
        this.productNameList= transData(response.data.list, 'id', 'pid', 'children');
        console.log("产品类别下拉框", response);
      })
    },


    //加载表格
    get_table_data() {
      this.table.listLoading = true
      console.log("this.table.getdataListParm======>", this.table.getdataListParm)
      GetDataByName(this.table.getdataListParm).then(response => {
        console.log('table数据======>', response.data.list)
        if (response.data.list !== null) {
          for (var i = 0; i < response.data.list.length; i++) {
            response.data.list[i].enable = parseInt(response.data.list[i].enable)
            if ( response.data.list[i].pImage !== '') {
              response.data.list[i].imagePath = process.env.VUE_APP_BASE_API + response.data.list[i].imagePath;
              } else {
                response.data.list[i].imagePath = ''
              }
          }

          this.table.list = response.data.list
          this.table.pageNum = response.data.pageNum
          this.table.pageSize = response.data.pageSize
          this.table.total = response.data.total
        } else {
          this.table.list = []
        }
        setTimeout(() => {
          this.table.listLoading = false
        }, 100)
      })
    },
    get_table_data_left() {
      this.table.listLoading = true
      console.log("this.table.getdataListParm======>", this.table.getdataListParm)
      GetDataByName(this.table.getdataListParm).then(response => {
        console.log('table数据======>', response.data.list)
        if (response.data.list !== null) {
          for (var i = 0; i < response.data.list.length; i++) {
            response.data.list[i].enable = parseInt(response.data.list[i].enable)
          }

          this.table.list = response.data.list
          this.table.pageNum = response.data.pageNum
          this.table.pageSize = response.data.pageSize
          this.table.total = response.data.total
        } else {
          this.table.list = []
        }
        this.table.getdataListParm.parammaps.categoryId  = '';
        setTimeout(() => {
          this.table.listLoading = false
        }, 100)
      })
    },
    form_search() {
      console.log('点击了查询')

      this.table.getdataListParm.offset = 1
      this.get_table_data()
    },
    form_clear() {
      console.log('点击了重置')

      this.table.getdataListParm.parammaps.categoryId = ''
      this.table.getdataListParm.parammaps.pname = ''
      this.table.getdataListParm.parammaps.model = ''
      this.table.getdataListParm.parammaps.Specifications = ''
      this.table.getdataListParm.offset = 1
      this.get_table_data()
    },

    // 添加
    form_reset() {
      this.create.temp = { categoryId: '', pname: '', model: '', Specifications: '', remark: '', sort: '', enable: 1 }
    },

    //监听 - 表格中产品类别
    change_bar(item) {
      this.create.temp.cname = this.productNameList.find(obj => obj.id === item).name
    },

    //添加
    form_add() {
      console.log('点击了新增')
      this.form_reset()
      // this.dialogImageUrl = row.imagePath;
      this.create.dialogStatus = 'create'
      this.create.dialogFormVisible = true
      this.fileList = [];
      // if (row.imagePath !== ''){
      //   const fileList = [];
      //   var urlObj = { "url": "", "response": { "execresult": { "LastInsertId": "" } } };
      //   urlObj.url = row.imagePath;
      //   urlObj.response.execresult.LastInsertId = row.pImage;
      //   fileList.push(urlObj);
      //   this.fileList = fileList;
      // }
      
    },
    //添加保存
    add_dialog_save() {
      console.log('点击了新增保存')
      this.$refs['temp'].validate(valid => {
        if (valid) {

          //新增保存
          this.requestParam.name = 'insertProducts'
          this.requestParam.parammaps = this.create.temp

          this.requestParam = {
            data: [
              {
                name: "CheckProductPCode",
                type: "v",
                parammaps :{
                  pcode :this.create.temp.pcode,
                  id :''
                }
              },
              {
                name: "insertProducts",
                type: "e",
                parammaps: this.create.temp,
              },
            ]
          }
          
          ExecDataByConfig(this.requestParam).then(response => {
            console.log('新增保存发送参数', this.requestParam)
            if (response.msg !== 'fail') {
              this.defaultCheckedKeys = [];
              this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
              this.create.dialogFormVisible = false
              this.get_table_data()
            } else {
              this.$notify({ title: '失败', message: response.data, type: 'error', duration: 2000 })
            }
          })
        }
      })
    },


    // 编辑
    form_edit(row) {
      console.log('点击了编辑', row)
      row.categoryId = String(row.categoryId)
      // this.dialogImageUrl = row.imagePath;
      this.create.temp = Object.assign({}, row)
      this.create.temp.id = row.id
      this.create.dialogStatus = 'update'
      this.create.dialogFormVisible = true
      // this.create.pcode = row.pcode;
      this.defaultCheckedKeys =[row.categoryId] ;
      console.log(row.imagePath);
      if (row.pImage !== ''){
        const fileList = [];
        var urlObj = { "url": "", "response": { "execresult": { "LastInsertId": "" } } };
        urlObj.url = row.imagePath;
        urlObj.response.execresult.LastInsertId = row.pImage;
        fileList.push(urlObj);
        this.fileList = fileList;
      }else{
        this.fileList  = [];
        this.dialogImageUrl = '';
      }
    },

    // 编辑保存
    form_edit_save() {
      this.$refs['temp'].validate(valid => {
        if (valid) {
          // this.requestParam.name = 'updateProducts'
          // this.requestParam.parammaps = this.create.temp

          this.requestParam = {
            data: [
              {
                name: "CheckProductPCode",
                type: "v",
                parammaps :{
                  pcode :this.create.temp.pcode,
                  id : this.create.temp.id
                }
              },
              {
                name: "updateProducts",
                type: "e",
                parammaps: this.create.temp,
              },
            ]
          }
          ExecDataByConfig(this.requestParam).then(response => {
            console.log('编辑保存发送参数', this.requestParam)
            if (response.msg !== 'fail') {
              this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
              this.create.dialogFormVisible = false
              this.defaultCheckedKeys = [];
              this.get_table_data()
            } else {
              this.$notify({ title: '失败', message: '保存失败', type: 'error', duration: 2000 })
            }
          })
        }
      })
    },

    // 表格中的启用
    change_enable(index, row) {
      this.requestParam.name = 'updateProducts'
      this.requestParam.parammaps = {
        id: row.id,
        categoryId: row.categoryId,
        pname: row.pname,
        model: row.model,
        Specifications: row.Specifications,
        cname: row.cname,
        remark: row.remark,
        sort: row.sort,
        enable: row.enable
      }


      PostDataByName(this.requestParam).then(response => {
        console.log('表格中的启用发送参数', this.requestParam)
        if (response.msg !== 'fail') {
          this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
          this.create.dialogFormVisible = false
          this.get_table_data()
        } else {
          this.$notify({ title: '失败', message: '保存失败', type: 'error', duration: 2000 })
        }
      })


    },

    // 删除
    form_delete(row) {
      MessageBox.confirm('是否确认删除此信息?', {
        confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        this.requestParam.name = 'delProducts'
        this.requestParam.parammaps = {}
        this.requestParam.parammaps.id = row.id
        PostDataByName(this.requestParam).then(response => {
          if (response.msg === 'fail') {
            this.$notify({ title: '删除失败', message: response.data, type: 'warning', duration: 2000 })
          } else {
            this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
            this.get_table_data()
          }
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      })
    },


    // 导出
    form_export(item) {
      if (item == 1) {
        console.log('点击了导出模板')
      } else {
        console.log('点击了导出数据')
      }
    },

    // 导入
    form_inport() {
      console.log('点击了导入')
    }

  }
}
</script>
<style lang="scss" scoped>
.search {
  padding-top: 10px;
  clear: both;
}
.table {
  margin-top: 10px;
}
</style>

<style lang="scss" scoped>
.custom-tree {
  font-size: 26px; /* 设置字体大小 */
}
</style> 