<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" @click="onrelevancy">关联工资设置</el-button>
			  <el-button type="primary" :icon="Search" @click="onposition">定位</el-button>
			  <el-button type="primary" :icon="Search">查改</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%;height: 40vh;" tooltip-effect="dark" :data="tableData" row-key="ID" 
              highlight-current-row="true" border @selection-change="handleSelectionChange" :show-overflow-tooltip="true"
			   :row-style="{ height: '20px' }" 
			   :cell-style="{ padding: '0px' }" :header-row-style="{ height: '20px' }"
			   :header-cell-style="{ padding: '0px' }" @row-click="ontable" @row-dblclick="doubleClick">
              <!-- <el-table-column type="selection" width="55" /> -->
			  <el-table-column align="left" sortable label="员工编号" prop="员工编号" width="120"/>
              <el-table-column align="left" sortable label="员工姓名" prop="员工姓名" width="120"/>
			  <el-table-column align="left" sortable label="职称职务" prop="职称职务" width="160"/>
			  <el-table-column align="left" sortable label="所在部门" prop="所在部门" width="160"/>
			  <el-table-column align="left" sortable label="日期" prop="日期" width="160"/>
			  <el-table-column align="left" sortable label="关联系数" prop="关联系数" width="120"/>
              <el-table-column align="left" sortable label="关联人数" prop="关联人数" width="120"/>
              <el-table-column align="left" sortable label="关联计件工资" prop="个人计件工资" width="120"/>
              <el-table-column align="left" sortable label="关联加班工资" prop="个人加班工资" width="160"/>
			  <el-table-column align="left" sortable label="关联额定补差" prop="计时" width="160"/>
              <el-table-column align="left" sortable label="关联计时工资" prop="计时工资" width="160"/>
              <el-table-column align="left" sortable label="关联工资合计" prop="日工资合计" 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>
		  
		  
		  <div class="gva-table-box">
		    <!-- 数据展示 -->
		    <el-table ref="multipleTable" style="width: 100%" height="300px" tooltip-effect="dark" :data="tableData2" 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" sortable label="日期" prop="日期" width="120"/>
		      <el-table-column align="left" sortable label="员工编号" prop="员工编号" width="120"/>
		      <el-table-column align="left" sortable label="员工姓名" prop="员工姓名" width="120"/>
		      <el-table-column align="left" sortable label="职称职务" prop="职称职务" width="120"/>
		      <el-table-column align="left" sortable label="所在部门" prop="所在部门" width="160"/>
		      <el-table-column align="left" sortable label="被关联员工" prop="被关联员工" width="160"/>
		      <el-table-column align="left" sortable label="被关联姓名" prop="被关联姓名" width="120"/>
			  <el-table-column align="left" sortable label="权重" prop="权重" width="120"/>
			  <el-table-column align="left" sortable label="计件工资" prop="个人计件工资" width="120"/>
			  <el-table-column align="left" sortable label="加班工资" prop="个人加班工资" width="120"/>
			  <el-table-column align="left" sortable label="定额补差" prop="定额补差" width="120"/>
			  <el-table-column align="left" sortable label="计时工资" prop="计时工资" width="160"/>
		    </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" style="height: 700px;" >
            <!-- <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.关联人员工号" @keyup.enter.native="getygsubmit" :clearable="true" placeholder="ZT01733" />
                      </el-col>
					  <el-col :span="12">
					    <el-input v-model="formData.关联人员姓名" :clearable="true" placeholder="ZT01733" />
					  </el-col>
                    </el-row>
                  </el-form-item>
                </el-col>
				<el-col :span="6">
				  <el-form-item label="日期" prop="name">
				    <el-row :gutter="3">
				      <el-col :span="10">
				        <el-input v-model="formData.日期" :clearable="true" placeholder="ZT01733" />
				      </el-col>
				    </el-row>
				  </el-form-item>
				</el-col>
				<el-col :span="4">
				  <el-form-item label="关联系数" prop="name">
				    <el-row :gutter="3">
				      <el-col :span="12">
				        <el-input v-model="formData.日关联系数" :clearable="true" placeholder="ZT01733" />
				      </el-col>
				    </el-row>
				  </el-form-item>
				</el-col>
				<el-col :span="3">
					<el-col :span="3">
					  <el-button type="primary" @click="onflushed">刷新</el-button>
					</el-col>
				  
				</el-col>
				<el-col :span="4">
				  <el-form-item label="关联人数" prop="name">
				    <el-row :gutter="20">
				      <el-col :span="12">
				        <el-input v-model="formData.日关联人数" :clearable="true" placeholder="ZT01733" />
				      </el-col>
				    </el-row>
				  </el-form-item>
				</el-col>
              </el-row>
            </el-form>
			
			
			<el-table
			  tooltip-effect="dark"
			  :data="relevancyselectData"
			  row-key="ID"
			  highlight-current-row="true"
			  border
			  style="width:100%"
			  height="400px"
			  @row-dblclick="relevancySelectClick"
			  :selectable="row => rowSelectable(row)"
			  @selection-change="relevancySelectionChange"
			>
			  <el-table-column type="selection" width="55" align="center" label=""></el-table-column>
			  <el-table-column
			    prop="日期"
			    label="日期"
			    width="150"
			  />
			  <el-table-column
				prop="班组员工编号"
				label="班组员工编号"
				width="400"
			  />
			  <el-table-column
			    prop="组员权重"
			    label="组员权重"
			    width="150"
			  />
			  <el-table-column
				prop="计件工资基数"
				label="计件工资基数"
				width="400"
			  />
			  <el-table-column
			    prop="加班工资基数"
			    label="加班工资基数"
			    width="150"
			  />
			  <el-table-column
			    prop="UniqID"
			    label="UniqID"
			    width="150"
			  />
			</el-table>
			
            <!-- </el-scrollbar> -->
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="batchadd">批量附加组员</el-button>
				<el-button @click="batchdel">批量删除组员</el-button>
				<el-button @click="uprelevancy">更新关联系数</el-button>
				<el-button @click="oncopy">组员复制</el-button>
				<el-button @click="closeDialog">取 消</el-button>
                <el-button type="primary" @click="enterDialog">确 定</el-button>
              </div>
            </template>
          </el-dialog>


          <el-dialog v-model="positioningVisibleshow" :before-close="closepositioningVisible" :title="type==='create'?'添加':'修改'" destroy-on-close>
            
          	<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.员工编号" :clearable="true" placeholder="ZT01733" />
          	        </el-col>
          	      </el-row>				  
          	    </el-form-item>
          	  </el-col>
			  <el-col :span="6">
			    <el-form-item label="姓名" prop="name">
			      <el-row :gutter="20">
			        <el-col :span="12">
			          <el-input v-model="formData.姓名" :clearable="true" placeholder="ZT01733" />
			        </el-col>
			      </el-row>				  
			    </el-form-item>
			  </el-col>
          	</el-row>
			
			<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.部门名称" :clearable="true" placeholder="ZT01733" />
			        </el-col>
			      </el-row>				  
			    </el-form-item>
			  </el-col>
			  <el-col :span="6">
			    <el-form-item label="职务" prop="name">
			      <el-row :gutter="20">
			        <el-col :span="12">
			          <el-input v-model="formData.职务" :clearable="true" placeholder="ZT01733" />
			        </el-col>
			      </el-row>				  
			    </el-form-item>
			  </el-col>
			</el-row>
			
			
			<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.入职日期" :clearable="true" placeholder="ZT01733" />
			        </el-col>
			      </el-row>
			    </el-form-item>
			  </el-col>
			</el-row>
			
			
			<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.关联权重" :clearable="true" placeholder="ZT01733" />
			        </el-col>
			      </el-row>
			    </el-form-item>
			  </el-col>
			</el-row>
          </el-dialog>
         
		 
		 <el-dialog v-model="batchaddshow" :before-close="closepositioningVisible" :title="type==='create'?'添加':'修改'" destroy-on-close>
		   
		 	<el-col :span="12">
		 	  <el-form-item label="定位" prop="name">
		 	    <el-row :gutter="3">
		 	      <el-col :span="12">
		 	        <el-input v-model="formData.定位" :clearable="true" placeholder="ZT01733" />
		 	      </el-col>
				  <el-col :span="3">
				    <el-button type="primary" @click="oninvestigate">查找</el-button>
				  </el-col>
		 	    </el-row>
		 	  </el-form-item>
		 	</el-col>
		 	
		 	<el-table
		 	  tooltip-effect="dark"
		 	  :data="batchaddselectData"
		 	  row-key="ID"
		 	  highlight-current-row="true"
		 	  border
		 	  style="width:100%"
		 	  height="400px"
		 	  @row-dblclick="batchaddSelectClick"
		 	  :selectable="row => rowSelectable(row)"
		 	  @selection-change="batchaddSelectionChange"
		 	>
		 	  <el-table-column type="selection" width="55" align="center" label=""></el-table-column>
		 	  <el-table-column
		 	    prop="日期"
		 	    label="日期"
		 	    width="150"
		 	  />
		 	  <el-table-column
		 		prop="所在部门"
		 		label="所在部门"
		 		width="400"
		 	  />
		 	  <el-table-column
		 	    prop="职称职务"
		 	    label="职称职务"
		 	    width="150"
		 	  />
		 	  <el-table-column
		 		prop="班组员工编号"
		 		label="班组员工编号"
		 		width="400"
		 	  />
		 	  <el-table-column
		 	    prop="班组"
		 	    label="班组"
		 	    width="150"
		 	  />
			  <el-table-column
			    prop="计件工资基数"
			    label="计件工资基数"
			    width="150"
			  />
			  <el-table-column
			    prop="加班工资基数"
			    label="加班工资基数"
			    width="150"
			  />
		 	  <el-table-column
		 	    prop="UniqID"
		 	    label="UniqID"
		 	    width="150"
		 	  />
		 	</el-table>	
				
			<template #footer>
			  <div class="dialog-footer">
				<el-button @click="batchup">提 交</el-button>
			  </div>
			</template>
		 </el-dialog>
		 
		 
		 <el-dialog v-model="copyshow" :before-close="closepositioningVisible" :title="type==='create'?'添加':'修改'" destroy-on-close>
		   
		 	<el-col :span="10">
		 	  <el-form-item label="日期" prop="name">
		 	    <el-row :gutter="3">
		 	      <el-col :span="10">
		 	        <el-input v-model="formData.old_time" @keyup.enter.native="getcopylist" :clearable="true" placeholder="ZT01733" />
		 	      </el-col>
		 				  
						 <el-col :span="13">
						   <el-form-item label="复制成" prop="name">
						     <el-row :gutter="3">
						       <el-col :span="20">
						         <el-input v-model="formData.new_time" :clearable="true" placeholder="ZT01733" />
						       </el-col>
						 			  <el-col :span="3">
						 			    <el-button type="primary" @click="oncopyup">执行</el-button>
						 			  </el-col>						 			 
						     </el-row>						 	
						   </el-form-item>
						 </el-col>
		 	    </el-row>
				
		 	  </el-form-item>
		 	</el-col>
		 	
		 	<el-table
		 	  tooltip-effect="dark"
		 	  :data="copyselectData"
		 	  row-key="ID"
		 	  highlight-current-row="true"
		 	  border
		 	  style="width:100%"
		 	  height="400px"
		 	  @row-dblclick="copySelectClick"
		 	  :selectable="row => rowSelectable(row)"
		 	  @selection-change="copySelectionChange"
		 	>
		 	  <el-table-column type="selection" width="55" align="center" label=""></el-table-column>
		 	  <el-table-column
		 	    prop="员工编号"
		 	    label="员工编号"
		 	    width="150"
		 	  />
		 	  <el-table-column
		 		prop="员工姓名"
		 		label="员工姓名"
		 		width="400"
		 	  />
			  <el-table-column
			    prop="所在部门"
			    label="所在部门"
			    width="150"
			  />
		 	  <el-table-column
		 	    prop="职称职务"
		 	    label="职称职务"
		 	    width="150"
		 	  />
			  <el-table-column
				prop="UniqID"
				label="UniqID"
				width="150"
			  />
		 	</el-table>	
		 				
		 </el-dialog>
		 
        </el-main>
      </el-container>
    </el-container>

  </div>
