<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" :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="bh" width="120"/>
              <el-table-column align="left" sortable label="员工姓名" prop="员工姓名" width="120"/>
              <el-table-column align="left" sortable label="日期" prop="sczl_rq" 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%" 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="sczl_rq" width="120"/>
		      <el-table-column align="left" sortable label="工单编号" prop="sczl_gdbh" width="120"/>
		      <el-table-column align="left" sortable label="产品名称" prop="Gd_cpmc" width="120"/>
		      <el-table-column align="left" sortable label="印件及工序" prop="sczl_type" width="120"/>
		      <el-table-column align="left" sortable label="机台编号" prop="sczl_jtbh" 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-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-column align="left" sortable label="员工编号" prop="bh" width="160"/>
			  <el-table-column align="left" sortable label="姓名" prop="xm" width="120"/>
			  <el-table-column align="left" sortable label="比例" prop="Rate" 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.code" :clearable="true" placeholder="ZT01733" />
                      </el-col>
                    </el-row>
                  </el-form-item>
                </el-col>
              </el-row>

                            <!-- 标题栏 -->
                            <el-row :gutter="10">
                              <el-col :span="3">
                                <span>工单编号</span>
                              </el-col>
                              <el-col :span="3">
                                <span>印件工序</span>
                              </el-col>
                              <el-col :span="3">
                                <span>工序名称</span>
                              </el-col>
                              <el-col :span="9">
                                <span>印件名称</span>
                              </el-col>
                              <el-col :span="2">
                                <span>包装产量</span>
                              </el-col>
							  <el-col :span="2">
							    <span>每箱数量</span>
							  </el-col>
							  <el-col :span="2">
							    <span>零头</span>
							  </el-col>
                            </el-row>
              
                            <!-- 员工1 -->
                            <el-row :gutter="5" style="margin-top: 10px;">
                              <el-col :span="3">
                                <el-input v-model="formData.image" :clearable="true" placeholder="ZI00401" />
                              </el-col>
                              <el-col :span="3">
                                <el-input v-model="formData.image" :clearable="true" placeholder="瞿春生" />
                              </el-col>
                              <el-col :span="3">
                                <el-input v-model="formData.image" :clearable="true" placeholder="11.0" />
                              </el-col>
                              <el-col :span="9">
                                <el-input v-model="formData.image" :clearable="true" placeholder="打包废纸" />
                              </el-col>
                              <el-col :span="2">
                                <el-input v-model="formData.image" :clearable="true" placeholder="是" />
                              </el-col>
							  <el-col :span="2">
							    <el-input v-model="formData.image" :clearable="true" placeholder="是" />
							  </el-col>
							  <el-col :span="2">
							    <el-input v-model="formData.image" :clearable="true" placeholder="是" />
							  </el-col>
                            </el-row>
              
                            <!-- 员工2 -->
                            <el-row :gutter="5" style="margin-top: 10px;">
                              <el-col :span="3">
                                <el-input v-model="formData.image" :clearable="true" placeholder="ZI00401" />
                              </el-col>
                              <el-col :span="3">
                                <el-input v-model="formData.image" :clearable="true" placeholder="瞿春生" />
                              </el-col>
                              <el-col :span="3">
                                <el-input v-model="formData.image" :clearable="true" placeholder="11.0" />
                              </el-col>
                              <el-col :span="9">
                                <el-input v-model="formData.image" :clearable="true" placeholder="打包废纸" />
                              </el-col>
                              <el-col :span="2">
                                <el-input v-model="formData.image" :clearable="true" placeholder="是" />
                              </el-col>
							  <el-col :span="2">
							    <el-input v-model="formData.image" :clearable="true" placeholder="是" />
							  </el-col>
							  <el-col :span="2">
							    <el-input v-model="formData.image" :clearable="true" placeholder="是" />
							  </el-col>
                            </el-row>
              
                            <!-- 员工3 -->
                            <el-row :gutter="5" style="margin-top: 10px;">
                              <el-col :span="3">
                                <el-input v-model="formData.image" :clearable="true" placeholder="ZI00401" />
                              </el-col>
                              <el-col :span="3">
                                <el-input v-model="formData.image" :clearable="true" placeholder="瞿春生" />
                              </el-col>
                              <el-col :span="3">
                                <el-input v-model="formData.image" :clearable="true" placeholder="11.0" />
                              </el-col>
                              <el-col :span="9">
                                <el-input v-model="formData.image" :clearable="true" placeholder="打包废纸" />
                              </el-col>
                              <el-col :span="2">
                                <el-input v-model="formData.image" :clearable="true" placeholder="是" />
                              </el-col>
							  <el-col :span="2">
							    <el-input v-model="formData.image" :clearable="true" placeholder="是" />
							  </el-col>
							  <el-col :span="2">
							    <el-input v-model="formData.image" :clearable="true" placeholder="是" />
							  </el-col>
                            </el-row>
              
                            <!-- 员工4 -->
                            <el-row :gutter="5" style="margin-top: 10px;">
                              <el-col :span="3">
                                <el-input v-model="formData.image" :clearable="true" placeholder="ZI00401" />
                              </el-col>
                              <el-col :span="3">
                                <el-input v-model="formData.image" :clearable="true" placeholder="瞿春生" />
                              </el-col>
                              <el-col :span="3">
                                <el-input v-model="formData.image" :clearable="true" placeholder="11.0" />
                              </el-col>
                              <el-col :span="9">
                                <el-input v-model="formData.image" :clearable="true" placeholder="打包废纸" />
                              </el-col>
                              <el-col :span="2">
                                <el-input v-model="formData.image" :clearable="true" placeholder="是" />
                              </el-col>
							  <el-col :span="2">
							    <el-input v-model="formData.image" :clearable="true" placeholder="是" />
							  </el-col>
							  <el-col :span="2">
							    <el-input v-model="formData.image" :clearable="true" placeholder="是" />
							  </el-col>
                            </el-row>
              
                            <!-- 员工5 -->
                            <el-row :gutter="5" style="margin-top: 10px;">
                              <el-col :span="3">
                                <el-input v-model="formData.image" :clearable="true" placeholder="ZI00401" />
                              </el-col>
                              <el-col :span="3">
                                <el-input v-model="formData.image" :clearable="true" placeholder="瞿春生" />
                              </el-col>
                              <el-col :span="3">
                                <el-input v-model="formData.image" :clearable="true" placeholder="11.0" />
                              </el-col>
                              <el-col :span="9">
                                <el-input v-model="formData.image" :clearable="true" placeholder="打包废纸" />
                              </el-col>
                              <el-col :span="2">
                                <el-input v-model="formData.image" :clearable="true" placeholder="是" />
                              </el-col>
							  <el-col :span="2">
							    <el-input v-model="formData.image" :clearable="true" placeholder="是" />
							  </el-col>
							  <el-col :span="2">
							    <el-input v-model="formData.image" :clearable="true" placeholder="是" />
							  </el-col>
                            </el-row>
              
                            <!-- 员工6 -->
                            <el-row :gutter="5" style="margin-top: 10px;">
                              <el-col :span="3">
                                <el-input v-model="formData.image" :clearable="true" placeholder="ZI00401" />
                              </el-col>
                              <el-col :span="3">
                                <el-input v-model="formData.image" :clearable="true" placeholder="瞿春生" />
                              </el-col>
                              <el-col :span="3">
                                <el-input v-model="formData.image" :clearable="true" placeholder="11.0" />
                              </el-col>
                              <el-col :span="9">
                                <el-input v-model="formData.image" :clearable="true" placeholder="打包废纸" />
                              </el-col>
                              <el-col :span="2">
                                <el-input v-model="formData.image" :clearable="true" placeholder="是" />
                              </el-col>
							  <el-col :span="2">
							    <el-input v-model="formData.image" :clearable="true" placeholder="是" />
							  </el-col>
							  <el-col :span="2">
							    <el-input v-model="formData.image" :clearable="true" placeholder="是" />
							  </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="positioningVisibleshow" :before-close="closepositioningVisible" :title="type==='create'?'添加':'修改'" destroy-on-close>
            <el-card>
          				<el-form-item label="员工编号" prop="name">
          				  <el-row :gutter="20">
          				    <el-col :span="12">
          				      <el-input v-model="positionvalue" :clearable="true" placeholder="ZT01733" />
          				    </el-col>                      
          				  </el-row>
          				</el-form-item>
          			</el-card>
          			<el-button type="primary" @click="enterpositioning">确 定</el-button>
          </el-dialog>
         
        </el-main>
      </el-container>
    </el-container>

  </div>
