<template>
  <div>
    <!-- 左侧树形结构 -->
    <el-container>
      <el-aside width="250px">
        <div class="JKWTree-tree">
          <h3>机台生产日报表附加维护</h3>
          <el-tree :data="treeData" :props="defaultProps" highlight-current="true"
            @node-click="handleNodeClick"></el-tree>
        </div>
      </el-aside>

      <el-container>
        <el-main>
          <!-- 按钮区域 -->
          <div class="gva-table-box">
            <div class="gva-btn-list">
              <el-row :span="6">
                <el-input v-model="searchInfo" placeholder="输入工单编号或产品名称" />
              </el-row>
              <el-button type="primary" :icon="Search" @click="onSearch">搜索</el-button>
              <el-button type="primary" :icon="Refresh">重置</el-button>
			  <el-button type="primary"  @click="onDel">删除</el-button>
              <div style="margin-left: auto;">
                <el-button type="primary" :icon="Download" @click="exportExcel">导出到Excel</el-button>
              </div>
            </div>
            <!-- 数据展示 -->
            <el-table ref="multipleTable" style="width: 100%" tooltip-effect="dark" :data="tableData" row-key="ID"
              highlight-current-row="true" border @selection-change="handleSelectionChange" 
			  :show-overflow-tooltip="true" @row-dblclick="doubleClick">
              <el-table-column type="selection" width="55" />
              <el-table-column align="left" label="生产日期" prop="sczl_rq" width="120"/>
              <el-table-column align="left" label="设备编号" prop="sczl_jtbh" width="120"/>
              <el-table-column align="left" label="设备名称" prop="sczl_sbmc" width="340"/>
              <el-table-column align="left" label="班组编号" prop="sczl_bzdh" width="120"/>
              <el-table-column align="left" label="排班工时" prop="sczl_设备运行工时" width="120"/>
              <el-table-column align="left" label="备注" prop="sczl_desc" width="120"/>
              <el-table-column align="left" label="创建用户" prop="sys_id" width="120"/>
              <el-table-column align="left" label="创建时间" prop="sys_rq" width="160"/>
              <el-table-column align="left" label="修改时间" prop="mod_rq" width="160"/>
              <el-table-column align="left" label="UNIQID" prop="UniqId" width="120"/>
            </el-table>
            <!-- 分页 -->
            <div class="gva-pagination">
              <el-pagination layout="total, sizes, prev, pager, next, jumper" :current-page="page" :page-size="limit"
                :page-sizes="[10, 30, 50, 100]" :total="total" @current-change="handleCurrentChange"
                @size-change="handleSizeChange" />
            </div>
          </div>
          <!-- 弹出框 -->
          <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" :title="type === 'create' ? '添加' : '修改'"
            destroy-on-close width="1200px">
            <!-- <el-scrollbar height="500px"> -->
            <el-form :model="formData" label-position="left" ref="elFormRef" :rules="rule">

              <el-row :gutter="20">

                <el-col :span="6">
                  <el-form-item label="日期" prop="name">
                    <el-row :gutter="20">
                      <el-col :span="12">
                        <el-input v-model="formData.sczl_rq" :clearable="true" placeholder="ZT01733" />
                      </el-col>
                    </el-row>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">            
                <el-col :span="8">
                  <el-row :gutter="20">
                    <el-col :span="14">
                      <el-form-item label="机器" prop="id">
                        <el-input v-model="formData.sczl_jtbh" @keyup.enter.native="getJTsubmit" :clearable="true" placeholder="0.00" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="10">                     
                        <el-input v-model="formData.设备名称" :clearable="true" placeholder="是" />
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
			  
			  <el-row :gutter="20">
			
			    <el-col :span="8">
			      <el-row :gutter="20">
			        <el-col :span="14">
			          <el-form-item label="组别" prop="id">
			            <el-input v-model="formData.sczl_bzdh" :clearable="true" placeholder="0.00" />
			          </el-form-item>
			        </el-col>
			        <el-col :span="10">
			            <el-form-item label="通电时间" prop="id">
			            <el-input v-model="formData.sczl_设备运行工时" :clearable="true" placeholder="是" />
			            </el-form-item>
			        </el-col>
			      </el-row>
			    </el-col>
			  </el-row>
			  
			  <el-row :gutter="20">			 
			    <el-col :span="8">
			      <el-row :gutter="20">
			        <el-col :span="14">
			        <el-form-item label="备注" prop="id" style="margin-top: 10px;">
			          <el-input v-model="formData.sczl_desc" :clearable="true" placeholder="" />
			        </el-form-item>
			        </el-col>
			      </el-row>
			    </el-col>
			  </el-row>
			  
            </el-form>
            <!-- </el-scrollbar> -->
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="closeDialog">取 消</el-button>
                <el-button type="primary" @click="enterDialog">确 定</el-button>
              </div>
            </template>
          </el-dialog>

          
		  <el-dialog
		    v-model="GetjtbhVisible"
		    title="选择"
		    destroy-on-close
		    width="600px"
		  			>		     
		       <el-aside width="250px">
		         <div class="JKWTree-tree">		          
		           <el-tree :data="GetJTtreeData" :props="defaultProps" highlight-current="true"
		             @node-click="GetMachineDedhhandleNodeClick" @node-dblclick="handleNodeDoubleClick"></el-tree>
		         </div>
		       </el-aside>		       
		  </el-dialog>
		  
        </el-main>
      </el-container>
    </el-container>

  </div>
