﻿<template>
  <div class="sys-user-container">
    <el-row :gutter="5" style="width: 100%; flex: 1">
      <el-col :span="4" :xs="24">
        <OrgTree ref="orgTreeRef" @node-click="nodeClick" :lv="2" />
      </el-col>
      <el-col :span="20" :xs="24" style="display: flex; flex-direction: column">
        <el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
          <el-form :model="queryParams" ref="queryForm" labelWidth="90">
            <el-row>
              <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4" class="mb10">
                <el-form-item label="关键字">
                  <el-input v-model="queryParams.searchKey" clearable="" placeholder="请输入模糊查询关键字" />

                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
                <el-form-item label="产线编码">
                  <el-input v-model="queryParams.productionLineCode" clearable="" placeholder="请输入产线编码" />

                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
                <el-form-item label="产线名称">
                  <el-input v-model="queryParams.productionLineName" clearable="" placeholder="请输入产线名称" />

                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
                <el-form-item label=" 产线类别">
                  <el-select clearable="" filterable="" v-model="queryParams.productionLineTypeCode"
                    placeholder="请选择 产线类别">
                    <el-option v-for="(item, index) in  mesProductionLineTypeProductionLineTypeCodeDropdownList"
                      :key="index" :value="item.value" :label="item.label" />

                  </el-select>

                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
                <el-form-item label="所属车间">
                  <el-select clearable="" filterable="" v-model="queryParams.factoryCode" placeholder="请选择所属车间">
                    <el-option v-for="(item, index) in  mesWorkShopFactoryCodeDropdownList" :key="index"
                      :value="item.value" :label="item.label" />

                  </el-select>

                </el-form-item>
              </el-col>
              <!-- <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
                <el-form-item label="公休日类型">
                  <el-select clearable="" v-model="queryParams.holidayType" placeholder="请选择公休日类型">
                    <el-option v-for="(item, index) in dl('HolidayType')" :key="index" :value="item.code"
                      :label="`[${item.code}] ${item.value}`" />

                  </el-select>

                </el-form-item>
              </el-col> -->
              <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4" class="mb10">
                <el-form-item>
                  <el-button-group style="display: flex; align-items: center;">
                    <el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'mesProductionLine/page'">
                      查询
                    </el-button>
                    <el-button icon="ele-Refresh" @click="() => queryParams = {}"> 重置 </el-button>
                    <el-button icon="ele-ZoomIn" @click="changeAdvanceQueryUI" v-if="!showAdvanceQueryUI"
                      style="margin-left:5px;"> 高级查询 </el-button>
                    <el-button icon="ele-ZoomOut" @click="changeAdvanceQueryUI" v-if="showAdvanceQueryUI"
                      style="margin-left:5px;"> 隐藏 </el-button>
                    <el-button type="primary" style="margin-left:5px;" icon="ele-Plus" @click="openAddMesProductionLine"
                      v-auth="'mesProductionLine/add'"> 新增 </el-button>

                  </el-button-group>
                </el-form-item>

              </el-col>
            </el-row>
          </el-form>
        </el-card>
        <el-card class="full-table" shadow="hover" style="margin-top: 5px;">
          <el-table :data="tableData" style="width: 100%" v-loading="loading" tooltip-effect="light" row-key="id"
            @sort-change="sortChange" border="" @expand-change="handleExpandChange">
            <el-table-column type="expand">
              <template #default="scope">
                <el-card style="padding-left: 20px;">
