<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"
          />
        </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"
                  style="width: 150px;"
                  placeholder="输入工单编号"
                />
              </el-row>
              <el-button
                type="primary"
                :icon="Search"
                @click="handleSearch"
              >搜索
              </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"
              @row-dblclick="doubleClick"
            >
              <el-table-column
                type="selection"
                width="55"
              />
              <!-- 循环渲染列 -->
              <el-table-column
                v-for=" column in tableColumns "
                :key="column.prop"
                :prop="column.prop"
                :label="column.label"
                :width="column.width"
                show-overflow-tooltip="true"
              />
            </el-table>
            <!-- 分页 -->
            <div class="gva-pagination">
              <el-pagination
                v-model:current-page="page"
                v-model:page-size="limit"
                layout="total, sizes, prev, pager, next, jumper"
                :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-form
              ref="elFormRef"
              :model="detailData"
              inline="true"
              label-position="left"
              :rules="rule"
            >
              <el-form-item label="日期">
                <el-input
                  v-model="detailData.sczl_rq"
                  style="width: 120px;"
                />
              </el-form-item>
              <el-form-item label="员工编号">
                <el-input
                  v-model="detailData.sczl_bh"
                  style="width: 100px;"
                />
                <el-input
                  v-model="detailData.name"
                  style="width: 100px; padding-left: 5px;"
                />
              </el-form-item>
              <el-form-item label="组别">
                <el-input
                  v-model="detailData.sczl_bzdh"
                  style="width: 50px;"
                />
              </el-form-item>
              <br>
              <el-form-item
                label="计时时数"
                style="padding-left: 195px;"
              >
                <el-input
                  v-model="detailData.sczl_jsss"
                  style="width: 100px;"
                />
              </el-form-item>
              <el-form-item label="冲月定额">
                <el-input
                  v-model="detailData.sczl_冲定额"
                  style="width: 50px;"
                />
              </el-form-item>

              <el-table
                :data="detailData.table"
                border
                tooltip-effect="dark"
                :row-style="{ height: '20px' }"
                :cell-style="{ padding: '0px' }"
                :header-row-style="{ height: '20px' }"
                :header-cell-style="{ padding: '0px' }"
              >
                <el-table-column
                  label="工单编号"
                  width="100"
                >
                  <template #default="{ row, $index }">
                    <el-input
                      v-model="row.sczl_gdbh"
                      @keyup.enter="handleEnter($index, row)"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="印件工序"
                  width="100"
                >
                  <template #default="{ row }">
                    <el-input v-model="row.sczl_yjGx" />
                  </template>
                </el-table-column>
                <el-table-column
                  label="工序名称"
                  width="100"
                >
                  <template #default="{ row }">
                    <el-input v-model="row.sczl_gxmc" />
                  </template>
                </el-table-column>
                <el-table-column label="印件名称">
                  <template #default="{ row }">
                    <el-input v-model="row.Gd_cpmc" />
                  </template>
                </el-table-column>
                <el-table-column
                  label="包装产量"
                  width="100"
                >
                  <template #default="{ row }">
                    <el-input v-model="row.sczl_cl" />
                  </template>
                </el-table-column>
                <el-table-column
                  label="返工产量"
                  width="100"
                >
                  <template #default="{ row }">
                    <el-input v-model="row.sczl_返工产量" />
                  </template>
                </el-table-column>
                <el-table-column
                  label="每箱数量"
                  width="100"
                >
                  <template #default="{ row }">
                    <el-input v-model="row.sczl_PgCl" />
                  </template>
                </el-table-column>
                <el-table-column
                  label="计产系数"
                  width="100"
                >
                  <template #default="{ row }">
                    <el-input v-model="row.sczl_计产系数" />
                  </template>
                </el-table-column>
                <el-table-column
                  label="来源"
                  width="100"
                >
                  <template #default="{ row }">
                    <el-input v-model="row.sczl_Jtbh1" />
                  </template>
                </el-table-column>
                <el-table-column
                  label="定额代号"
                  width="100"
                >
                  <template #default="{ row }">
                    <el-input v-model="row.sczl_dedh" />
                  </template>
                </el-table-column>
              </el-table>

              <el-form-item
                label="其他备注"
                style="margin-top: 10px;"
              >
                <el-input v-model="detailData.sczl_desc" />
              </el-form-item>

            </el-form>

            <!-- <el-form :model="form" inline="true" label-position="left" ref="elFormRef1" :rules="rule">
              <el-form-item label="日期">
                <el-input v-model="form.sczl_rq" style="width: 120px;" />
              </el-form-item>
              <el-form-item label="员工编号">
                <el-input v-model="form.sczl_bh" style="width: 100px;" />
                <el-input v-model="form.name" style="width: 100px; padding-left: 5px;" />
              </el-form-item>
              <el-form-item label="组别">
                <el-input v-model="form.sczl_bzdh" style="width: 50px;" />
              </el-form-item>
              <br>
              <el-form-item label="计时时数" style="padding-left: 195px;">
                <el-input v-model="form.sczl_jsss" style="width: 100px;" />
              </el-form-item>
              <el-form-item label="冲月定额">
                <el-input v-model="form.sczl_冲定额" style="width: 50px;" />
              </el-form-item>
              <br>
            </el-form>

            <el-form :model="form" inline="true" label-position="top" ref="elFormRef2" :rules="rule">
              <el-form-item label="工单编号">
                <div style="width: 150px;">
                  <el-input v-model="form.sczl_rq" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                </div>
              </el-form-item>

              <el-form-item label="工单编号">
                <div style="width: 150px;">
                  <el-input v-model="form.sczl_rq" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                </div>
              </el-form-item>
              <el-form-item label="工单编号">
                <div style="width: 150px;">
                  <el-input v-model="form.sczl_rq" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                </div>
              </el-form-item>

              <el-form-item label="工单编号">
                <div style="width: 150px;">
                  <el-input v-model="form.sczl_rq" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                </div>
              </el-form-item>

              <el-form-item label="工单编号">
                <div style="width: 150px;">
                  <el-input v-model="form.sczl_rq" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                </div>
              </el-form-item>

              <el-form-item label="工单编号">
                <div style="width: 150px;">
                  <el-input v-model="form.sczl_rq" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                </div>
              </el-form-item>

              <el-form-item label="工单编号">
                <div style="width: 150px;">
                  <el-input v-model="form.sczl_rq" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                </div>
              </el-form-item>
              <el-form-item label="工单编号">
                <div style="width: 150px;">
                  <el-input v-model="form.sczl_rq" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                </div>
              </el-form-item>

              <el-form-item label="工单编号">
                <div style="width: 150px;">
                  <el-input v-model="form.sczl_rq" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                </div>
              </el-form-item>

              <el-form-item label="工单编号">
                <div style="width: 150px;">
                  <el-input v-model="form.sczl_rq" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                  <el-input v-model="form.sczl_rq" style="margin-top: 5px;" />
                </div>
              </el-form-item>
            </el-form> -->

            <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="dialogSelectVisible"
            title="选择"
            destroy-on-close
            width="600px"
          >
            <el-table
              tooltip-effect="dark"
              :data="selectData"
              row-key="ID"
              highlight-current-row="true"
              border
              style="width:100%"
              @row-dblclick="handleSelectClick"
            >
              <el-table-column
                prop="Gd_cpmc"
                label="产品名称"
                width="300"
              />
              <el-table-column
                prop="Gy0_gxmc"
                label="产品名称"
                width="100"
              />
              <el-table-column
                prop="jyGx"
                label="产品名称"
                width="100"
              />
            </el-table>
          </el-dialog>

        </el-main>
      </el-container>
    </el-container>

  </div>
