<template>
  <div>
    <el-container>

      <el-scrollbar max-height="75vh">
        <el-aside>
          <div class="JKWTree-tree">
            <h3> 工单抽检记录维护</h3>
            <el-tree
              :data="treeData"
              :props="defaultProps"
              @node-click="handleNodeClick"
            />
          </div>
        </el-aside>
      </el-scrollbar>

      <el-container>
        <!--        <el-header>dd</el-header>-->
        <el-main>

          <div class="gva-search-box">
            <el-form
              ref="elSearchFormRef"
              :inline="true"
              :model="searchInfo"
              class="demo-form-inline"
              :rules="searchRule"
            >
              <el-form-item>
                <el-input
                  v-model="searchInfo"
                  :clearable="true"
                  placeholder="输入工单编号"
                />
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  icon="search"
                  @click="handlerSearch"
                >查询</el-button>
				<el-button
				   type="primary"
				   :icon="Search"
				   @click="handleShowAdd"
				 >新增
				 </el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="gva-table-box">
            <!-- <div class="gva-btn-list">
              <el-button type="primary" icon="plus" @click="openDialog">新增</el-button>
              <el-popover v-model:visible="deleteVisible" :disabled="!multipleSelection.length" placement="top" width="160">
                <p>确定要删除吗？</p>
                <div style="text-align: right; margin-top: 8px;">
                  <el-button type="primary" link @click="deleteVisible = false">取消</el-button>
                  <el-button type="primary" @click="onDelete">确定</el-button>
                </div>
                <template #reference>
                  <el-button icon="delete" style="margin-left: 10px;" :disabled="!multipleSelection.length" @click="deleteVisible = true">删除</el-button>
                </template>
              </el-popover>
            </div> -->
            <el-table
              ref="multipleTable"
              border
              style="width: 100%"
              tooltip-effect="dark"
              :data="tableData"
              row-key="ID"
              highlight-current-row
              :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="getDetailData"
			  @row-click="handleSelectChange"
            >
              <el-table-column
                type="selection"
                width="55"
				
              />
              <el-table-column
                align="center"
                label="日期"
                prop="Sczl_rq"
                width="100"
				sortable
              />
              <el-table-column
                align="left"
                label="员工编号"
                prop="Sczl_bh"
                width="90"
				sortable
              />
              <el-table-column
                align="left"
                label="员工姓名"
                prop="name"
                width="90"
				sortable
              />
              <el-table-column
                align="left"
                label="工单编号"
                prop="Sczl_gdbh"
                width="90"
				sortable
              />
              <el-table-column
                align="left"
                label="产品名称"
                prop="Gd_cpmc"
                width="130"
				sortable
              />
              <el-table-column
                align="left"
                label="工序名称"
                prop="Sczl_gxmc"
                width="95"
				sortable
              />
              <el-table-column
                align="left"
                label="印件号"
                prop="sczl_yjno"
                width="70"
				sortable
              />
              <el-table-column
                align="left"
                label="工序号"
                prop="sczl_gxh"
                width="70"
				sortable
              />
              <el-table-column
                align="left"
                label="流程单号"
                prop="Sczl_num"
                width="85"
				sortable
              />
              <el-table-column
                align="left"
                label="抽检数"
                prop="Sczl_抽检数"
                width="70"
				sortable
              />
              <el-table-column
                align="left"
                label="A类废"
                prop="sczl_A类废"
                width="70" sortable
              />
              <el-table-column
                align="left"
                label="B类废"
                prop="sczl_B类废"
                width="70"  sortable
              />
              <el-table-column
                align="left"
                label="C类废"
                prop="sczl_C类废"
                width="70" sortable
              />
              <el-table-column
                align="left"
                label="备注"
                prop="Sczl_desc"
                width="80" sortable
              />
              <el-table-column
                align="left"
                label="创建用户"
                prop="Sys_id"
                width="120" sortable
              />
              <el-table-column
                align="left"
                label="创建时间"
                prop="Sys_rq"
                width="160" sortable
              />
              <el-table-column
                align="left"
                label="修改时间"
                prop="Mod_rq"
                width="120" sortable
              />
              <el-table-column
                align="left"
                label="UNIQID"
                prop="UniqId"
                width="75" sortable
              />
            </el-table>
            <div class="gva-pagination">
              <el-pagination
                v-model:current-page="page"
                v-model:page-size="pageSize"
                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"
            destroy-on-close
            width="800"
          >
            <!--            <el-scrollbar height="340px">-->
            <el-form
              ref="elFormRef"
              :model="detailData"
              :inline="true"
              label-position="right"
              :rules="rule"
              label-width="75px"
            >
              <el-form-item
                label="员工编号:"
                prop="address"
              >
                <el-input
                  v-model="detailData.Sczl_bh"
                  :clearable="true"
				  @keyup.enter="handleGetYg"
                />
              </el-form-item>
              <el-form-item prop="image">
                <el-input
                  v-model="detailData.name"
                  :clearable="true"
                  placeholder="请输入员工姓名"
                />
              </el-form-item>
            </el-form>
            <el-form
              ref="elFormRef"
              :model="detailData"
              :inline="true"
              label-position="right"
              :rules="rule"
              label-width="75px"
            >
              <el-form-item
                label="班组:"
                prop="address"
              >
                <!-- <el-input
                  v-model="detailData.sczl_bzdh"
                  :clearable="true"
                  placeholder="请输入班组"
                /> -->
				<el-select v-model="detailData.sczl_bzdh" placeholder="" style="width: 70px"
				           
				>
				  <el-option label="A班" value="A班"></el-option>
				  <el-option label="B班" value="B班"></el-option>
				</el-select>
              </el-form-item>
              <el-form-item
                label="日期:"
                prop="image"
              >
                <el-input
                  v-model="detailData.Sczl_rq"
                  :clearable="true"
                  placeholder="请输入日期"
                />
              </el-form-item>
            </el-form>
            <el-form
              ref="elFormRef"
              :model="detailData"
              :inline="true"
              label-position="right"
              :rules="rule"
              label-width="75px"
            >
              <el-form-item
                label="工单编号:"
                prop="address"
              >
                <el-input
                  v-model="detailData.Sczl_gdbh"
                  :clearable="true"
                  placeholder="请输入工单编号"
                />
              </el-form-item>
              <el-form-item prop="image">
                <el-input
                  v-model="detailData.Gd_cpmc"
                  :clearable="true"
                  placeholder="请输入产品名称"
                />
              </el-form-item>
            </el-form>
            <el-form
              ref="elFormRef"
              :model="detailData"
              :inline="true"
              label-position="right"
              :rules="rule"
              label-width="75px"
            >
              <el-form-item
                label="工序名称:"
                prop="address"
              >
                <el-input
                  v-model="detailData.Sczl_gxmc"
                  :clearable="true"
                  placeholder="请输入工序名称"
                  style="width: 140px;"
                />
              </el-form-item>
              <el-form-item prop="image">
                <el-input
                  v-model="detailData.sczl_gxh"
                  :clearable="true"
                  placeholder="请输入工序号"
                  style="width: 140px;"
                />
              </el-form-item>
              <el-form-item
                label="流程单号:"
                prop="address"
              >
                <el-input
                  v-model="detailData.Sczl_num"
                  :clearable="true"
                  placeholder="请输入流程单号"
                  style="width: 140px;"
                />
              </el-form-item>
            </el-form>
            <el-form
              ref="elFormRef"
              :model="detailData"
              :inline="true"
              label-position="right"
              :rules="rule"
              label-width="75px"
            >
              <el-form-item
                label="抽检数量:"
                prop="address"
              >
                <el-input
                  v-model="detailData.Sczl_抽检数"
                  :clearable="true"
                  placeholder="请输入抽检数量"
                  style="width: 123px;"
                />
              </el-form-item>
            </el-form>
            <el-form
              ref="elFormRef"
              :model="detailData"
              :inline="true"
              label-position="right"
              :rules="rule"
              label-width="75px"
            >
              <el-form-item
                label="A类废品:"
                prop="address"
              >
                <el-input
                  v-model="detailData.Sczl_A类废"
                  :clearable="true"
                  placeholder="请输入A类废品"
                  style="width: 123px;"
                />
              </el-form-item>
              <el-form-item
                label="B类废品:"
                prop="image"
              >
                <el-input
                  v-model="detailData.Sczl_B类废"
                  :clearable="true"
                  placeholder="请输入B类废品"
                  style="width: 123px;"
                />
              </el-form-item>
              <el-form-item
                label="C类废品:"
                prop="address"
              >
                <el-input
                  v-model="detailData.Sczl_C类废"
                  :clearable="true"
                  placeholder="请输入C类废品"
                  style="width: 123px;"
                />
              </el-form-item>
            </el-form>
            <el-form
              ref="elFormRef"
              :model="detailData"
              label-position="right"
              :rules="rule"
              label-width="80px"
            >
              <el-form-item
                label="其他备注:"
                prop="address"
              >
                <el-input
                  v-model="detailData.Sczl_desc"
                  :clearable="true"
                  placeholder="请输入其他备注"
                />
              </el-form-item>
            </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="detailShow"
            style="width: 800px"
            lock-scroll
            :before-close="closeDetailShow"
            title="查看详情"
            destroy-on-close
          >
            <el-scrollbar height="550px">
              <el-descriptions
                column="1"
                border
              >
                <el-descriptions-item label="address字段">
                  {{ formData.address }}
                </el-descriptions-item>
                <el-descriptions-item label="image字段">
                  {{ formData.image }}
                </el-descriptions-item>
                <el-descriptions-item label="name字段">
                  {{ formData.name }}
                </el-descriptions-item>
              </el-descriptions>
            </el-scrollbar>
          </el-dialog>-->

        </el-main>

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

  </div>