<!--                <NestedTable v-if="scope.row.expanded" :getPartLists="getPartLists[scope.row.id]" />-->
                  <el-tabs v-model="activeChild[scope.row.id]">
                    <el-tab-pane label="关联设备"  name="equipment"></el-tab-pane>
                    <el-tab-pane label="上岗资质" name="person"></el-tab-pane>
                    <el-tab-pane label="可加工产品"  name="product"></el-tab-pane>
                  </el-tabs>
                  <!--   员工  -->
                  <el-table :data="scope.row.personTableData || []" style="width: 100%" v-loading="loading" tooltip-effect="light" row-key="id" border="" v-show="activeChild[scope.row.id] == 'person'">
                    <el-table-column type="index" label="序号" width="55" align="center" />
                    <el-table-column prop="account" label="账号" show-overflow-tooltip="" />
                    <el-table-column prop="realName" label="姓名" show-overflow-tooltip="" />
                  </el-table>
                  <!--   设备  -->
                  <el-table :data="scope.row.equipmentTableData || []" style="width: 100%" v-loading="loading" tooltip-effect="light" row-key="id" border="" v-show="activeChild[scope.row.id] == 'equipment'||!activeChild[scope.row.id]">
                    <el-table-column type="index" label="序号" width="55" align="center" />
                    <el-table-column prop="equipmentCode" label="设备编码" show-overflow-tooltip="" />
                    <el-table-column prop="equipmentName" label="设备名称" show-overflow-tooltip="" />
                  </el-table>
                  <!--    产品    -->
                  <el-table :data="scope.row.productTableData || []" style="width: 100%" v-loading="loading" tooltip-effect="light" row-key="id" border="" v-show="activeChild[scope.row.id] == 'product'">
                    <el-table-column type="index" label="序号" width="55" align="center" />
                    <el-table-column prop="productCode" label="产品编码" show-overflow-tooltip="" />
                    <el-table-column prop="productName" label="产品名称" show-overflow-tooltip="" />
                  </el-table>
                </el-card>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="55" align="center" />
            <el-table-column prop="productionLineCode" label="产线编码" show-overflow-tooltip="" />
            <el-table-column prop="productionLineName" label="产线名称" show-overflow-tooltip="" />
            <el-table-column prop="productionLineTypeCode" label=" 产线类别" show-overflow-tooltip="">
              <template #default="scope">
                <span>{{ scope.row.productionLineTypeCodeProductionLineTypeName }}</span>

              </template>

            </el-table-column>
            <el-table-column prop="factoryCode" label="所属工厂" show-overflow-tooltip="">
              <template #default="scope">
               <span v-show="scope.row.factoryCode">[{{ scope.row.factoryCode }}]</span><span>{{ scope.row.factoryName }}</span>

              </template>

            </el-table-column>
            <el-table-column prop="workShopCode" label="所属车间" show-overflow-tooltip="">
              <template #default="scope">
                <span v-show="scope.row.workShopCode">[{{ scope.row.workShopCode }}]</span><span>{{ scope.row.workShopName  }}</span>

              </template>

            </el-table-column>
            <!-- <el-table-column prop="holidayType" label="公休日类型" show-overflow-tooltip="">
              <template #default="scope">
                {{ scope.row.holidayTypeName }}
              </template>
            </el-table-column> -->
            <el-table-column prop="remark" label="备注" show-overflow-tooltip="" />
            <el-table-column prop="sorts" label="排序" show-overflow-tooltip="" />
            <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip="" />
            <el-table-column prop="updateTime" label="更新时间" show-overflow-tooltip="" />
            <el-table-column prop="createUserName" label="创建者姓名" show-overflow-tooltip="" />
            <el-table-column label="操作" width="140" align="center" fixed="right"
              v-if="auth('mesProductionLine/update') || auth('mesProductionLine/delete')">
              <template #default="scope">
                <!-- <el-button icon="ele-Delete" size="small" text="" type="primary" @click="machinable(scope.row)"
                  v-auth="'mesProductionLine/delete'"> 可加工零件 </el-button> -->
                <el-button icon="ele-Edit" size="small" text="" type="primary"
                  @click="openEditMesProductionLine(scope.row)" v-auth="'mesProductionLine/update'"> 编辑 </el-button>
                <el-button icon="ele-Delete" size="small" text="" type="primary"
                  @click="delMesProductionLine(scope.row)" v-auth="'mesProductionLine/delete'"> 删除 </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination v-model:currentPage="tableParams.page" v-model:page-size="tableParams.pageSize"
            :total="tableParams.total" :page-sizes="[10, 20, 50, 100, 200, 500]" small="" background=""
            @size-change="handleSizeChange" @current-change="handleCurrentChange"
            layout="total, sizes, prev, pager, next, jumper" />
          <printDialog ref="printDialogRef" :title="printMesProductionLineTitle" @reloadTable="handleQuery" />
          <editDialog ref="editDialogRef" :title="editMesProductionLineTitle" @reloadTable="handleQuery" />
          <editDialog1 ref="editDialogRef1" :title="editMesProductionLineTitle1" @reloadTable="handleQuery" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup="" name="mesProductionLine">