</template>

<script setup>
import {
  getList,
  getTab,
  dailygetTab,
  dailygetList,
  dailygetAllList,
  dailygetDetail,
  dailysearch,
  relatedTab,
  relatedList,
  relatedsearch,
  relatedAllList,
  setting,
  getYg,
  weightDetail,
  updateNum,
  batchAddLst,
  copyLst,
  batchAdd,
  batchDel,
  copy,
  batchAddSearch
} 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'
import { Value } from 'sass'

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

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

const getTabdata = async () => {
    //接口调用函数
    const response  = await relatedTab();
	console.log(response)
	
	
	const transformedData = response.data.map(item => ({
	      label: `${item.label}`,
	      children: item.children.map(sysItem => ({
	        label: `${sysItem.label}`,
	        params: {
	          date: item.label,
	          sys_id: sysItem.label,
	          total:'',
	        },
	      })),
	    }));
	    treeData.splice(0, treeData.length, ...transformedData);
 console.log(treeData)
	
	}
	

getTabdata();

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
 关联人员工号: '',
 关联人员姓名: '',
 日关联系数: '',
 日关联人数: '',
 日期: '',

 员工编号:'',
 姓名:'',
 部门名称:'',
 职务:'',
 入职日期:'',
 关联权重:'',
 定位:'',
 
 old_time:'',
 new_time:'',
})

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

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