</template>

<script setup>
import { getSpotList, getSpotTab, getSpotLocal, getSpotInfo, updateSpotData,add } from '@/api/mes/job'
import { createCompany, deleteCompany, deleteCompanyByIds, findCompany, updateCompany } from '@/api/company'
import{getYg}from '@/api/mes_api_gty/myapi'
// 全量引入格式化工具 请按需保留
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive, ref } from 'vue'

defineOptions({
  name: 'Sampling'
})

const treeData = ref([])
const SpotTab = async() => {
  const getSpotTabs = await getSpotTab()
  if (getSpotTabs.code === 0) {
    treeData.value = getSpotTabs.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,
          total: sysItem.count,
        },
      })),
    }))
  }
}
SpotTab()
const handleNodeClick = (node, check) => {
  // 存放当前节点的nodeId
  if (node.params) {
    params.date = node.params.date
    params.sys_id = node.params.sys_id
    params.type = 'getTableData'
    page.value = 1
    handleCurrentChange()
  }
}
// 自动化生成的字典（可能为空）以及字段
const formData = ref({
  address: '',
  image: '',
  name: '',
})
const handleGetYg = async() => {
  try {
    const res = await getYg({ sczl_bh: detailData.Sczl_bh })
    if (res.code === 0) {
      detailData.name = res.data.ygxm
    }
  } catch (e) {
    console.log(e)
  }
}