</template>

<script setup>
import {
  getList,
  getTab,
  dailygetTab,
  dailygetList,
  dailygetAllList,
  dailygetDetail,
  dailysearch
} 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 dailygetTab();
	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);

	
	}
	

getTabdata();

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
  id: '',
  name: '',
  date: '',
  group: '',
  packingOutput: '',
  reworkOutput: '',
  pieceOutput: '',
  order: '',
  user: '',
  createTime: '',
  updateTime: '',
  uniqid: '',
})

// 验证规则
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 dailygetList({
	  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) => {
    const name = item['员工姓名'].trim(); // 获取员工姓名并去除空格
    if (name !== currentName) {
      // 如果员工姓名发生改变，说明需要插入合计数据
      if (currentSummary) {
        // 将上一个员工的合计数据插入到数组中
        summaryData.push(currentSummary);
      }
      // 创建新的合计数据
      currentSummary = {
        '员工姓名': name,
        '日期': 0,
        '计件工资': 0,
        '加班工资': 0,
        '日工资合计': 0
      };
      currentName = name;
    }

    // 更新合计数据
	
    currentSummary['日期']++;
    currentSummary['计件工资'] += parseFloat(item['计件工资']);
    currentSummary['加班工资'] += parseFloat(item['加班工资']);
    currentSummary['日工资合计'] += parseFloat(item['日工资合计']);
	currentSummary['员工姓名']='合计（'+currentSummary['日期']+'天）';
  });

  // 将最后一个员工的合计数据插入到数组中
  if (currentSummary) {
    summaryData.push(currentSummary);
  }

  // 将日期填充到表格中
  summaryData.forEach((summary) => {
    summary['计件工资'] = summary['计件工资'].toFixed(2); // 保留两位小数
	summary['加班工资'] = summary['加班工资'].toFixed(2);
	summary['日工资合计'] = summary['日工资合计'].toFixed(2);
  });

  return summaryData;
};
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;
    getTableData();
  }
}