// =========== 表格控制部分 ===========
const tableData = reactive([])
const tableData2 = 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 relatedList({
	  date: params.date, department: params.sys_id,});
  console.log(response)
  if (response.code === 0) {
	   const originalData = response.data;
	      const summaryData = generateSummaryData(originalData);
	      // 将合计数据插入到原始数据中
	      const combinedData = [];
	      originalData.forEach((item, index) => {
	        combinedData.push(item);
	        const nextItem = originalData[index + 1];
	        if (nextItem && nextItem['员工姓名'] !== item['员工姓名']) {
	          // 如果下一个员工姓名与当前不同，插入合计数据
	          const currentSummary = summaryData.shift();
	          combinedData.push(currentSummary);
			  console.log(currentSummary)
			 
	        }
	      });
		  console.log(combinedData)
	      // 更新表格数据
	      tableData.splice(0, tableData.length, ...combinedData);
		  
  }
}

const generateSummaryData = (data) => {
  const summaryData = [];
  let currentName = null;
  let currentSummary = null;

  data.forEach((item, index) => {
    const name = item['员工姓名'].trim(); // 获取员工姓名并去除空格
    const nextItem = data[index + 1];

    // 更新合计数据
    if (currentName === name) {
      currentSummary['日期']++;
      currentSummary['计件工资'] += parseFloat(item['计件工资']);
      currentSummary['加班工资'] += parseFloat(item['加班工资']);
      currentSummary['日工资合计'] += parseFloat(item['日工资合计']);
    } else {
      // 如果员工姓名发生改变，或者已经到达数据结尾，将上一个员工的合计数据插入到数组中
      if (currentSummary) {
        currentSummary['员工姓名'] = '合计（' + currentSummary['日期'] + '天）';
        currentSummary['计件工资'] = currentSummary['计件工资'].toFixed(2); // 保留两位小数
        currentSummary['加班工资'] = currentSummary['加班工资'].toFixed(2);
        currentSummary['日工资合计'] = currentSummary['日工资合计'].toFixed(2);
        summaryData.push(currentSummary);
      }

      // 创建新的合计数据
      currentSummary = {
        '员工姓名': name,
        '日期': 1,
        '计件工资': parseFloat(item['计件工资']),
        '加班工资': parseFloat(item['加班工资']),
        '日工资合计': parseFloat(item['日工资合计'])
      };
      currentName = name;
    }

    // 如果已经到达数据结尾，将最后一个员工的合计数据插入到数组中
    if (!nextItem) {
      currentSummary['员工姓名'] = '合计（' + currentSummary['日期'] + '天）';
      currentSummary['计件工资'] = currentSummary['计件工资'].toFixed(2); // 保留两位小数
      currentSummary['加班工资'] = currentSummary['加班工资'].toFixed(2);
      currentSummary['日工资合计'] = currentSummary['日工资合计'].toFixed(2);
      summaryData.push(currentSummary);
    }
  });

  return summaryData;
};
let date=ref()
const handleNodeClick = (node, check) => {
  //存放当前节点的nodeId
  if (node.params) {
    params.date = node.params.date;
    params.sys_id = node.params.sys_id;
    total.value = node.params.total;
	date=node.params.date
	console.log(date)
    getTableData();
	
  }
}
const relevancyselectData=ref([]);
// 关联工资设置
function onrelevancy() {
	console.log(formData)
	console.log(code)
	console.log(time)
	Setting(time.value,code.value)
    
}
//获取关联工资信息
const Setting = async (date,code) => {

  const res = await setting({date:date,code:code})
  console.log(res)
  if (res.code === 0) {
  relevancyselectData.value=res.data
  formData.value.日期=res.data[0].日期
  formData.value.关联人员工号=res.data[0].关联人员工号
  formData.value.关联人员姓名=res.data[0].关联人员姓名
  formData.value.日关联人数=res.data[0].日关联人数
  formData.value.日关联系数=res.data[0].日关联系数
  dialogFormVisible.value=true
  }
}
//员工编号回车事件
const getygsubmit = (event) => {
	   GetYg()  
}
//获取员工信息
const GetYg = async () => {
  const response = await getYg({sczl_bh:formData.value.关联人员工号});
  console.log(response) 
  if (response.code === 0) {
	console.log(response.data.ygxm) 
	formData.value.关联人员姓名=response.data.ygxm
  }
}
function onflushed() {
	Setting(formData.value.日期,formData.value.关联人员工号)
}

