<template>
  <div>
    <layout>
      <layout-header>
        <!-- 按钮 -->
        <el-form inline>
          <el-form-item>
            <el-input
              v-model="searchInfo"
              placeholder="搜索产品编号或产品名称"
              clearable
              style="width: 180px;"
            />
            <el-button
              type="primary"
              icon="Search"
              class="search"
              @click="handleSearch"
            />

            <el-button
              type="primary"
              icon="edit"
              class="bt"
              @click="handleShowDetail"
            ><i class="el-icon-edit" />查改
            </el-button>

            <el-button
              type="primary"
              icon="edit"
              class="bt"
              @click="handleShowAdd"
            >新增
            </el-button>

            <el-button
              type="primary"
              icon="delete"
              class="bt"
              @click="handleDelete"
            >删除
            </el-button>

          </el-form-item>
        </el-form>

        <!-- 弹出框 -->
        <div>
          <el-dialog
            v-model="dialogFormVisible"
            :title="type"
            destroy-on-close
            width="1200px"
          >

            <el-form
              id="detail-form"
              :model="detailData"
              inline
              label-position="left"
              @keyup="moveFocus"
            >
              <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;"
				   @click="selectvalue($event)"
                  readonly
                />
              </el-form-item>
              <el-form-item label="组别">
                <el-select
                  v-model="detailData.sczl_bzdh"
                  placeholder=" "
                  style="width: 80px"
                >
                  <el-option
                    label="A班"
                    value="A班"
                  />
                  <el-option
                    label="B班"
                    value="B班"
                  />

                </el-select></el-form-item>
              <br>
              <el-form-item
                label="计时时数"
                style="padding-left: 195px;"
              >
                <el-input
                  v-model="detailData.sczl_jsss"
                  style="width: 100px;"
				  @click="selectvalue($event)"
                />
              </el-form-item>
              <el-form-item label="冲月定额">
                <el-select
                  v-model="detailData.sczl_冲定额"
                  placeholder=" "
                  style="width: 100px"
                >
                  <el-option
                    label=""
                    value=""
                  />
                  <el-option
                    label="是"
                    value="是"
                  />

                </el-select>
              </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"
                      readonly
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="工序名称"
                  width="100"
                >
                  <template #default="{ row }">
                    <el-input
                      v-model="row.sczl_gxmc"
                      readonly
                    />
                  </template>
                </el-table-column>
                <el-table-column label="印件名称">
                  <template #default="{ row }">
                    <el-input
                      v-model="row.Gd_cpmc"
                      readonly
                    />
                  </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"
                      @keyup.enter.native="getDedhsubmit"
                    />
                  </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>

            <template #footer>
              <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</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
              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>
        </div>

      </layout-header>

      <layout>
        <!--    左侧树侧形结构-->
        <layout-sider
          :resize-directions="['right']"
          :width="220"
          style="margin-right: 10px;"
        >
          <div
            class="JKWTree-tree"
            style="height: 70vh;"
          >
            <h3>包装计件单据维护</h3>
            <el-tree
              :data="treeData"
              highlight-current
              @node-click="handleNodeClick"
            />
          </div>
        </layout-sider>

        <layout-content>
          <!-- 数据展示 -->
          <div class="gva-table-box">
            <el-table
              ref="table"
              style="width: 100%"
              :data="tableData"
              row-key="ID"
              highlight-current-row
              border
              show-overflow-tooltip
              :row-style="{ height: '20px' }"
              :cell-style="{ padding: '0px' }"
              :header-row-style="{ height: '20px' }"
              :header-cell-style="{ padding: '0px' }"
              @row-dblclick="handleShowDetail"
              @current-change="(row, oldRow) => { currentRow = row}"
            >
              <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"
				sortable
              />
            </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>
        </layout-content>
      </layout>
    </layout>

  </div>
</template>

<script setup>
import { Layout, LayoutContent, LayoutHeader, LayoutSider } from '@arco-design/web-vue'
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'

// import { Download, Search, Delete } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import { getGxMc, getInfo, getLocate, getPackingSideTable, getPackingTable, updatePackingTable, getYg, DeletePackingTable, addPackingTable, getDedh } from '@/api/mes_api_gty/myapi'

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

// 侧边栏功能
const treeData = reactive([])
const getSideData = async() => {
  try {
    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)
    }
  } catch (e) {
    console.log(e)
  }
}
getSideData()

// 表格功能
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 params = {
  type: '',
  date: '',
  sys_id: '',
  gdbh: '',
}

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

const type = ref('')
const searchInfo = ref('')
const currentRow = ref({})
// const multipleSelection = ref([])

