<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-form-item>
        </el-form>

        <!-- 弹出框 -->
        <div>
          <!-- 详情页 -->
          <el-dialog
            v-model="dialogFormVisible"
            :before-close="closeDialog"
            :title="type"
            destroy-on-close
            width="800px"
          >
            <!-- <el-scrollbar height="500px"> -->
            <el-form
              id="detail-form"
              ref="elFormRef"
              :model="detailData"
              label-position="left"
              inline
              @keyup="moveFocus"
            >
              <el-form-item
                label="员工编号"
              >
                <el-input
                  v-model="detailData.Sczl_bh1"
                  style="width: 100px"
                  @keyup.enter="handleYgbhEnter"
                />
                <el-input
                  v-model="detailData.name"
                  style="width: 100px; margin-left: 5px"
                  readonly
                />
              </el-form-item>

              <br>

              <el-form-item
                label="工序类别"
              >
                <el-select
                  v-model="detailData.sczl_Type"
                  style="width: 150px"
                >
                  <el-option
                    label="拆片"
                    value="拆片"
                  />
                  <el-option
                    label="包装"
                    value="包装"
                  />
                  <el-option
                    label="打包"
                    value="打包"
                  />
                  <el-option
                    label="拉料"
                    value="拉料"
                  />

                </el-select>

              </el-form-item>

              <el-form-item
                label="日期"
              >
                <el-input
                  v-model="detailData.Sczl_rq"
                  style="width: 150px"
                />
              </el-form-item>

              <el-form-item
                label="工单编号"
              >
                <el-input
                  v-model="detailData.sczl_gdbh"
                  style="width: 100px"
                  @keyup.enter="handleGdbhEnter"
                />
                <el-input
                  v-model="detailData.Gd_cpmc"
                  style="width: 400px; margin-left: 5px"
                  readonly
                />
              </el-form-item>

              <el-form-item
                label="工艺流程"
              >
                <el-input
                  v-model="detailData.Sczl_gxmc"
                  style="width: 300px"
                  @keyup.enter="handleGylcEnter"
                />
                <el-input
                  v-model="detailData.sczl_gxh"
                  style="width: 100px; margin-left: 5px"
                  readonly
                />
              </el-form-item>
              <br>

              <el-form-item
                v-if="type === '新增'"
                label=""
                style="margin-left: 67px;"
              >
                <el-input
                  v-model="leftData"
                  style="width: 100px"
                />
              </el-form-item>

              <el-form-item
                v-if="type === '新增'"
                label="X"
              >
                <el-input
                  v-model="rightData"
                  style="width: 100px;margin-left: 12px;"
                  @keyup.enter="()=>{detailData.Sczl_cl = (leftData * rightData).toString()}"
                  @keyup.down="()=>{detailData.Sczl_cl = (leftData * rightData).toString()}"
                />
              </el-form-item>

              <el-form-item
                v-if="type === '新增'"
                label="计件产量"
                style="margin-left: 30px;"
              >
                <el-input
                  v-model="detailData.Sczl_cl"
                  style="width: 100px"
                />
              </el-form-item>

              <el-form-item
                v-if="type === '查改'"
                label="计件产量"
                style="margin-left: 400px;"
              >
                <el-input
                  v-model="detailData.Sczl_cl"
                  style="width: 100px"
                />
              </el-form-item>

              <el-form-item
                label="工价代号"
              >
                <el-input
                  v-model="detailData.sys_bh"
                  style="width: 200px"
                  @keyup.enter="handleGjdhEnter"
                />
                <el-input
                  v-model="detailData.sys_mc"
                  style="width: 300px; margin-left: 5px"
                  readonly
                />
              </el-form-item>

              <el-form-item
                label="票号备注"
              >
                <el-input
                  v-model="detailData.Sczl_desc"
                  style="width: 505px"
                />
              </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="dialogDedh"
            :before-close="()=>{dialogDedh = false}"
            title="工价代号"
            destroy-on-close
          >

            <el-scrollbar
              style="height: 50vh;width: 50vw;"
            >
              <el-tree
                :data="dedhTreeData"
                highlight-current
                style="width: 90%;"
                @node-click="handleSelectDjdh"
              />
            </el-scrollbar>
          </el-dialog>

          <!-- 工艺流程弹窗 -->
          <el-dialog
            v-model="dialogGylc"
            :before-close="()=>{dialogGylc = false}"
            title="工艺流程"
            destroy-on-close
          >

            <el-scrollbar
              style="height: 50vh;width: 50vw;"
            >
              <el-tree
                :data="gylcTreeData"
                highlight-current
                style="width: 90%;"
                @node-click="handleSelectGylc"
              />
            </el-scrollbar>
          </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>
          <!-- 数据展示 -->
          <el-table
            ref="table"
            style="width: 100%"
            tooltip-effect="dark"
            :data="tableData"
            row-key="ID"
            highlight-current-row
            border
            show-overflow-tooltip="true"
            :row-style="{ height: '20px' }"
            :cell-style="{ padding: '0px' }"
            :header-row-style="{ height: '20px' }"
            :header-cell-style="{ padding: '0px' }"
            @selection-change="handleSelectionChange"
            @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>
        </layout-content>
      </layout>
    </layout>

  </div>