const relevancySelection=ref([])
//列表勾选
const relevancySelectionChange = (val) => {
     relevancySelection.value = val.map(item => {
          return {
            UniqID: item.UniqID,
          };
        });
		console.log(relevancySelection.value)
}
const copyselectData=ref([])
// 组员复制
const oncopy = () => {
  copyshow.value=true
}

//时间回车事件
const getcopylist = (event, inputName) => {
	  CopyLst()
}
//获取复制信息
const CopyLst = async () => {
  const response = await copyLst({date:formData.value.old_time});
  console.log(response) 
  if (response.code === 0) {
	copyselectData.value=response.data
  }
}
const copySelection=ref([])
//列表勾选
const copySelectionChange = (val) => {
       copySelection.value = val.map(item => {
          return {
            old_time:formData.value.old_time,
			new_time:formData.value.new_time,
            关联员工: item.员工编号
          };
        });
		console.log(copySelection.value)
}
const oncopyup = () => {
	
 Copy()
}
//提交数组
const Copy= async () => {
  const response = await copy(copySelection.value);
  console.log(response) 
  if (response.code === 0) {
	  copyshow.value=false
	  // batchaddselectData.value=response.data
	  // batchaddshow.value=true
  }
}
// 更新关联系数
const uprelevancy = () => {
  UpdateNum()
}
//更新关联系数
const UpdateNum = async () => {
  const response = await updateNum({date:formData.value.日期,code:formData.value.关联人员工号,num:formData.value.日关联系数});
  console.log(response) 
  if (response.code === 0) {
     // Setting(formData.value.日期,formData.value.关联人员工号)
	 tableData[rowIndex.value].关联系数=formData.value.日关联系数
	  console.log(); // Accessing the value of rowIndex
	 
  }
}
// 批量删除
const batchdel = () => {
  BatchDel()
}
//删除提交
const BatchDel = async () => {
  const response = await batchDel(relevancySelection.value);
  console.log(response) 
  if (response.code === 0) {
     Setting(formData.value.日期,formData.value.关联人员工号)
  }
}
//关联表格双击事件
const relevancySelectClick = (row, column, event) => {
	console.log(row.日期)
	console.log(row.班组员工编号)
    WeightDetail(row.日期,row.班组员工编号)
}
//获取关联员工信息
const WeightDetail = async (date,code) => {
  const response = await weightDetail({date:date,code:code.split("（")[0]});
  console.log(response.data[0].员工编号) 
  if (response.code === 0) {
	formData.value.员工编号=response.data[0].员工编号
	formData.value.姓名=response.data[0].姓名
	formData.value.部门名称=response.data[0].部门名称
	formData.value.职务=response.data[0].职务
	formData.value.入职日期=response.data[0].入职日期
	formData.value.关联权重=response.data[0].关联权重
	console.log(formData)
	positioningVisibleshow.value=true
  }
}