// 获取列表数据
const getTableData = async() => {
  try {
    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)
      setCurrent(tableData[0])
    }
  } catch (e) {
    console.log(e)
  }
}
// 获取定位数据
const getLocateTable = async() => {
  try {
    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)
    }
  } catch (e) {
    console.log(e)
  }
}
// 删除数据
const deleteTableData = async(id) => {
  try {
    const res = await DeletePackingTable({ UniqId: id })
    if (res.code === 0) {
      return 0
    }
  } catch (e) {
    console.log(e)
  }
}

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()
  }
}

const selectvalue = (e) => {
 console.log(e)
 e.currentTarget.select();
}
// 定位
const handleSearch = () => {
  params.gdbh = searchInfo.value
  params.type = 'getLocateTable'
  page.value = 1
  getLocateTable()
}

// 查改
const handleShowDetail = () => {
  type.value = '查改'
  getTableInfo(currentRow.value?.UniqId)
}

// 删除
const handleDelete = () => {
  console.log(currentRow.value)
  ElMessageBox.confirm(
    `确认删除这条数据么?`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      const ret = await deleteTableData(currentRow.value?.UniqId)
      console.log(ret)
      if (ret === 0) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      } else {
        ElMessage({
          type: 'error',
          message: '删除失败',
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
// 分页
// #region
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
  }
}
// #endregion

// 详情界面
const detailData = reactive({
  UniqId: '',
  selectIndex: 0,
  sczl_rq: '',
  sczl_bh: '',
  name: '',
  sczl_bzdh: '',
  sczl_jsss: '',
  sczl_冲定额: '',
  sczl_desc: '',
  table: [],
})
const selectData = reactive([])
const table = ref()

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

const setCurrent = (row) => {
  table.value?.setCurrentRow(row)
}

// 获取详细信息
const getTableInfo = async(id) => {
  try {
    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 !== '') // 过滤掉空的工单编号
      detailData.UniqId = id
      dialogFormVisible.value = true

      // 在 setTimeout 中获取元素，确保在 DOM 渲染完毕后执行
      setTimeout(() => {
        formElements = document.getElementById('detail-form').elements
        formElements[0].focus()
      }, 0)
    }
  } catch (e) {
    console.log(e)
  }
}

// 获取工序名称
const getTableGxMc = async(index, row) => {
  try {
    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)
        detailData.selectIndex = index
        dialogSelectVisible.value = true
      }
    }
  } catch (e) {
    console.log(e)
  }
}

// 更新数据
const updateDetailData = async() => {
  const restoredData = {
    UniqId: detailData.UniqId,
    sczl_rq: detailData.sczl_rq,
    sczl_bh: detailData.sczl_bh,
    name: detailData.name,
    sczl_bzdh: detailData.sczl_bzdh,
    sczl_jsss: detailData.sczl_jsss,
    sczl_冲定额: detailData.sczl_冲定额,
    sczl_desc: detailData.sczl_desc,
  }
  detailData.table.forEach((item, index, array) => {
    const num = index + 1
    restoredData[`sczl_gdbh${num}`] = item.sczl_gdbh
    restoredData[`sczl_yjGx${num}`] = item.sczl_yjGx
    restoredData[`sczl_gxmc${num}`] = item.sczl_gxmc
    restoredData[`Gd_cpmc${num}`] = item.Gd_cpmc
    restoredData[`sczl_cl${num}`] = item.sczl_cl
    restoredData[`sczl_返工产量${num}`] = item.sczl_返工产量
    restoredData[`sczl_PgCl${num}`] = item.sczl_PgCl
    restoredData[`sczl_计产系数${num}`] = item.sczl_计产系数
    restoredData[`sczl_Jtbh${num}`] = item.sczl_Jtbh1
    restoredData[`sczl_dedh${num}`] = item.sczl_dedh
  })
  const res = await updatePackingTable(restoredData)
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '更新成功',
    })
    dialogFormVisible.value = false
  }
}

