<template>
  <div>
    <!-- 左侧树形结构和右侧表格 -->
    <el-row :gutter="20">
      <!-- 左侧树形结构 -->
      <el-col :span="3">
       <div style="marginTop:20px;margin-left: 10px;">
         <el-tree
           :data="goodsTypeData"
           v-model="getGoodsListParm.parammaps.goodsTypeId"
           :props="defaultProps"
           @node-click="handleNodeClick"
            :disabled="false"
         ></el-tree>
       </div>
      </el-col>

      <!-- 右侧表格和表单 -->
      <el-col :span="21">
        <!-- 搜索条件 -->
        <div class="app-container">
          <tree-select
            v-model="getGoodsListParm.parammaps.goodsTypeId"
            class="typeSelect"
            :height="300"
            :width="250"
            clearable
            :data="goodsTypeData1"
            :placeholder="placeholder"
            style="display: inline-block"
            :default-props="defaultProps"
            :node-key="nodeKey"
            :checked-keys="defaultCheckedKeys"
            @popoverHide="popoverHide"
            :disabled="false"
          />
          <el-input
            v-model="getGoodsListParm.parammaps.goodsName"
            placeholder="货品名称"
            clearable
            style="width: 120px"
            class="filter-item"
          />
          <el-input
            v-model="getGoodsListParm.parammaps.goodsCode"
            placeholder="货品编码"
            clearable
            style="width: 120px"
            class="filter-item"
          />
          <el-input
            v-model="getGoodsListParm.parammaps.goodsSpecification"
            placeholder="货品规格"
            clearable
            style="width: 120px"
            class="filter-item"
          />
          <el-select
            v-model="getGoodsListParm.parammaps.goodsEnabled"
            clearable
            placeholder="货品状态"
            class="filter-item"
            style="width: 120px"
          >
            <el-option
              v-for="item in statuesList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-date-picker
            ref="inputDatetime2"
            v-model="getGoodsListParm.parammaps.inputDatetime2"
            class="inputDatetime"
            type="daterange"
            style="width: 250px; top: -3px"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
          <el-button
            v-waves
            class="search-button"
            type="primary"
            icon="el-icon-search"
            @click="form_search"
          >搜索</el-button>
        </div>

        <!-- 操作按钮 -->
        <div  class="search-button-container">
          <el-button
            class="search-button"
            type="primary"
            icon="el-icon-circle-plus"
            @click="form_add"
          >新增</el-button>
          <el-button
            class="search-button"
            type="primary"
            style="background-color: #aaaaaa;"
            icon="el-icon-s-order"
            @click="template_excel"
          >模板</el-button>

        <el-upload
           style="display: inline-block"
           :headers="headers"
           :data="uploadData"
           :action="uploadExcelUrl"
           :show-file-list="false"
           :before-upload="beforeImportExcel"
           :on-success="handleImportExcelSuccess"
         >
           <el-button
             v-waves
              class="search-button-upload"
               type="primary"
                style="background-color: #ffaa00;"
             icon="el-icon-upload2"
           >导入</el-button>
         </el-upload>

          <el-button
            class="search-button"
            type="primary"
            style="background-color: #00ff15;"
            icon="el-icon-upload2"
            @click="derive_data"
          >导出</el-button>
        </div>

        <!-- 表格 -->
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          element-loading-text="给我一点时间"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%;margin-left: 20px;"
          :row-style="rowStyle"
          :cell-style="cellStyle"
          class="elTable  table-fixed"
          :max-height="myHeight"
        >
          <el-table-column label="序号" align="center" type="index" width="50px">
            <template slot-scope="scope">
              <span>{{ scope.$index + (pageNum - 1) * pageSize + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="货品类别" align="center" prop="goodsTypeName" />
              <el-table-column label="货品名称" align="center" prop="goodsName" />
          <el-table-column label="货品编号" align="center" prop="goodsCode" />
          <el-table-column label="货品规格" align="center" prop="goodsSpecification" />
          <el-table-column label="计量单位" align="center" prop="goodsUnit" />
          <el-table-column label="录入日期" align="center" prop="createTime" />
          <el-table-column label="录入人" align="center" prop="createrName" />
          <el-table-column label="货品图片" align="center">
            <template slot-scope="scope">
              <el-popover placement="right" title="" trigger="hover">
                <img
                       slot="reference"
                       :src="scope.row.goodsImagePath"
                       style="height: 100px; width: 100px"
                     />
                     <!-- 悬停时显示的内容 -->
                     <img
                       :src="scope.row.goodsImagePath"
                       style="height: 200px; width: 200px"
                     />
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="货品状态" align="center">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.goodsEnabled"
                :active-value="0"
                :inactive-value="1"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="handleSwitchChange(scope.$index, scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="150px" header-align="center" align="center">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="handleGet(scope.row)">查看</el-button>
              <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="primary" size="mini" @click="handleDel(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
          v-show="total >= 0"
          :total="total"
          :page.sync="getGoodsListParm.offset"
          :limit.sync="getGoodsListParm.pagecount"
          @pagination="get_goods_data"
        />

      </el-col>
    </el-row>


    <!-- 弹窗 -->
<el-dialog
    :title="dialogTitle"
    :visible.sync="dialogFormVisible"
    :close-on-click-modal="false"
     @close="handleCancel"
    :style="{ maxHeight: '100vh', overflowY: 'auto' }"
  >

 <div class="app-add">
 <el-form
          :rules="rules"
          :inline="true"
          :model="formLabelAlign"
          label-position="left"
          label-width="auto"
          style="width: 90%; margin: 0 auto 30px"
        >
      <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="货品类别:" prop="typea">
              <tree-select
                class="typeSelect"
                :height="300"
                :width="160"
                size="small"
                clearable
                :data="goodsTypeData"
                :placeholder="placeholder"
                :default-props="defaultProps"
                :node-key="nodeKey"
                :checked-keys="defaultCheckedKeys"
                @popoverHide="popoverHideAdd"
                :disabled="isView"
              />
            </el-form-item>
          </el-col>
        <el-col :span="8">
          <el-form-item label="货品编号:" prop="goodsCode">
            <el-input
              v-model="formLabelAlign.goodsCode"
              placeholder="请输入货品编号"
               :disabled="isView || !formLabelAlign.goodsTypeId"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="货品名称:" prop="goodsName">
            <el-input
              v-model="formLabelAlign.goodsName"
              placeholder="请输入货品名称"
               :disabled="isView"
            />
          </el-form-item>
        </el-col>

      </el-row>

      <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="货品规格:" >
              <el-input
                v-model="formLabelAlign.goodsSpecification"
                placeholder="请输入货品规格"
               :disabled="isView"
              />
            </el-form-item>
          </el-col>

<el-col :span="8">
            <el-form-item label="货品型号:" >
              <el-input
                v-model="formLabelAlign.goodsModel"
                placeholder="请输入货品型号"
               :disabled="isView"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计量单位:">
              <el-select v-model="formLabelAlign.goodsUnit" placeholder="请选择" :disabled="isView" clearable style="width: 187px">
              <el-option
                   v-for="item in measureList"
                   :key="item.id"
                   :label="item.name"
                   :value="item.id">
                 </el-option>
               </el-select>
            </el-form-item>
          </el-col>

      </el-row>

 <el-row :gutter="24">


   <el-col :span="8">
     <el-form-item label="用途:">
       <el-input
         v-model="formLabelAlign.purpose"
         placeholder="请输入用途"
        :disabled="isView"
       />
     </el-form-item>
   </el-col>
          <el-col :span="8">
            <el-form-item label=" 录入人:">
              <el-select v-model="formLabelAlign.createrId" placeholder="请选择" :disabled="isView" clearable style="width: 187px">
              <el-option
                   v-for="item in empList"
                   :key="item.id"
                   :label="item.name"
                   :value="item.id">
                 </el-option>
               </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="录入日期:">
            <el-date-picker
                  style="width: 187px"
                  v-model="formLabelAlign.date"
                  type="date"
                  format="yyyy-MM-dd"
               :disabled="isView"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期">
                </el-date-picker>
            </el-form-item>
          </el-col>


      </el-row>

       <el-row :gutter="24">
         <el-col :span="8">
                  <el-form-item label="备注:">
                    <el-input
                      v-model="formLabelAlign.remarks"
                      placeholder="请输入备注"
                     :disabled="isView"
                    />
                  </el-form-item>
                </el-col>

      </el-row>
<!-- <div> -->
      <el-row :gutter="24">
          <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-item>
                 </el-col>
                 </el-row>

      <el-table
        :key="tableKey"
        v-loading="listLoading"
        element-loading-text="给我一点时间"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;margin-left: 20px;"
        :row-style="rowStyle"
        :cell-style="cellStyle"
        class="elTable  table-fixed"
        :max-height="myHeight"
      >
      <el-table-column
        label="序号"
        align="center"
        type="index"
        width="50px"
      />


      </el-table>

    <!-- </div> -->
    </el-form>
    </div>

  <div  slot="footer" class="dialog-footer">
        <el-button class="add-button" v-if="!isEdit && isShow"  style="background-color: #13ce66;" @click="handleAdd">保存并新增</el-button>
        <el-button class="add-button"  v-if="!isEdit && isShow"   @click="handleAddAndOff">保存并关闭</el-button>
        <el-button class="add-button"   v-if="!isEdit && isShow"  style="background-color: #ffffff; color: black;"  @click="handleCancel">取消并关闭</el-button>

        <el-button class="add-button" v-if="isEdit"   @click="handleEditAndOff">保存并关闭</el-button>
        <el-button class="add-button"  v-if="isEdit"  style="background-color: #ffffff; color: black;"  @click="handleCancel">取消并关闭</el-button>
  </div>
  </el-dialog>
  </div>
</template>

<!-- <el-form ref="form" label-position="top" :rules="rules" label-width="80px" :model="formLabelAlign">
    <el-form-item label="资产编号" prop="assetCode" style="display: flex; align-items: center;">
      <el-input v-model="formLabelAlign.assetCode"></el-input>
    </el-form-item>
  </el-form> -->

<script>
  import { PostDataByName, ExecDataByConfig, failproccess, GetDataByName, transData } from '@/api/common';
  import TreeSelect from '@/components/TreeSelect'; // 确保路径正确
  import Pagination from '@/components/Pagination'
  import waves from '@/directive/waves'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
  import 'element-ui/lib/theme-chalk/index.css';
  import Cookies from 'js-cookie'

  export default {
  inject: ['reload'],
  name: 'Basics',
  components: { Pagination, TreeSelect },
  directives: { waves },
    data() {
      return {
            rules: { goodsCode: [
        { required: true, message: '货品编码不能为空', trigger: 'blur' },
      ],

      uploadData: {
        name: 'importDiesel',
        importParams: '牧场,油卡编号,设备名称,设备编号,加油日期,加油量(升),单价,加油人,录入人,柴油类型,备注',
        sheetname: 'SheetJS'
      },
      goodsName: [
        { required: true, message: '货品名称不能为空', trigger: 'blur' },
      ],
      goodsSpecification: [
        { required: true, message: '货品规格不能为空', trigger: 'blur' },
      ],
      goodsUnit: [
        { required: true, message: '货品单位不能为空', trigger: 'blur' },
      ],
      typea : [
          { required: true, message: '货品分类不能为空', trigger: 'blur' },
      ],
      },

         total: 0,
           dialogImageUrl: '',
                 dialogVisible: false,
                 uploadImageUrl: process.env.VUE_APP_BASE_API + 'authdata/uploaderimage',
              uploadExcelUrl:  process.env.VUE_APP_BASE_API + 'authdata/GoodsExcel',
                 //图片请求头
 headers: { optname: 'insertcustompic', id: 1,token: getToken()},
       getDictList :{name:"getDictListSelect",parammaps:{pid:"75"}},
 fileList: [],
        statuesList: [
          { id: '0', name: '启用' },
          { id: '1', name: '禁用' }
        ],
        measureList:[],
       pageNum: 0,
       pageSize: 0,
       isView : false,
          isEdit : false,
        nodeKey: 'id',
        disabled: false, // 是否禁用
           listLoading: true,
           isShow: false,
            myHeight: document.documentElement.clientHeight - 85 - 250,
           rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
           cellStyle: { padding: 0 + 'px' },
           tableKey :0,
            list: [],//数据列表
           defaultCheckedKeys: [], // 默认选中 的节点

        getGoodsListParm:{name:'getGoodsList' ,page: 1,offset: 1, returntype: 'Map', pagecount: 7, parammaps:{ goodsTypeId:''}},
        getEmployeesSelectParm :{name:'getEmployeesSelect'},
        updateGoodsStatusByIdParm : {  name: "updateGoodsStatusById", returntype: "Map",  parammaps: {goodsEnabled: 0, id: 0 } },

        empList :[],
        placeholder: '请选择设备分类',
        deleteGoodsParm:{name: 'deleteGoods',parammaps:{ id:''}},
        getGoodsTypeParm: { name: 'GetGoodsTypeList' },
        goodsTypeData:[],
         goodsTypeData1:[],
        formLabelAlign :{ goodsTypeId: '',
     goodsCode: ''},
        dialogTitle : '',
         dialogFormVisible: false,
        defaultProps: {
          children: 'children',
          label: 'goodsTypeName'
        }
      };
    },
    methods: {

      buildInsertRequest() {
        return {
          common: { returnmap: "0" },
          data: [
            {
              name: "CheckGoodsNameUniqueOnInsert",
              type: "v",
              parammaps: { goodsName: this.formLabelAlign.goodsName }, // 动态绑定 goodsName
            },
            {
              name: "CheckGoodsCodeUniqueOnInsert",
              type: "v",
              parammaps: { goodsCode: this.formLabelAlign.goodsCode }, // 动态绑定 goodsCode
            },
            {
              name: "InsertGoods",
              type: "e",
              parammaps: {
                goodsTypeId: this.formLabelAlign.goodsTypeId,
                goodsCode: this.formLabelAlign.goodsCode,
                goodsName: this.formLabelAlign.goodsName,
                goodsSpecification: this.formLabelAlign.goodsSpecification,
                goodsModel: this.formLabelAlign.goodsModel,
                goodsUnit: this.formLabelAlign.goodsUnit,
                createrId: this.formLabelAlign.createrId,
                remarks: this.formLabelAlign.remarks,
                goodsImage: this.formLabelAlign.goodsImage || "0",
                goodsEnabled:0,
                purpose: this.formLabelAlign.purpose || "",
                createTime: this.formLabelAlign.date,
              },
            },
          ],
        };
      },
      buildUpdateRequest() {
        return {
          common: { returnmap: "0" },
          data: [
            {
              name: "CheckGoodsNameUniqueOnUpdate",
              type: "v",
              parammaps: {
                goodsName: this.formLabelAlign.goodsName, // 动态绑定 goodsName
                id: this.formLabelAlign.id, // 动态绑定 id
              },
            },
            {
              name: "CheckGoodsCodeUniqueOnUpdate",
              type: "v",
              parammaps: {
                goodsCode: this.formLabelAlign.goodsCode, // 动态绑定 goodsCode
                id: this.formLabelAlign.id, // 动态绑定 id
              },
            },
            {
              name: "updateGoods",
              type: "e",
              parammaps: {
                id: this.formLabelAlign.id, // 动态绑定 id
                goodsTypeId: this.formLabelAlign.goodsTypeId,
                goodsCode: this.formLabelAlign.goodsCode,
                goodsName: this.formLabelAlign.goodsName,
                goodsSpecification: this.formLabelAlign.goodsSpecification,
                goodsModel: this.formLabelAlign.goodsModel,
                goodsUnit: this.formLabelAlign.goodsUnit,
                remarks: this.formLabelAlign.remarks,
                goodsImage: this.formLabelAlign.goodsImage || "0", // 默认值为 "0"
                goodsEnabled: this.formLabelAlign.goodsEnabled || "1", // 默认值为 "1"
              },
            },
          ],
        };
      },

        resetInsertForm() {
          // 重置 formLabelAlign 数据
          this.formLabelAlign = {
            goodsTypeId: '', // 商品类别 ID
            goodsCode: '', // 商品编码
            goodsName: '', // 商品名称
            goodsSpecification: '', // 商品规格
            goodsModel: '', // 商品型号
            goodsUnit: '', // 商品单位
            createrId: '', // 创建人 ID
            remarks: '', // 备注
            goodsImage: '0', // 商品图片
            goodsEnabled: '1', // 商品状态（默认启用）
            purpose: '', // 用途
            picture: '', // 图片
          };

          this.fileList= [];
        },
         handleEditAndOff(){
           this.handleEdit1();
             this.dialogFormVisible = false;
           },
        handleEdit1(){


        const  code = this.formLabelAlign.goodsUnit;
        const  id  = this.formLabelAlign.goodsUnitId;
        console.log("goodsCode : ",code);
        console.log("goodsTypeId : ",id);

        if (typeof code === 'number') {
         this.formLabelAlign.goodsUnit = code ;
        } else {
          this.formLabelAlign.goodsUnit = id ;
        }


          const requestParam = this.buildUpdateRequest();
          console.log(requestParam);
             ExecDataByConfig(requestParam).then(response => {
               if (response.msg !== 'fail') {
                 this.resetInsertForm();
                 this.get_goods_data();
                         this.isEdit= false;
                 this.defaultCheckedKeys=  [];
                 this.$notify({
                   title: '成功',
                   message: '操作成功',
                   type: 'success',
                   duration: 2000,
                 });
               } else {
                 this.$notify({
                   title: '失败',
                   message: response.data,
                   type: 'error',
                   duration: 2000,
                 });
               }
             });
        },
        handleAddAndOff(){
          this.handleAdd();
           this.dialogFormVisible = false;
        },
  handleAdd() {

     const requestParam = this.buildInsertRequest();
     ExecDataByConfig(requestParam).then(response => {
       if (response.msg !== 'fail') {
         this.resetInsertForm();
         this.get_goods_data();
                 this.isEdit= false;
  this.defaultCheckedKeys=  [];
         this.$notify({
           title: '成功',
           message: '操作成功',
           type: 'success',
           duration: 2000,
         });
       } else {
         this.$notify({
           title: '失败',
           message: response.data,
           type: 'error',
           duration: 2000,
         });
       }
     });
   },

      handleCancel(){
         this.defaultCheckedKeys= [];
        this.formLabelAlign.createrId = '';
        this.dialogFormVisible = false;
        this.dialogImageUrl  = '';
this.isShow = false;
this.isView = false;
        this.resetInsertForm();
         this.isEdit= false;
      },
      handlePicChange(file, fileList) {

      },
      beforeImportExcel(file) {
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.error('上传文件大小不能超过 2MB!')
        }
        return isLt2M
      },

      handleImportExcelSuccess(res, file) {
      //  if (res.msg === 'ok') {
        if (res.msg === 'ok') {
          if (res.data.err_count > 0) {
            this.$message({
              title: '失败',
              message: '导入失败',
              type: 'danger',
              duration: 2000
            })
            this.$notify({
              title: '失败',
              message: '导入失败',
              type: 'danger',
              duration: 2000
            })
             import('@/vendor/Export2Excel').then(excel => {
               const list1 = res.data.result
               const tHeader = [
                 '货品类别',
                 '货品编号',
                 '货品名称',
                 '货品规格',
                 '货品型号',
                 '计量单位',
                 '用途',
                 '录入人',
                 '备注', '错误信息'
               ]
               const filterVal = [
                '货品类别',
                '货品编号',
                '货品名称',
                '货品规格',
                '货品型号',
                '计量单位',
                '用途',
                '录入人',
                '备注','error_msg'
               ]
               const data1 = this.formatJson(filterVal, list1)
               excel.export_json_to_excel({
                 header: tHeader,
                 data: data1,
                 filename: '货品信息_error',
                 autoWidth: true,
                 bookType: 'xlsx'
               })
             })
          }else{
            this.get_goods_data();
            this.$message({
              title: '成功',
              message: '导入成功',
              type: 'success',
              duration: 2000
            })
            this.$notify({
              title: '成功',
              message: '导入成功',
              type: 'success',
              duration: 2000
            })
          }
        } else {
          this.$notify({
            title: '失败',
            message: '上传失败',
            type: 'danger',
            duration: 2000
          })
        }
      },


       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) {
                  console.log('文件上传成功时的钩子response', response, );
                  console.log('文件上传成功时的钩子file', file);
                  console.log('fileList', fileList);
                  if (fileList.length == 1) {
                    document.getElementById('uploadPic').lastChild.style.display = "none"
                  } else {
                    document.getElementById('uploadPic').lastChild.style.display = "inline-block"
                  }
                  this.$set(this.formLabelAlign, 'goodsImage', response.execresult.LastInsertId);
                 },
            handlePictureCardPreview(file) {
              this.dialogImageUrl = file.url;
              this.dialogVisible = true;
      },
      popoverHideAdd(checkedIds,row){
        this.formLabelAlign.goodsTypeId = row.id;
        console.log(row);
          console.log(row.goodsTypeCode);
            console.log("11111111111111111");

        this.formLabelAlign.goodsCode = row.goodsTypeCode;
         console.log( this.formLabelAlign.goodsCode);
      },
     handleDel(row) {
       MessageBox.confirm('名称：' + row.goodsName, '确认删除？', {
         confirmButtonText: '确认',
         cancelButtonText: '取消',
         type: 'warning',
       }).then(() => {
         this.deleteGoodsParm.parammaps.id = row.id;
         PostDataByName(this.deleteGoodsParm).then(response => {
           if (response.msg !== 'fail') {
              this.get_goods_data();
             this.$notify({
               title: '成功',
               message: '删除成功',
               type: 'success',
               duration: 2000,
             });
           } else {
             failproccess(response, this.$notify);
           }
         });
       });

     },
   handleSwitchChange(index,row) {
     console.log(row.goodsEnabled);
     this.updateGoodsStatusByIdParm.parammaps.id = row.id;
     this.updateGoodsStatusByIdParm.parammaps.goodsEnabled = row.goodsEnabled;
     // if (row.goodsEnabled == 1 ){
     //        console.log("00000000000000");
     //   this.updateGoodsStatusByIdParm.parammaps.goodsEnabled  = 0;
     // }else{
     //       console.log("1111111111111111111");
     //    this.updateGoodsStatusByIdParm.parammaps.goodsEnabled  = 1;
     // }


     // 调用API更新状态
     PostDataByName(this.updateGoodsStatusByIdParm).then(response => {
       if (response.msg !== 'fail') {
         // 更新前端状态
          this.get_goods_data();
         // 显示成功通知
         this.$notify({
           title: '成功',
           message: '修改成功',
           type: 'success',
           duration: 2000,
         });
       } else {
         // 处理失败情况
         failproccess(response, this.$notify);
       }
     });
   },
      form_search(){
      this.get_goods_data();
      },
      template_excel(){
        import('@/vendor/Export2Excel').then(excel => {

          const tHeader = [
            '货品类别',
            '货品编号',
            '货品名称',
            '货品规格',
            '货品型号',
            '计量单位',
            '用途',
            '录入人',
            '备注'
          ];

          excel.export_json_to_excel({
            header: tHeader,
            data: [],
            filename: '货品模板',
            autoWidth: true,
            bookType: 'xlsx'
          })
        })
      },
      derive_data(){
          this.get_goods_data()
         import('@/vendor/Export2Excel').then(excel => {
                const tHeader = [
                  '货品名称',
                  '货品编号',
                  '货品规格',
                  '货品型号',
                  '计量单位',
                  '用途',
                  '录入人',
                  '一级分类',
                  '二级分类',
                  '三级分类'
                ];

              const filterVal = [
                'goodsName',
                'goodsCode',
                'goodsSpecification',
                'goodsModel',
                'goodsUnit',
                'purpose',
                'createrName',
                'goodsTypeName1',
                'goodsTypeName2',
                'goodsTypeName'
              ];
                const data1 = this.formatJson(filterVal, this.list)
                excel.export_json_to_excel({
                  header: tHeader,
                  data: data1,
                  filename: '货品导出',
                  autoWidth: true,
                  bookType: 'xlsx'
                })
              })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v =>
          filterVal.map(j => {
            if (j === 'timestamp') {
              return parseTime(v[j])
            } else {
              return v[j]
            }
          })
        )
      },
    form_add(){
      this.isShow = true;
      this.isView = false;
       console.log("form_add called, isView set to:", this.isView);
      this.dialogTitle = "新增货品"
      this.formLabelAlign.createrId = Cookies.get('employeid');
       this.formLabelAlign.date = this.getDefaultDate();
      this.dialogFormVisible = true;
    },
      getDefaultDate() {
          const today = new Date();
          const year = today.getFullYear();
          const month = String(today.getMonth() + 1).padStart(2, '0');
          const day = String(today.getDate()).padStart(2, '0');
          return `${year}-${month}-${day}`;
        },
    handleGet(row){
     this.dialogTitle = "查看货品";
     this.isView = true;
      this.dialogFormVisible = true;
  this.formLabelAlign.id = row.id;
      this.formLabelAlign.goodsModel = row.goodsModel;
      this.formLabelAlign.goodsImage = row.goodsImage;
      this.formLabelAlign.goodsTypeId = row.goodsTypeId;
      this.formLabelAlign.goodsCode = row.goodsCode;
      this.formLabelAlign.goodsName = row.goodsName;
      this.formLabelAlign.goodsSpecification = row.goodsSpecification;
      this.formLabelAlign.purpose = row.purpose;
       this.formLabelAlign.goodsEnabled = row.goodsEnabled;
      this.formLabelAlign.date = row.createTime;
      this.formLabelAlign.remarks = row.remarks;
      this.defaultCheckedKeys = [row.goodsTypeId];
  this.formLabelAlign.createrId = row.createrId;
   this.formLabelAlign.goodsUnitId=  row.goodsUnitId;
   this.formLabelAlign.goodsUnit = row.goodsUnit;
   this.dialogImageUrl =   row.goodsImagePath;
      const fileList = [];
        var urlObj = { "url": "", "response": { "execresult": { "LastInsertId": "" } } };
        urlObj.url = row.goodsImagePath;
        urlObj.response.execresult.LastInsertId = row.goodsImage;
        fileList.push(urlObj);

      this.fileList = fileList;
    },


    handleEdit(row){
      this.dialogTitle = "修改货品";
     this.isEdit = true;
      this.dialogFormVisible = true;
      this.formLabelAlign.id = row.id;
     this.formLabelAlign.goodsEnabled = row.goodsEnabled;
      this.formLabelAlign.goodsModel = row.goodsModel;
      this.formLabelAlign.goodsImage = row.goodsImage;
      this.formLabelAlign.goodsTypeId = row.goodsTypeId;
      this.formLabelAlign.goodsCode = row.goodsCode;
      this.formLabelAlign.goodsName = row.goodsName;
      this.formLabelAlign.goodsSpecification = row.goodsSpecification;
      this.formLabelAlign.purpose = row.purpose;
      this.formLabelAlign.date = row.createTime;
      this.formLabelAlign.remarks = row.remarks;
      this.defaultCheckedKeys = [row.goodsTypeId];
  this.formLabelAlign.createrId = row.createrId;

   this.formLabelAlign.goodsUnitId=  row.goodsUnitId;
   this.formLabelAlign.goodsUnit = row.goodsUnit;

   this.dialogImageUrl =   row.goodsImagePath;
      const fileList = [];
        var urlObj = { "url": "", "response": { "execresult": { "LastInsertId": "" } } };
        urlObj.url = row.goodsImagePath;
        urlObj.response.execresult.LastInsertId = row.goodsImage;
        fileList.push(urlObj);

      this.fileList = fileList;
      },
      popoverHide(checkedIds,checkedData) {
        if (checkedIds !== null) {
          this.getGoodsListParm.parammaps.goodsTypeId = checkedData.id
        } else {
          this.getGoodsListParm.parammaps.goodsTypeId ='';
        }
      },

  handleNodeClick(data, node) {
    console.log(data);
        this.getGoodsListParm.parammaps.goodsTypeId = data.id;
        this.get_goods_data_left();
      },
      get_goods_type_data() {
        GetDataByName(this.getGoodsTypeParm).then((response) => {
          if (response.data && response.data.list) {

            const list = response.data.list.map(item => ({
              ...item,
              pid: parseInt(item.pid),
              id: parseInt(item.id),
            }));
            this.goodsTypeData = transData(list, 'id', 'pid', 'children');

            for (let i = 0; i < response.data.list.length; i++) {
                  response.data.list[i].goodsTypeName = response.data.list[i].goodsTypeName +'/' +response.data.list[i].goodsTypeCode
            }
            const list1 = response.data.list.map(item => ({
              ...item,
              pid: parseInt(item.pid),
              id: parseInt(item.id),
            }));
            this.goodsTypeData1 = transData(list1, 'id', 'pid', 'children');
          }
        });
      },
      get_emp_data(){
        GetDataByName(this.getEmployeesSelectParm).then((response) => {
          if (response.data && response.data.list) {
            this.empList = response.data.list;
          }else{
           this.empList = [];
          }
        });
      },
      get_goods_data() {
       if (
        this.getGoodsListParm.parammaps.inputDatetime2 !== undefined &&
        this.getGoodsListParm.parammaps.inputDatetime2 !== null
       ) {
         this.getGoodsListParm.parammaps.startTime = this.getGoodsListParm.parammaps.inputDatetime2[0]
         this.getGoodsListParm.parammaps.stopTime = this.getGoodsListParm.parammaps.inputDatetime2[1]
       } else {
         this.getGoodsListParm.parammaps.startTime = ''
         this.getGoodsListParm.parammaps.stopTime = ''
       }
        GetDataByName(this.getGoodsListParm).then((response) => {
          if (response.data && response.data.list) {
            this.list = response.data.list;
            this.listLoading = false;
            for (let i = 0; i < response.data.list.length; i++) {
              if (
                response.data.list[i].goodsImagePath !== null
              ) {
                this.list[i].goodsImagePath =
                  process.env.VUE_APP_BASE_API + response.data.list[i].goodsImagePath;

              } else {
                this.list[i].goodsImagePath = ''
              }
            }
           this.pageNum =  response.data.pageNum
           this.pageSize  =   response.data.pageSize
            this.total = response.data.total
          }else{
           this.list = [];
            this.listLoading = false;
          }
        });
      },
      get_dict_list(){
            GetDataByName(this.getDictList).then((response) => {
                if (response.data && response.data.list) {
                  this.measureList = response.data.list;

                }
              });
      },
      get_goods_data_left() {
       if (
        this.getGoodsListParm.parammaps.inputDatetime2 !== undefined &&
        this.getGoodsListParm.parammaps.inputDatetime2 !== null
       ) {
         this.getGoodsListParm.parammaps.startTime = this.getGoodsListParm.parammaps.inputDatetime2[0]
         this.getGoodsListParm.parammaps.stopTime = this.getGoodsListParm.parammaps.inputDatetime2[1]
       } else {
         this.getGoodsListParm.parammaps.startTime = ''
         this.getGoodsListParm.parammaps.stopTime = ''
       }
        GetDataByName(this.getGoodsListParm).then((response) => {
          if (response.data && response.data.list) {
            this.list = response.data.list;
            this.listLoading = false;
            for (let i = 0; i < response.data.list.length; i++) {
              if (
                response.data.list[i].goodsImagePath !== null
              ) {
                this.list[i].goodsImagePath =
                  process.env.VUE_APP_BASE_API + response.data.list[i].goodsImagePath;

              } else {
                this.list[i].goodsImagePath = ''
              }
            }
           this.pageNum =  response.data.pageNum
           this.pageSize  =   response.data.pageSize
            this.total = response.data.total
          }else{
           this.list = [];
            this.listLoading = false;
          }
          this.getGoodsListParm.parammaps.goodsTypeId = '';
        });
      }
    },
    computed: {
      // 设置请求头
      headers() {
        return {
          // 设置token
          token: getToken()
        }
      },
      uploadData() {
        return {
          name: 'importGoodsExecl',
          importParams: '货品类别,货品编号,货品名称,货品规格,货品型号,计量单位,用途,录入人,备注',
          sheetname: 'SheetJS'
        }
      }
    },
    created() {
        console.log('defaultProps:', this.defaultProps);
        console.log('getGoodsListParm:', this.getGoodsListParm);
      this.get_goods_type_data();
       this.get_emp_data();
       this.get_dict_list();
      this.get_goods_data();

    },
  };