// 批量添加
const batchadd = () => {
	BatchAddLst()
  
}
const batchaddselectData=ref([])


//批量附加组员列表
const BatchAddLst = async () => {
  const response = await batchAddLst({date:formData.value.日期,code:formData.value.关联人员工号});
  console.log(response) 
  if (response.code === 0) {
	  batchaddselectData.value=response.data
	  batchaddshow.value=true
  }
}
// 查找
const oninvestigate = () => {
  BatchAddSearch()
}
//查找
const BatchAddSearch= async () => {
  const response = await batchAddSearch({date:formData.value.日期,search:formData.value.定位});
  console.log(response) 
  if (response.code === 0) {
	  batchaddselectData.value=response.data
	  // batchaddshow.value=true
  }
}
const batchaddSelection=ref([])
//列表勾选
const batchaddSelectionChange = (val) => {
     batchaddSelection.value = val.map(item => {
          return {
            UniqID: item.UniqID,
            关联员工: item.班组员工编号.split("（")[0]
          };
        });
		console.log(batchaddSelection.value)
}
//提交
const batchup = () => {
	
 BatchAdd()
}
//提交数组
const BatchAdd= async () => {
  const response = await batchAdd(batchaddSelection.value);
  console.log(response) 
  if (response.code === 0) {
	  Setting(formData.value.日期,formData.value.关联人员工号)
	  batchaddshow.value=false
	  // batchaddselectData.value=response.data
	  // batchaddshow.value=true
  }
}