// 定位
function onposition() {
  positioningVisibleshow.value=true
}
const enterpositioning = async () => {
 console.log(params.date)
 let parts = params.date.split('-')
 
 // # 截取第一个"-"之前的内容并赋值给新变量1
 let new_variable1 = parts[0]
 console.log(new_variable1)
 
 // # 截取第一个"-"之后到第二个"-"之前的内容并赋值给新变量2
 let new_variable2 = parts[1]
 console.log(new_variable1+new_variable2) 
 Getlocate(new_variable1+new_variable2)
 positioningVisibleshow.value=false
}
let positionvalue=ref()
const Getlocate = async (value) => {
  
  // const response = await locate(locatevalue);
  // console.log(locatevalue)
  // console.log(response)
  // if (response.code === 0) {
  //   tableData.splice(0, tableData.length, ...response.data.rows);
  // }
  const response = await dailysearch({
    date: value,
    search:positionvalue.value
  })
  if (response.code === 0) {
	console.log(params.data+positionvalue.value)
    tableData.splice(0, tableData.length, ...response.data)
  }
  console.log(response)
  console.log(params.data+positionvalue.value)
}
// 搜索
function onSearch() {

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

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

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

// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
  // multipleSelection.value = val
  
}

// 批量删除控制标记
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 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()
    }
  })
}
// 单击表格操作
function ontable(row, column, event) {
  console.log(params.date)
  let parts = params.date.split('-')
  
  // # 截取第一个"-"之前的内容并赋值给新变量1
  let new_variable1 = parts[0]
  console.log(new_variable1)
  
  // # 截取第一个"-"之后到第二个"-"之前的内容并赋值给新变量2
  let new_variable2 = parts[1]
  console.log(new_variable1+new_variable2) 
  console.log(new_variable1)
  console.log(row.bh)
  Getundertable(new_variable1,row.bh)
}
//获取下列表
const Getundertable = async (date,bh) => {
  const response = await dailygetAllList({date:date,code:bh});
  if(response.code==0){
	  console.log(response)
	   tableData2.splice(0, tableData2.length, ...response.data);
	// console.log(response.data.num)
	// const rowIndex = tableData.findIndex(row => row.UniqId === lastCellValue);
	// console.log(rowIndex)
	// tableData[rowIndex].sczl_废品率系数 = response.data.num;
  }
  // console.log(response)
  // const rowIndex = tableData.findIndex(row => row.UniqId === 123);
}
// 双击表格操作
function doubleClick(row, column, event) {
  console.log(row, column, event);
  // updateCompanyFunc(row);
  type.value = 'update';
  dialogFormVisible.value = true
}

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