</template>

<script setup>
import {
  getproductionaddList,
  getproductionaddCount,
  adddel,
  addedit,
  addgetJtbh,
  addgetInfo,
} from '@/api/jixiaoguanli/jitairibaobiao'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict, ReturnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Download } from '@element-plus/icons-vue'
import { ref, reactive, onMounted, onBeforeMount } from 'vue'
import { getPackingSideTable, getPackingTable } from '@/api/mes_api_gty/myapi'

defineOptions({
  name: '06-packingDocuments'
})

// 侧边栏数据请求
const treeData = reactive([]);

const getTabdata = async () => {
    //接口调用函数
    const response  = await getproductionaddCount();
	console.log(response)
	
	
	const transformedData = response.data.map(item => ({
	      label: `${item.date.replace(/-/g, '.')}【单据数: ${item.counts}张】`,
	      children: item.sys.map(sysItem => ({
	        label: `${sysItem.sys_id} 【记录数: ${sysItem.count}张】`,
	        params: {
	          date: item.date.replace(/\./g, '-'),
	          sys_id: sysItem.sys_id,
	          total: sysItem.count,
	        },
	      })),
	    }));
	    treeData.splice(0, treeData.length, ...transformedData);

	
	}

getTabdata();

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
			 sczl_rq: '',
             sczl_jtbh: '',
             设备名称: '',
             sczl_bzdh: '',
             sczl_设备运行工时: '',
             sczl_desc: '',
})

// 验证规则
const rule = reactive({
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const tableData = reactive([])
const detailData = reactive([])
const total = ref(0)
const page = ref(1)
const limit = ref(10)
const searchInfo = ref('')
const params = {
  date: '',
  sys_id: '',
  page: page.value.toString(),
  limit: limit.value.toString(),
}

// 分页设置
const handleSizeChange = (val) => {
  limit.value = val;
  params.limit = val.toString();
  getTableData();
}

// 页面跳转
const handleCurrentChange = (val) => {
  page.value = val
  params.page = val.toString();
  getTableData()
}

const getTableData = async () => {
  const response = await getproductionaddList(params);
  if (response.code === 0) {
    tableData.splice(0, tableData.length, ...response.data.rows);
  }
}

const handleNodeClick = (node, check) => {
  if (node.params) {
    params.date = node.params.date;
    params.sys_id = node.params.sys_id;
    total.value = node.params.total;
    handleCurrentChange(1);
  }
}

// 搜索
function onSearch() {

}
// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () => {
}

// 获取需要的字典 可能为空 按需保留
setOptions()

// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
  // multipleSelection.value = val
  if(val.length>0){
  	multipleSelection.value = val
  	const lenth=val.length
  	// ScrapFactor.gdbh=val[lenth-1].combinedProp.split('-')[0];
  	// const parts = val[lenth-1].combinedProp2.split('-')
  	// ScrapFactor.yjno=parts[0];
  	// ScrapFactor.gxh=parts[1];
  	// ScrapFactor.type=val[lenth-1].sczl_检验类别
  	// console.log(ScrapFactor)
  	lastCellValue=val[lenth-1].UniqId
  	console.log(val)
  	val.splice(0, val.length);  // 清空 val 数组	
  	console.log(lastCellValue)
  }
}

// 批量删除控制标记
const deleteVisible = ref(false)

// 多选删除
const onDelete = async () => {
  const ids = []
  if (multipleSelection.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据'
    })
    return
  }
  multipleSelection.value &&
    multipleSelection.value.map(item => {
      ids.push(item.ID)
    })
  const res = await deleteCompanyByIds({ ids })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === ids.length && page.value > 1) {
      page.value--
    }
    deleteVisible.value = false
    getTableData()
  }
}

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const updateCompanyFunc = async (row) => {
  const res = await findCompany({ ID: row.ID })
  type.value = 'update'
  if (res.code === 0) {
    formData.value = res.data.recompany
    dialogFormVisible.value = true
  }
}