// 验证规则
const rule = reactive({
})

/* const searchRule = reactive({
  createdAt: [
    { validator: (rule, value, callback) => {
      if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
        callback(new Error('请填写结束日期'))
      } else if (!searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt) {
        callback(new Error('请填写开始日期'))
      } else if (searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt && (searchInfo.value.startCreatedAt.getTime() === searchInfo.value.endCreatedAt.getTime() || searchInfo.value.startCreatedAt.getTime() > searchInfo.value.endCreatedAt.getTime())) {
        callback(new Error('开始日期应当早于结束日期'))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ],
}) */

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = reactive([])
const searchInfo = ref('')
const params = {
  date: '',
  sys_id: '',
  search: '',
  type: '',
}
const minUniqId = ref('')
// 获取表格数据
const getTableData = async() => {
  const { date, sys_id } = params
  const res = await getSpotList({ date, sys_id,
    page: page.value.toString(), limit: pageSize.value.toString() })
  if (res.code === 0) {
    tableData.splice(0, tableData.length, ...res.data.rows)
    total.value = res.data.total
	minUniqId.value= Math.min(...tableData.map(row => row.UniqId));
  }
}

const getLocal = async() => {
  const res = await getSpotLocal({
    search: params.search,
    page: page.value.toString(),
    limit: pageSize.value.toString()
  })
  if (res.code === 0) {
    tableData.splice(0, tableData.length, ...res.data.rows)
    total.value = res.data.total
  }
}

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