</template>

<script setup>
import { Layout, LayoutContent, LayoutHeader, LayoutSider } from '@arco-design/web-vue'
import { ElMessage, dayjs } from 'element-plus'
import { ref, reactive } from 'vue'
import { getSide, getTable, getYg, getGdmc, getDedh, getGxMc, updateData, add } from '@/api/mes_api_gty/otherDocuments'

defineOptions({
  name: '07OtherDocuments'
})

// 侧边栏数据请求
const treeData = reactive([])
const getSideData = async() => {
  const response = await getSide()
  if (response.code === 0) {
    const transformedData = response.data.map(item => ({
      label: `${item.date.replace(/-/g, '.')}【产量合计: ${item.counts}】`,
      children: item.sys.map(sysItem => ({
        label: `${sysItem.Sczl_bh1}(${sysItem.name}) 【产量合计: ${sysItem.count}】`,
        params: {
          date: item.date.substring(0, 4) + '-' + item.date.substring(4),
          Sczl_bh1: sysItem.Sczl_bh1,
        },
      })),
    }))
    treeData.splice(0, treeData.length, ...transformedData)
  }
}
getSideData()

const elFormRef = ref()

// ============== 表格页面 ==============
const tableColumns = [
  { prop: 'sczl_Type', label: '计件类型', width: '100' },
  { prop: 'Sczl_rq', label: '日期', width: '100' },
  { prop: 'Sczl_bh1', label: '员工编号', width: '100' },
  { prop: 'name', label: '员工姓名', width: '100' },
  { prop: 'sczl_gdbh', label: '工单编号', width: '100' },
  { prop: 'Gd_cpmc', label: '产品名称', width: '300' },
  { prop: 'Sczl_cl', label: '产量', width: '100' },
  { prop: '', label: '千件工价', width: '100' }, // prop 属性值需要补充
  { prop: 'sys_mc', label: '工价备注', width: '200' }, // prop 属性值需要补充
  { prop: 'Sczl_desc', label: '备注', width: '100' },
  { prop: 'Sczl_gxmc', label: '工序名称', width: '100' },
  { prop: 'sczl_yjno', label: '印件号', width: '100' },
  { prop: 'sczl_gxh', label: '工序号', width: '100' },
  { prop: 'sys_id', label: '创建用户', width: '150' },
  { prop: 'sys_rq', label: '创建时间', width: '200' },
  { prop: 'mod_rq', label: '修改时间', width: '200' },
  { prop: 'UniqId', label: 'UNIQID', width: '100' }
]
const tableData = reactive([])
const currentRow = ref()
const type = ref('')

const page = ref(1)
const total = ref(0)
const limit = ref(10)
const searchInfo = ref('')
const params = {
  date: '',
  Sczl_bh1: '',
  order: '',
  page: page.value.toString(),
  limit: limit.value.toString(),
}

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

// 获取表格数据
const getTableData = async() => {
  // try {
  const response = await getTable(params)
  if (response.code === 0) {
    total.value = response.data.total
    tableData.splice(0, tableData.length, ...response.data.rows)
    setCurrent(tableData[0])
  }
}

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

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

// 点击左侧节点
const handleNodeClick = (node, check) => {
  if (node.params) {
    params.date = node.params.date
    params.Sczl_bh1 = node.params.Sczl_bh1
    params.order = ''
    page.value = 1
    handleCurrentChange()
  }
}

// 搜索
function handleSearch() {
  params.order = searchInfo.value
  params.date = ''
  params.Sczl_bh1 = ''
  page.value = 1
  handleCurrentChange()
}

// ============== 详情页面 ==============
const detailData = reactive({})
const leftData = ref(0)
const rightData = ref(0)
const dedhTreeData = ref()
const gylcTreeData = ref()

// 弹窗控制标记
const dialogFormVisible = ref(false)
const dialogDedh = ref(false)
const dialogGylc = ref(false)
// 新增数据
const handleShowAdd = () => {
  if (!currentRow.value) {
    ElMessage({
      type: 'info',
      message: '请选择一条数据'
    })
    return
  }
  type.value = '新增'
  Object.assign(detailData, currentRow.value)
  // dialogFormVisible.value = true
  const date = dayjs().format('YYYY-MM-DD')
  detailData.Sczl_rq = date
  showDialog()
}
// 查改
const handleShowDetail = () => {
  type.value = '查改'
  Object.assign(detailData, currentRow.value)
  // dialogFormVisible.value = true
  showDialog()
}
const handleYgbhEnter = async() => {
  const res = await getYg({ sczl_bh: detailData.Sczl_bh1 })
  if (res.code === 0) {
    detailData.name = res.data.ygxm
  }
}