</template>

<script setup>
import { createCompany, deleteCompanyByIds, updateCompany } from '@/api/company'

// 全量引入格式化工具 请按需保留
import { ElMessage } from 'element-plus'
import { Download, Search } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import { getGxMc, getInfo, getLocate, getPackingSideTable, getPackingTable } from '@/api/mes_api_gty/myapi'

defineOptions({
  name: '06PackingDocuments',
})

// 侧边栏数据
const treeData = reactive([])
const getSideData = async() => {
  const response = await getPackingSideTable()
  if (response.code === 0) {
    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,
        },
      })),
    }))
    treeData.splice(0, treeData.length, ...transformedData)
  }
}

getSideData()

// 自动化生成的字典（可能为空）以及字段
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 tableColumns = [
  { label: '员工编号', prop: 'sczl_bh', width: '100' },
  { label: '员工姓名', prop: 'name', width: '100' },
  { label: '生产日期', prop: 'sczl_rq', width: '100' },
  { label: '班组', prop: 'sczl_bzdh', width: '100' },
  { label: '包装产量', prop: 'sczl_cl', width: '100' },
  { label: '返工产量', prop: 'sczl_fgsl', width: '100' },
  { label: '计件产量', prop: 'sczl_jjcl', width: '100' },
  { label: '相关工单', prop: 'sczl_gdbh1', width: '100' },
  { label: '创建用户', prop: 'sys_id', width: '120' },
  { label: '创建时间', prop: 'sys_rq', width: '180' },
  { label: '修改时间', prop: 'mod_rq', width: '180' },
  { label: 'UNIQID', prop: 'UniqId', width: '100' },
]
const tableData = reactive([])

const total = ref(0)
const page = ref(1)
const limit = ref(10)

const searchInfo = ref('')
const params = {
  type: '',
  date: '',
  sys_id: '',
  gdbh: '',
}