// 新增数据
const handleShowAdd = async() => {
  type.value = '新增'
  await getTableInfo(currentRow.value?.UniqId)
  // 默认日期为前一天的日期
  const date = dayjs().subtract(1, 'day').format('YYYY-MM-DD')
  detailData.sczl_rq = date
}
const addDetailData = async() => {
  const restoredData = {
    sys_id: params.sys_id,
    sczl_rq: detailData.sczl_rq,
    sczl_bh: detailData.sczl_bh,
    // name: detailData.name,
    sczl_bzdh: detailData.sczl_bzdh,
    sczl_jsss: detailData.sczl_jsss,
    sczl_冲定额: detailData.sczl_冲定额,
    sczl_desc: detailData.sczl_desc,
  }
  detailData.table.forEach((item, index, array) => {
    const num = index + 1
    restoredData[`sczl_gdbh${num}`] = item.sczl_gdbh
    restoredData[`sczl_yjGx${num}`] = item.sczl_yjGx
    restoredData[`sczl_gxmc${num}`] = item.sczl_gxmc
    // restoredData[`Gd_cpmc${num}`] = item.Gd_cpmc
    restoredData[`sczl_cl${num}`] = item.sczl_cl
    restoredData[`sczl_返工产量${num}`] = item.sczl_返工产量
    restoredData[`sczl_PgCl${num}`] = item.sczl_PgCl
    restoredData[`sczl_计产系数${num}`] = item.sczl_计产系数
    restoredData[`sczl_Jtbh${num}`] = item.sczl_Jtbh1
    restoredData[`sczl_dedh${num}`] = item.sczl_dedh
  })
  const res = await addPackingTable(restoredData)
  console.log(restoredData)
  console.log(res)
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '新增成功',
    })
    dialogFormVisible.value = false
    getTableData()
    getSideData()
  }
}

const handleGetYg = async() => {
  try {
    const res = await getYg({ sczl_bh: detailData.sczl_bh })
    if (res.code === 0) {
      detailData.name = res.data.ygxm
    } else {
      detailData.name = ''
    }
  } catch (e) {
    console.log(e)
  }
}

// 处理选择框回车操作
const handleEnter = (index, row) => {
  if (row.sczl_gdbh === '') {
    detailData.table[index].sczl_yjGx = ''
    detailData.table[index].sczl_gxmc = ''
    detailData.table[index].Gd_cpmc = ''
  } else {
    getTableGxMc(index, row)
  }
}

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

// 弹窗确定
const enterDialog = () => {
  if (type.value === '查改') {
    updateDetailData()
  } else if (type.value === '新增') {
    addDetailData()
  }
}
// 定额代号回车事件
const getDedhsubmit = () => {}

let formElements
const moveFocus = (event) => {
  const index = Array.from(formElements).indexOf(event.target)
  const key = event.key
  event.preventDefault()
  switch (index) {
    case 0:
      if (key === 'ArrowDown') {
        formElements[1].focus()
		formElements[1].select()
      } else if (key === 'ArrowUp') {
        formElements[formElements.length - 1].focus()
		formElements[formElements.length - 1].select()
      } else if (key === 'Enter') {
        formElements[1].focus()
		formElements[1].select()
      }
      break

    case 1:
      if (key === 'ArrowDown') {
        formElements[3].focus()
		formElements[3].select()
        handleGetYg()
      } else if (key === 'ArrowUp') {
        formElements[0].focus()
		formElements[0].select()
        handleGetYg()
      } else if (key === 'Enter') {
        formElements[3].focus()
		formElements[3].select()
        handleGetYg()
      }
      break

    case 3:
      if (key === 'ArrowDown') {
        formElements[4].focus()
		formElements[4].select()
      } else if (key === 'ArrowUp') {
        formElements[1].focus()
		formElements[1].select()
      } else if (key === 'Enter') {
        formElements[4].focus()
		formElements[4].select()
      }
      break

    case formElements.length - 1 :
      if (key === 'ArrowDown') {
        formElements[0].focus()
		formElements[0].select()
      } else if (key === 'ArrowUp') {
        formElements[index - 1].focus()
		formElements[index - 1].select()
      } else if (key === 'Enter') {
        formElements[0].focus()
		formElements[0].select()
      }
      break

    default:
      if (key === 'ArrowDown') {
        formElements[index + 1].focus()
		formElements[index + 1].select()
      } else if (key === 'ArrowUp') {
        formElements[index - 1].focus()
		formElements[index - 1].select()
      } else if (key === 'Enter') {
        formElements[index + 1].focus()
		formElements[index + 1].select()
      }
      break
  }
}
</script>

<style scoped>
:deep(.plan-usage-low div) {
  color: red !important;
}

.JKWTree-container {
  display: flex;
}

.JKWTree-tree {
  width: 100%;
  background-color: #fff;
  /*background-color: rgba(241, 224, 224, 0.99);*/
  padding: 10px;
  margin-right: 20px;
}

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

.JKWTree-content {
  flex: 1;
}

:deep(.el-table__body .warning-row) {
  background: #FFFF80 !important;
}

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

:deep(.el-table .bg-yellow) {
  background: yellow;
}

</style>
<style scoped>
:deep(.el-table td .cell) {
  line-height: 25px !important;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}

.search {
  margin-left: 0px !important;
  margin-right: 10px !important;
}

.bt {
  margin-left: 2px !important;
  padding: 3px !important;
  font-size: 12px;
}

.el-tabs__header {
  margin: 0px !important;
}

.gva-table-box {
  padding: 0px !important;
}

.mab {
  margin-bottom: 5px;
}
</style>