// 弹窗控制标记
const dialogFormVisible = ref(false)

// 打开弹窗
const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    address: '',
    image: '',
    name: '',
  }
}
// 弹窗确定
const enterDialog = async () => {
	
	
  updateDetailData()
  // elFormRef.value?.validate(async (valid) => {
  //   if (!valid) return
  //   let res
  //   switch (type.value) {
  //     case 'create':
  //       res = await createCompany(formData.value)
  //       break
  //     case 'update':
  //       res = await updateCompany(formData.value)
  //       break
  //     default:
  //       res = await createCompany(formData.value)
  //       break
  //   }
  //   if (res.code === 0) {
  //     ElMessage({
  //       type: 'success',
  //       message: '创建/更改成功'
  //     })
  //     closeDialog()
  //     getTableData()
  //   }
  // })
}
let table=ref(5);
let lastCellValue=ref()
// 双击表格操作
function doubleClick(row, column, event) {
  type.value = 'update';
  		  lastCellValue= row['UniqId'];
    		 console.log(lastCellValue)
  table.value=lastCellValue
  	 dialogFormVisible.value = true
	 AddgetInfo(table.value)
}
//获取详细信息
const AddgetInfo = async (value) => {
  const response = await addgetInfo({UniqId:value});
  console.log(response) 
  if (response.code === 0) {
	formData.value=response.data[0];
  }
}
//机台回车事件
const getJTsubmit = (event, inputName) => {
	  GetJtbh()
}
const GetjtbhVisible = ref(false)
let GetJTtreeData = reactive([]);
//获取机台
const GetJtbh = async () => {
  const response = await addgetJtbh({sys_mc:''});
  if(response.code==0){
	  // 遍历接口返回的数据，构建父子关系
	GetJTtreeData.splice(0, GetJTtreeData.length);
	response.data.forEach(item => {
	  const departments = item["使用部门"];
	  departments.forEach(department => {
	    const departmentData = {
	      label: department,
	      value: department,
	      children: item[department].map(device => {
	        return {
	          label: device["jtbh"]+'/'+device["设备名称"],
	          value: device["jtbh"]
	        };
	      })
	    };
	    GetJTtreeData.push(departmentData);
	  });
	});
		
		
		// 将父子关系转换为数组
		// const transformedData = Object.values(treeData);
		// console.log(transformedData)
		// GetJTtreeData = transformedData;
	  // JTBHselectData.splice(0, selectData.length, ...response.data)
	  GetjtbhVisible.value=true
	   
  }
  console.log(response)
}
const GetMachineDedhhandleNodeClick = (node,check,nodeData) => {
  if (node.children) {
       // 点击的是父节点
       // 执行相应的父节点单击事件处理逻辑
	   console.log('2222')
     } else {
       // 点击的是子节点
       // 执行相应的子节点单击事件处理逻辑
       console.log('11111');
	   console.log(node.label)
	   const splitIndex = node.label.indexOf('/');
	   formData.value.sczl_jtbh = node.label.substring(0, splitIndex);
	   formData.value.设备名称 = node.label.substring(splitIndex + 1);
	    GetjtbhVisible.value=false
     }
}
// 更新数据
const updateDetailData = async() => {
  const restoredData = {
    UniqId: lastCellValue,
	sczl_rq:formData.value.sczl_rq,
	sczl_jtbh:formData.value.sczl_jtbh,
	sczl_bzdh:formData.value.sczl_bzdh,
	sczl_设备运行工时:formData.value.sczl_设备运行工时,
	sczl_desc:formData.value.sczl_desc,
  }

  console.log(restoredData)
    console.log(lastCellValue)
    formData.value.UniqId=lastCellValue
    console.log(formData)
	restoredData.UniqId='10'
   const response = await addedit(restoredData);
  // console.log(FormData)
  console.log(response)
}

const AddDel = async (value) => {
  const response = await adddel({UniqId:'0'});
  console.log(response) 
  if (response.code === 0) {
	 console.log('333') 
  }
}

//删除
function onDel() {
	AddDel()
}
// 导出excel
function exportExcel() {
  console.log('导出到excel');
}

// 生命周期钩子
onMounted(async () => {
});
</script>

<style>
.JKWTree-container {
  display: flex;
}

.JKWTree-tree {
  width: 300px;
  background-color: #fff;
  padding: 10px;
  margin-right: 20px;
}

.JKWTree-tree h3 {
  font-size: 15px;
  font-weight: 700;
  margin: 10px 0;
}

.JKWTree-content {
  flex: 1;
}

/* 选中某行时的背景色*/
.el-table__body tr.current-row>td {
  background: #ff80ff !important;
  /* 背景颜色 */
}
</style>