</script>


<style scoped>
.inline-form-item {
  display: flex;
  align-items: center;
}

.inline-form-item .el-form-item__label {
  margin-right: 10px; /* 调整标签和输入框之间的间距 */
}

::v-deep .el-tree-node {
  margin-bottom: 5px; /* 调整节点之间的间距 */
}


::v-deep .el-tree-node__label {
  font-size: 20px; /* 调整字体大小 */
}


</style>

<style>

.app-container {
  padding: 10px;
   margin-left: 10px;
}

.search-button-container {
  padding: 10px;
  padding-left: 20px;
}


  .typeSelect span .el-popover__reference .el-input--suffix {
    top: -3px;
    .el-input__inner {
      height: 40px !important;
    }
  }
.filter-item {
  margin-left: 10px; /* 设置左边距 */
}

.inputDatetime {
  padding: 0;
  margin: 0 10px;
  margin-left: 10px;
}

.search-button {
   padding: 10px 20px;
       border: 0.01px solid #ccc; /* 黑色边框，宽度为 2px */
        margin-right: 10px;
}

.search-button-upload {
   padding: 10px 20px;
       border: 0.01px solid #ccc; /* 黑色边框，宽度为 2px */
        margin-right: 20px;
}


.el-table .warning-row {
  background: oldlace;
}
.el-table .success-row {
  background: #f0f9eb;
}

.form-item {
  width:40%;
  display: flex;
  flex-direction: column;
  gap: 10px; /* 调整内部间距 */
}

#uploadPic {
  width: 700px;
}

.dialog-footer{
  right:10px;
  position:absolute;
  bottom:10px;
}
.add-button {
  background-color: #2196f3; /* 绿色背景 */
  color: white; /* 白色文字 */
  padding: 10px 20px; /* 内边距 */

  border-radius: 5px; /* 圆角 */
  cursor: pointer; /* 鼠标悬停时显示手型 */
  font-size: 16px; /* 字体大小 */
  transition: background-color 0.3s ease; /* 背景颜色过渡效果 */
  padding: 8px 12px;
  margin: 15px 30px;
    border: 0.01px solid #ccc; /* 黑色边框，宽度为 2px */
}

</style>