import { ref } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { auth } from '/@/utils/authFunction';
import { getDictDataItem as di, getDictDataList as dl } from '/@/utils/dict-utils';
import { formatDate } from '/@/utils/formatTime';
import NestedTable from './component/NestedTable.vue'

import printDialog from '/@/views/system/print/component/hiprint/preview.vue'
import editDialog from '/@/views/mes/mesProductionLine/component/editDialog.vue'
import editDialog1 from '/@/views/mes/mesProductionLine/component/editDialog1.vue'
import { pageMesProductionLine, deleteMesProductionLine, getPartList } from '/@/api/mes/mesProductionLine';
import { getMesProductionLineTypeProductionLineTypeCodeDropdown } from '/@/api/mes/mesProductionLine';
import { getMesWorkShopFactoryCodeDropdown } from '/@/api/mes/mesProductionLine';
import OrgTree from '/@/views/mes/mesProductionLine/component/orgTree1.vue';

const showAdvanceQueryUI = ref(false);
const printDialogRef = ref();
const editDialogRef = ref();
const editDialogRef1 = ref();
const loading = ref(false);
const tableData = ref<any>([]);
const initialData = ref<any>([]);
const expandedRowId = ref(null);
const getPartLists = ref({});
const queryParams = ref<any>({});
const tableParams = ref({
  page: 1,
  pageSize: 10,
  total: 0,
});
interface TableRow {
  date: string;
  name: string;
  address: string;
  children?: TableRow[];
  expanded?: boolean;
}
const printMesProductionLineTitle = ref("");
const editMesProductionLineTitle = ref("");
const editMesProductionLineTitle1 = ref("");


const activeChild = ref({});




// 改变高级查询的控件显示状态
const changeAdvanceQueryUI = () => {
  showAdvanceQueryUI.value = !showAdvanceQueryUI.value;
}
// 查询操作
const handleQuery = async () => {
  loading.value = true;
  var res = await pageMesProductionLine(Object.assign(queryParams.value, tableParams.value));
  // tableData.value = res.data.result?.items ?? [];
  tableParams.value.total = res.data.result?.total;
  tableData.value = (res.data.result?.items ?? []).map((item) => {
  return {
    ...item,
    expanded: false,
    personTableData: (item.personCodes || '')
        .split(',')
        .filter((item) => item)
        .map((data, index) => {
          return {
            account: data || '',
            realName: (item.personNames || '').split(',').filter((item) => item)?.[index] || '',
          };
        }),
    equipmentTableData: (item.equipmentCodes || '')
        .split(',')
        .filter((item) => item)
        .map((data, index) => {
          return {
            equipmentCode: data || '',
            equipmentName: (item.equipmentNames || '').split(',').filter((item) => item)?.[index] || '',
          };
        }),
    productTableData: (item.productCodes || '')
        .split(',')
        .filter((item) => item)
        .map((data, index) => {
          return {
            productCode: data || '',
            productName: (item.productNames || '').split(',').filter((item) => item)?.[index] || '',
          };
        }),
  };
});
  console.log(tableData)
  loading.value = false;
};