// 修改页面容量
const handleCurrentChange = () => {
  switch (params.type) {
    case 'getTableData':
      getTableData()
      break
    case 'getLocal':
      getLocal()
      break
    default:
      break
  }
}

// 搜索
const handlerSearch = () => {
  params.search = searchInfo.value
  params.type = 'getLocal'
  page.value = 1
  handleCurrentChange()
}
// 新增数据
const handleShowAdd = async () => {
  type.value = '新增';
  console.log(currentRow.value);

  const res = await getSpotInfo({ UniqId: minUniqId.value });

  if (res.code === 0) {
	  let sczl_rq = new Date();
	  sczl_rq.setDate(sczl_rq.getDate() - 0); // 今天的前N天的日期，N自定义
	  res.data[0].Sczl_rq = `${sczl_rq.getFullYear()}-${sczl_rq.getMonth() + 1}-${sczl_rq.getDate()}`;
    Object.assign(detailData, res.data[0]);
    detailData.UniqId = currentRow.value;
    dialogFormVisible.value = true
  }
};
	// type.value='add'
 //    Object.assign(detailData);
	// dialogFormVisible.value = true
  
// };
// ============== 详情展示 ===============
const detailData = reactive({})

// 展示详情
const getDetailData = async(row) => {
  console.log(row.UniqId)
  const { UniqId } = row
  type.value='查改'
  const res = await getSpotInfo({ UniqId })
  if (res.code === 0) {
    Object.assign(detailData, res.data[0])
    detailData.UniqId = UniqId
    dialogFormVisible.value = true
  }
}
const currentRow = ref()
const handleSelectChange = (row, column, event) => {
  currentRow.value = row.UniqId
}

// 弹窗确定更新数据
const enterDialog = async() => {
  // const obj = { ...detailData }
   console.log(type.value)
   if (type.value === '查改') {
  	   updateDetailData()
  	 } else if (type.value === '新增') {
  	   addDetailData()
  	 }else {
		 console.log(type)
	 }

}
const addDetailData = async() => {
	const obj = {}
	Object.assign(obj, detailData)
	delete obj.name
	delete obj.Gd_cpmc
	delete obj.sczl_gxh
	const res = await add(obj)
	if (res.code === 0) {
	  ElMessage({
	    type: 'success',
	    message: '新增成功'
	  })
	  dialogFormVisible.value = false
	}
}
const updateDetailData = async() => {
	const obj = {}
	Object.assign(obj, detailData)
	delete obj.name
	delete obj.Gd_cpmc
	delete obj.sczl_gxh
	const res = await updateSpotData(obj)
	if (res.code === 0) {
	  ElMessage({
	    type: 'success',
	    message: '更新成功'
	  })
	  dialogFormVisible.value = false
	}
}
// 获取需要的字典 可能为空 按需保留
const setOptions = async() => {
}

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

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

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteCompanyFunc(row)
  })
}

// 批量删除控制标记
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 deleteCompanyFunc = async(row) => {
  const res = await deleteCompany({ ID: row.ID })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    getTableData()
  }
}

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

// 查看详情控制标记
const detailShow = ref(false)

// 打开详情弹窗
const openDetailShow = () => {
  detailShow.value = true
}

// 打开详情
const getDetails = async(row) => {
  // 打开弹窗
  const res = await findCompany({ ID: row.ID })
  if (res.code === 0) {
    formData.value = res.data.recompany
    openDetailShow()
  }
}

// 关闭详情弹窗
const closeDetailShow = () => {
  detailShow.value = false
  formData.value = {
    address: '',
    image: '',
    name: '',
  }
}

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

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

</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;
}

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