const handleGdbhEnter = async() => {
  const res = await getGdmc({ gdbh: detailData.sczl_gdbh })
  if (res.code === 0) {
    detailData.Gd_cpmc = res.data.Gd_cpmc
  }
}

const handleGylcEnter = async() => {
  const res = await getGxMc({ gdbh: detailData.sczl_gdbh, keyword: '' })
  if (res.code === 0) {
    const ret = res.data.map(item => ({
      ...item,
      label: item['jyGx'],
    }))
    gylcTreeData.value = ret
    dialogGylc.value = true
  }
}

const handleSelectGylc = (node, check) => {
  detailData.Sczl_gxmc = node['jyGx']
  detailData.sczl_gxh = node['Gy0_gxh']
  dialogGylc.value = false
}

const handleGjdhEnter = async() => {
  const res = await getDedh({ sczl_jtbh: '' })
  if (res.code === 0) {
    const { data } = res

    const transformData = (data) => {
      if (Array.isArray(data)) {
        return data.map((item) => transformData(item))
      } else if (typeof data === 'object') {
        const { Key_, sys_bh, sys_mc, bh_mc } = data
        const label = `${sys_bh}【${sys_mc}】`
        const node = { Key_, sys_bh, sys_mc, label }

        if (bh_mc) {
          node.children = transformData(bh_mc)
        }

        return node
      } else {
        return data
      }
    }

    const temp = []
    temp[0] = transformData(data)
    dedhTreeData.value = temp
    console.log(temp)
    dialogDedh.value = true
  }
}

const handleSelectDjdh = (node, check) => {
  if (!node['children']) {
    console.log(node)
    const { sys_bh, sys_mc } = node
    detailData.sys_bh = sys_bh
    detailData.sys_mc = sys_mc
    dialogDedh.value = false
  }
}

// 弹窗确定
const enterDialog = async() => {
  if (type.value === '查改') {
    updateDetailData()
  } else if (type.value === '新增') {
    addDetailData()
  }
}
// 新增
const addDetailData = async() => {
  const restoredData = {
    Sys_id: '[1009/李美芬]',
    Sczl_bh1: detailData.Sczl_bh1,
    sczl_Type: detailData.sczl_Type,
    // name: detailData.name,
    Sczl_rq: detailData.Sczl_rq,
    Sczl_gdbh: detailData.sczl_gdbh,
    Sczl_gxmc: detailData.Sczl_gxmc,
    sczl_gxh: detailData.sczl_gxh,
    Sczl_cl: detailData.Sczl_cl,
    Sczl_dedh: detailData.sys_bh,
    Sczl_desc: detailData.Sczl_desc,
  }
  console.log(restoredData)
  const res = await add(restoredData)
  console.log(restoredData)
  console.log(res)
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '新增成功',
    })
    dialogFormVisible.value = false
  }
  getSideData()
}
// 修改
const updateDetailData = async() => {
  const params = {
    UniqId: detailData.UniqId,
    Sczl_bh1: detailData.Sczl_bh1,
    sczl_Type: detailData.sczl_Type,
    Sczl_rq: detailData.Sczl_rq,
    Sczl_gdbh: detailData.sczl_gdbh,
    Sczl_gxmc: detailData.Sczl_gxmc,
    sczl_gxh: detailData.sczl_gxh,
    Sczl_cl: detailData.Sczl_cl,
    Sczl_dedh: '',
    Sczl_desc: detailData.Sczl_desc,
  }
  const res = await updateData(params)
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '更新成功',
    })
    dialogFormVisible.value = false
    params.order = ''
    // page.value = 1
    handleCurrentChange()
  }
}

// 开启弹窗
const showDialog = () => {
  dialogFormVisible.value = true
  // 在 setTimeout 中获取元素，确保在 DOM 渲染完毕后执行
  setTimeout(() => {
    formElements = document.getElementById('detail-form').elements
    formElements[0].focus()
  }, 0)
}

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
}

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()
      } else if (key === 'ArrowUp') {
        formElements[formElements.length - 1].focus()
      } else if (key === 'Enter') {
        formElements[1].focus()
      }
      break

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

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

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

.JKWTree-tree {
  width: 100%;
  background-color: #fff;
  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 tr.current-row) > td {
  background: #ff80ff !important;
}
</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>