// const handleExpandChange = async (row) => {
//   row.expanded = !row.expanded;
//   var res = await getPartList(row.id);
//   getPartLists.value = res.data.result
//   console.log(getPartLists)
// };
const handleExpandChange = async (row) => {
  if (expandedRowId.value !== null && expandedRowId.value !== row.id) {
    // 收起之前展开的行
    const previousExpandedRow = tableData.value.find(item => item.id === expandedRowId.value);
    if (previousExpandedRow) {
      previousExpandedRow.expanded = false;
    }
  }

  row.expanded = !row.expanded;

  if (row.expanded) {
    // 更新当前展开的行ID
    expandedRowId.value = row.id;
    // 异步获取数据
    // const res = await getPartList(row.id);
    // getPartLists.value = { ...getPartLists.value, [row.id]: res.data.result };
  } else {
    // 如果当前行收起，则清空当前展开的行ID
    expandedRowId.value = null;
  }

  console.log(getPartLists.value);
};

// return {
//   tableData,
//   handleExpandChange,
//   getPartLists,
// };
// 列排序
const sortChange = async (column: any) => {
  queryParams.value.field = column.prop;
  queryParams.value.order = column.order;
  await handleQuery();
};

// 打开新增页面
const openAddMesProductionLine = () => {
  if(!queryParams.value.workShopCode) return ElMessage.warning("请选择所属车间");
  editMesProductionLineTitle.value = '添加产线档案';
  editDialogRef.value.openDialog({
    workShopCode:queryParams.value.workShopCode,
  });
};

// 打开打印页面
const openPrintMesProductionLine = async (row: any) => {
  printMesProductionLineTitle.value = '打印产线档案';
}

// 打开编辑页面
const openEditMesProductionLine = (row: any) => {
  editMesProductionLineTitle.value = '编辑产线档案';
  editDialogRef.value.openDialog(row);
};
const machinable = (row: any) => {
  editMesProductionLineTitle1.value = '可加工零件';
  editDialogRef1.value.openDialog(row);
};
// 删除
const delMesProductionLine = (row: any) => {
  ElMessageBox.confirm(`确定要删除吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await deleteMesProductionLine(row);
      handleQuery();
      ElMessage.success("删除成功");
    })
    .catch(() => { });
};

// 改变页面容量
const handleSizeChange = (val: number) => {
  tableParams.value.pageSize = val;
  handleQuery();
};

// 改变页码序号
const handleCurrentChange = (val: number) => {
  tableParams.value.page = val;
  handleQuery();
};

const mesProductionLineTypeProductionLineTypeCodeDropdownList = ref<any>([]);
const getMesProductionLineTypeProductionLineTypeCodeDropdownList = async () => {
  let list = await getMesProductionLineTypeProductionLineTypeCodeDropdown();
  mesProductionLineTypeProductionLineTypeCodeDropdownList.value = list.data.result ?? [];
};
getMesProductionLineTypeProductionLineTypeCodeDropdownList();

const mesWorkShopFactoryCodeDropdownList = ref<any>([]);
const getMesWorkShopFactoryCodeDropdownList = async () => {
  let list = await getMesWorkShopFactoryCodeDropdown();
  mesWorkShopFactoryCodeDropdownList.value = list.data.result ?? [];
};
getMesWorkShopFactoryCodeDropdownList();
// 树组件点击
const nodeClick = async (node: any) => {
  delete queryParams.value.factoryCode;
  delete queryParams.value.workShopCode;
  if(node.sign==1){
    queryParams.value.factoryCode = node.code;
  }else if(node.sign==2){
    queryParams.value.workShopCode = node.code;
  }
  handleQuery();
};
handleQuery();
</script>
<style scoped>
:deep(.el-ipnut),
:deep(.el-select),
:deep(.el-input-number) {
  width: 100%;
}
</style>