// 搜索
function onSearch() {
console.log(searchInfo.value)
Relatedsearch()
}
//定位
const fillTableData = (data) => {
  // Fill the table data
  tableData.splice(0, tableData.length, ...data);
};

const Relatedsearch = async () => {
  const response = await relatedsearch({
    date: params.date,
    search: searchInfo.value
  });
  console.log(response);
  if (response.code === 0) {
    const filledData = response.data.map((item) => {
      // Handle empty values for "个人计件工资" and "个人加班工资"
      if (item["个人计件工资"] === "") {
        item["个人计件工资"] = "0";
      }
      if (item["个人加班工资"] === "") {
        item["个人加班工资"] = "0";
      }
      return item;
    });

    // Update table data using await to ensure data is updated before proceeding
    await fillTableData(filledData);
  }
};
// ============== 表格控制部分结束 ===============

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

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

// 多选数据
const multipleSelection = ref([])
let code=ref()
let time=ref()
// 多选
const handleSelectionChange = (val,row) => {
  // multipleSelection.value = val
  console.log(val)
  console.log(row)
  if(val.length>0){
  	multipleSelection.value = val
  	const lenth=val.length
  	code=val[lenth-1].员工编号
	time=val[lenth-1].日期
	formData.value.员工编号=val[lenth-1].员工编号,
	formData.value.员工姓名= val[lenth-1].员工姓名,
	formData.value.日期=val[lenth-1].日期,
	formData.value.关联系数= val[lenth-1].关联系数,
	formData.value.关联人数= val[lenth-1].关联人数
  	val.splice(0, val.length);  // 清空 val 数组	
  	console.log(code+time)
  }
}

// 批量删除控制标记
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 positioningVisibleshow = ref(false)
const weightDetailVisible = ref(false)
const batchaddshow = ref(false)
const copyshow = ref(false)


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

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    address: '',
    image: '',
    name: '',
  }
}
// 弹窗确定
const enterDialog = async () => {
  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()
    }
  })
}
// 单击表格操作
const rowIndex=ref()
function ontable(row, column, event) {
  // console.log(params.date)
  // let parts = params.date.split('-')
  // console.log(row.员工编号)
  // RelatedAllList(params.date,row.员工编号)
  // console.log(formData);
  console.log(row)
  code.value=row.员工编号
  time.value=row.日期
  console.log(code.value+time.value)
  rowIndex.value = tableData.indexOf(row);
  console.log('单击的行数：', rowIndex.value);
}
let temporary = {
  员工编号: '',
  员工姓名: '',
  日期: '',
  关联系数: '',
  关联人数: ''
};
//获取下列表
const RelatedAllList = async (date,bh) => {
  const response = await relatedAllList({date:date,code:bh});
  if(response.code==0){
	  console.log(response)
	   tableData2.splice(0, tableData2.length, ...response.data);
  }
}
// 双击表格操作
function doubleClick(row, column, event) {
  // console.log(row, column, event);
  // // updateCompanyFunc(row);
  // type.value = 'update';
  // dialogFormVisible.value = true
  Setting(time.value,code.value)
}

// 导出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>