// 获取列表数据
const getTableData = async() => {
  const response = await getPackingTable({
    date: params.date, sys_id: params.sys_id,
    page: page.value.toString(), limit: limit.value.toString(),
  })
  if (response.code === 0) {
    total.value = response.data.total
    tableData.splice(0, tableData.length, ...response.data.rows)
  }
}

// 获取定位数据
const getLocateTable = async() => {
  const response = await getLocate({
    gdbh: params.gdbh,
    page: page.value.toString(), limit: limit.value.toString(),
  })
  if (response.code === 0) {
    total.value = response.data.total
    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
    params.type = 'getTableData'
    page.value = 1
    getTableData()
  }
}

// 定位
function handleSearch() {
  console.log(searchInfo.value)
  params.gdbh = searchInfo.value
  params.type = 'getLocateTable'
  page.value = 1
  getLocateTable()
}

// 分页设置
const handleSizeChange = () => {
  switch (params.type) {
    case 'getTableData':
      getTableData()
      break
    case 'getLocateTable':
      getLocateTable()
      break
    default:
      break
  }
}

// 页面跳转
const handleCurrentChange = () => {
  switch (params.type) {
    case 'getTableData':
      getTableData()
      break
    case 'getLocateTable':
      getLocateTable()
      break
    default:
      break
  }
}

// ============== 详情页面 ==============
const detailData = reactive({
  sczl_rq: '',
  sczl_bh: '',
  name: '',
  sczl_bzdh: '',
  sczl_jsss: '',
  sczl_冲定额: '',
  sczl_desc: '',
  table: [],
})
const selectData = reactive([
  {
    Gd_cpmc: '黄金叶（乐途硬）小盒（二维码改版）',
    Gy0_gxmc: '包装',
    jyGx: '01-71',
  },
])
let tableIndex = 0

// 获取详细信息
const getTableInfo = async(id) => {
  const response = await getInfo({ UniqId: id })
  if (response.code === 0) {
    const { sczl_rq, sczl_bh, name, sczl_bzdh, sczl_jsss, sczl_冲定额, sczl_desc, ...rest } = response.data
    // 直接赋值基础属性
    Object.assign(detailData, { sczl_rq, sczl_bh, name, sczl_bzdh, sczl_jsss, sczl_冲定额, sczl_desc })
    // 生成表格数据
    detailData.table = Array.from({ length: 6 }, (_, i) => i + 1) // 创建一个长度为6的数组 [1, 2, 3, 4, 5, 6]
      .map(num => {
        return {
          sczl_gdbh: rest[`sczl_gdbh${num}`],
          sczl_yjGx: rest[`sczl_yjGx${num}`],
          sczl_gxmc: rest[`sczl_gxmc${num}`],
          Gd_cpmc: rest[`Gd_cpmc${num}`],
          sczl_cl: rest[`sczl_cl${num}`],
          sczl_返工产量: rest[`sczl_返工产量${num}`],
          sczl_PgCl: rest[`sczl_PgCl${num}`],
          sczl_计产系数: rest[`sczl_计产系数${num}`],
          sczl_Jtbh1: rest[`sczl_Jtbh${num}`],
          sczl_dedh: rest[`sczl_dedh${num}`],
        }
      })
      .filter(item => item.sczl_gdbh !== '') // 过滤掉空的工单编号
    dialogFormVisible.value = true
  }
}

// 双击表格操作
function doubleClick(row, column, event) {
  type.value = 'update'
  getTableInfo(row.UniqId)
}

// 处理回车
const handleEnter = (index, row) => {
  getTableGxMc(index, row)
}

// 获取详细信息
const getTableGxMc = async(index, row) => {
  console.log(row)
  const response = await getGxMc({ gdbh: row.sczl_gdbh })
  if (response.code === 0) {
    const { Gd_cpmc, Gy0_gxmc, jyGx } = response.data[0]
    if (response.data.length === 1) {
      detailData.table[index].Gd_cpmc = Gd_cpmc
      detailData.table[index].sczl_yjGx = jyGx
      detailData.table[index].sczl_gxmc = Gy0_gxmc
    } else {
      selectData.splice(0, selectData.length, ...response.data)
      tableIndex = index
      dialogSelectVisible.value = true
    }
  }
}

// 处理选择框
const handleSelectClick = (row, column, event) => {
  const { Gd_cpmc, Gy0_gxmc, jyGx } = row
  detailData.table[tableIndex].Gd_cpmc = Gd_cpmc
  detailData.table[tableIndex].sczl_yjGx = jyGx
  detailData.table[tableIndex].sczl_gxmc = Gy0_gxmc
  dialogSelectVisible.value = false
}

// 多选数据
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 dialogSelectVisible = ref(false)

// 关闭弹窗
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()
    }
  })
}

// 导出excel
function exportExcel() {
  console.log('导出到excel')
}

// 生命周期钩子

</script>

<style scoped>
.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;
}

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