<template>
  <div>
    <!-- 左侧树形结构 -->
    <el-container>
      <el-aside width="300px">
        <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"
                  placeholder="输入工单编号"
                  style="width: 200px"
                />
              </el-row>
              <el-button
                type="primary"
                :icon="Search"
                @click="onSearch"
              >搜索</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
              border
              :row-style="{ height: '20px' }"
              :cell-style="{ padding: '0px' }"
              :header-row-style="{ height: '20px' }"
              :header-cell-style="{ padding: '0px' }"
              @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="拉料计件产量维护"
            destroy-on-close
            width="800px"
          >
            <!-- <el-scrollbar height="500px"> -->
            <el-form
              ref="elFormRef"
              :model="detailData"
              :rules="rule"
              label-position="left"
              inline
            >
              <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-input
                  v-model="detailData.sczl_Type"
                  style="width: 150px"
                />
              </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.image"
                  style="width: 300px"
                />
                <el-input
                  v-model="detailData.image"
                  style="width: 100px; margin-left: 5px"
                />
              </el-form-item>

              <el-form-item
                label="计件产量"
                style="margin-left: 300px"
              >
                <el-input
                  v-model="detailData.Sczl_cl"
                  style="width: 100px"
                />
              </el-form-item>

              <el-form-item
                label="工价代号"
              >
                <el-input
                  v-model="detailData.Sczl_dedh"
                  style="width: 200px"
                  @keyup.enter="handleGjdhEnter"
                />
                <el-input
                  v-model="detailData.aaaa"
                  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-main>
      </el-container>
    </el-container>

  </div>
</template>

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

// 全量引入格式化工具 请按需保留
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 { getSide, getTable, getInfo, getOtherInfo, updateData } 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 elSearchFormRef = 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: '', 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 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 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)
    }
  } catch (e) {
    console.log(e)
  }
}

// 分页设置
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 onSearch() {
  params.order = searchInfo.value
  params.date = ''
  params.Sczl_bh1 = ''
  page.value = 1
  handleCurrentChange()
}

// ============== 详情页面 ==============
const detailData = reactive({})

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

// 双击表格操作
const doubleClick = async(row, column, event) => {
  type.value = 'update'
  // const res = await getInfo({ UniqId: row.UniqId })
  // if (res.code === 0) {
  //   console.log(res)
  // }

  Object.assign(detailData, row)
  dialogFormVisible.value = true
}

const handleYgbhEnter = async() => {
  const res = await getOtherInfo({ Sczl_bh1: detailData.Sczl_bh1 })
  if (res.code === 0) {
    detailData.name = res.data.name
  }
}

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

const handleGjdhEnter = async() => {
  const res = await getOtherInfo({ Sczl_dedh: detailData.Sczl_dedh })
  if (res.code === 0) {
    detailData.aaaa = res.data.name
  }
}

// 弹窗确定
const enterDialog = 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: '',
    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 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) {
    detailData.value = res.data.recompany
    dialogFormVisible.value = true
  }
}

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

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  detailData.value = {
    address: '',
    image: '',
    name: '',
  }
}

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

// 生命周期钩子
onMounted(() => {
})
</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;
}

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