﻿<template>
	<div class="mesWorkTeam-container">
		<el-dialog v-model="isShowDialog" :width="800" draggable="" :close-on-click-modal="false" :fullscreen="fullScreen">
      <template #header>
        <div style="color: #fff;display: flex;align-items: center;justify-content: space-between;">
          <span>{{ props.title }}</span>
          <el-icon size="16" @click="fullScreen = !fullScreen" style="margin-right: 16px; display: block; vertical-align: middle;cursor: pointer">
            <ele-FullScreen v-if="!fullScreen" />
            <ele-Notification v-else />
          </el-icon>
        </div>
      </template>
			<el-form :model="ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
				<el-row :gutter="35">
					<el-form-item v-show="false">
						<el-input v-model="ruleForm.id" />
					</el-form-item>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="班组编码" prop="workTeamCode">
							<el-input v-model="ruleForm.workTeamCode" placeholder="请输入班组编码" maxlength="100" show-word-limit clearable />

						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="班组名称" prop="workTeamName">
							<el-input v-model="ruleForm.workTeamName" placeholder="请输入班组名称" maxlength="100" show-word-limit clearable />

						</el-form-item>

					</el-col>
<!--					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">-->
<!--						<el-form-item label="班制编码" prop="workTeamSeqCode">-->
<!--							<el-input v-model="ruleForm.workTeamSeqCode" placeholder="请输入班制编码" maxlength="100" show-word-limit clearable />-->
<!--						</el-form-item>-->
<!--					</el-col>-->
<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="所属工厂编码" prop="factoryCode">
							<el-select clearable filterable v-model="ruleForm.factoryCode" placeholder="请选择所属工厂编码">
								<el-option v-for="(item, index) in mesFactoryFactoryCodeDropdownList" :key="index"
									:value="item.value" :label="item.label" />

							</el-select>

						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="班长" prop="teamManageName">
              <el-input v-model="ruleForm.teamManageName" placeholder="请选班长" readonly show-word-limit clearable >
                <template #append>
                  <el-button icon="ele-Edit" @click="choosePerson"></el-button>
                </template>
              </el-input>
						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="备注" prop="remark">
							<el-input v-model="ruleForm.remark" placeholder="请输入备注" show-word-limit clearable />

						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="排序" prop="sorts">
							<el-input-number v-model="ruleForm.sorts" placeholder="请输入排序" clearable />

						</el-form-item>

					</el-col>
<!--					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">-->
<!--						<el-form-item label="创建者部门名称" prop="createOrgName">-->
<!--							<el-input v-model="ruleForm.createOrgName" placeholder="请输入创建者部门名称" maxlength="64" show-word-limit clearable />-->
<!--						</el-form-item>-->
<!--					</el-col>-->
				</el-row>
			</el-form>
      <el-tabs v-model="activeChild" class="tabs" style="font-size:12px !important;">
        <el-tab-pane label="关联员工" name="staff"></el-tab-pane>
        <el-tab-pane label="关联产线" name="workshop"></el-tab-pane>
        <el-tab-pane label="关联设备" name="equipment"></el-tab-pane>
      </el-tabs>
      <el-button icon="el-icon-plus" type="primary" @click="subAdd" class="subaddBtn">新增</el-button>
      <el-table :data="staffTableData" style="width: 100%" tooltip-effect="light" row-key="id" border="" v-show="activeChild == 'staff'">
        <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-column label="操作" width="140" align="center" fixed="right">
          <template #default="scope">
            <el-button icon="ele-Delete" size="small" type="primary"
                       @click="subDelete(scope.row, scope.$index)">
              删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-table :data="workshopTableData" style="width: 100%" tooltip-effect="light" row-key="id" border="" v-show="activeChild == 'workshop'">
        <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 label="操作" width="140" align="center" fixed="right">
          <template #default="scope">
            <el-button icon="ele-Delete" size="small" type="primary"
                       @click="subDelete(scope.row, scope.$index)">
              删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-table :data="equipmentTableData" style="width: 100%" tooltip-effect="light" row-key="id" border="" v-show="activeChild == 'equipment'">
        <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-column label="操作" width="140" align="center" fixed="right">
          <template #default="scope">
            <el-button icon="ele-Delete" size="small" type="primary"
                       @click="subDelete(scope.row, scope.$index)">
              删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="submit">确 定</el-button>
				</span>
			</template>
		</el-dialog>
    <!--  人员选择组件  -->
    <choose-user title="选择人员" ref="chooseUserRef" :is-any="true" @finish="onChooseFinish"></choose-user>
    <choose-user title="选择班长" ref="choosePersonRef" :is-any="false" @finish="onChoosePersonFinish"></choose-user>
    <!--  产线选择组件  -->
    <choose-production-line title="选择产线" ref="chooseWorkShopRef" :is-any="true" @finish="onChooseFinish"></choose-production-line>
    <!--  设备选择组件  -->
    <choose-equipment  title="选择设备" ref="chooseEquipmentRef" :is-any="true" @finish="onChooseFinish"></choose-equipment>
	</div>
</template>
<style scoped>
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>
<script lang="ts" setup>
	import { ref,onMounted } from "vue";
	import { getDictDataItem as di, getDictDataList as dl } from '/@/utils/dict-utils';
	import { ElMessage } from "element-plus";
	import type { FormRules } from "element-plus";
	import { addMesWorkTeam, updateMesWorkTeam, detailMesWorkTeam } from "/@/api/mes/mesWorkTeam";
  import ChooseUser from "/@/businessComponents/chooseUser.vue";
  import ChooseProductionLine from "/@/businessComponents/chooseProductionLine.vue";
  // import {getWorkShopTree} from "/@/api/mes/mesProductionLine";
  import chooseEquipment from "/@/businessComponents/chooseEquipment.vue"
  import { getMesFactoryFactoryCodeDropdown } from '/@/api/mes/mesWorkShop';
	//父级传递来的参数
	var props = defineProps({
		title: {
		type: String,
		default: "",
	},
	});
	//父级传递来的函数，用于回调
	const emit = defineEmits(["reloadTable"]);
	const ruleFormRef = ref();
	const isShowDialog = ref(false);
	const ruleForm = ref<any>({});
  const activeChild = ref('staff');
  let fullScreen = ref(false);
  // 子表
  const staffTableData = ref([]);
  const equipmentTableData = ref([]);
  const workshopTableData = ref([]);
	//自行添加其他规则
	const rules = ref<FormRules>({
		workTeamCode: [{required: true, message: '请输入班组编码！', trigger: 'blur',},],
		workTeamName: [{required: true, message: '请输入班组名称！', trigger: 'blur',},],
	});

	// 打开弹窗
	const openDialog = async (row: any) => {
		// ruleForm.value = JSON.parse(JSON.stringify(row));
		// 改用detail获取最新数据来编辑
    activeChild.value = "staff";
    staffTableData.value = [];
    equipmentTableData.value = [];
    workshopTableData.value = [];
		let rowData = JSON.parse(JSON.stringify(row));
		if (rowData.id){
      let data = (await detailMesWorkTeam(rowData.id)).data.result;
      data.teamManageName = data.teamManageInfo.realName;
      ruleForm.value = data
      // 映射子表
      // -人员
      staffTableData.value = (data.personCodes || "").split(',').filter(item=>item).map((item, index) => {
        return{
          account:item || "",
          realName:(data.personNames || "").split(',').filter(item=>item)?.[index] || ""
        }
      })
      // -产线
      workshopTableData.value = (data.productionLineCodes || "").split(',').filter(item=>item).map((item, index) => {
        return{
          productionLineCode:item || "",
          productionLineName:(data.productionLineNames || "").split(',').filter(item=>item)?.[index] || ""
        }
      })
      // -设备
      equipmentTableData.value = (data.equipmentCodes || "").split(',').filter(item=>item).map((item, index) => {
        return{
          equipmentCode:item || "",
          equipmentName:(data.equipmentNames || "").split(',').filter(item=>item)?.[index] || ""
        }
      })

    } else{
      ruleForm.value = rowData;
    }
		isShowDialog.value = true;
	};

	// 关闭弹窗
	const closeDialog = () => {
		emit("reloadTable");
		isShowDialog.value = false;
	};

	// 取消
	const cancel = () => {
		isShowDialog.value = false;
	};

	// 提交
	const submit = async () => {
		ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
			if (isValid) {
				let values = ruleForm.value;
        // 人员绑定
        values.personCodes = staffTableData.value.map((item: any) => item.account).join(',');
        values.personNames = staffTableData.value.map((item: any) => item.realName).join(',');
        // 设备绑定
        values.equipmentCodes = equipmentTableData.value.map((item: any) => item.equipmentCode).join(',');
        values.equipmentNames = equipmentTableData.value.map((item: any) => item.equipmentName).join(',');
        // 产线绑定
        values.productionLineCodes = workshopTableData.value.map((item: any) => item.productionLineCode).join(',');
        values.productionLineNames = workshopTableData.value.map((item: any) => item.productionLineName).join(',');

				if (ruleForm.value.id == undefined || ruleForm.value.id == null || ruleForm.value.id == "" || ruleForm.value.id == 0) {
					await addMesWorkTeam(values);
				} else {
					await updateMesWorkTeam(values);
				}
				closeDialog();
			} else {
				ElMessage({
					message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
					type: "error",
				});
			}
		});
	};

 const chooseUserRef = ref();
 const chooseWorkShopRef = ref();
 const chooseEquipmentRef = ref();
 const subAdd = ()=>{
   if(activeChild.value === 'staff'){
     chooseUserRef.value.openDialog({
       factoryCode:ruleForm.value.factoryCode
     });
   }
   if(activeChild.value === 'workshop'){
     chooseWorkShopRef.value.openDialog({
       // factoryCode:ruleForm.value.factoryCode
     });
   }
   if(activeChild.value === 'equipment'){
     chooseEquipmentRef.value.openDialog({});
   }
 }


 const onChooseFinish = (data:any)=>{
   console.log(data);
   if(activeChild.value === 'staff'){
     let list:any[] = (data?.rows || []).map((item:any)=>({
       ...item,
       realName:item.realName,
       account:item.account
     }))
     list.forEach(el=>{
       let isHas = staffTableData.value.find(item=> item.account == el.account)
       if(isHas){}else{
         staffTableData.value.push(el);
       }
     })
     // staffTableData.value.push(...list);
   }
   if(activeChild.value === 'workshop'){
     let list:any[] = (data?.rows || []).map((item:any)=>({
       ...item,
       workShopCode:item.workShopCode,
       workShopName:item.workShopName
     }))
     list.forEach(el=>{
       let isHas = workshopTableData.value.find(item=> item.productionLineCode == el.productionLineCode)
       if(isHas){}else{
         workshopTableData.value.push(el);
       }
     })
     // workshopTableData.value.push(...list);
   }
   if(activeChild.value === 'equipment'){
     let list:any[] = (data?.rows || []).map((item:any)=>({
       ...item,
       equipmentName:item.equipmentName,
       equipmentCode:item.equipmentCode
     }))
     list.forEach(el=>{
       let isHas = equipmentTableData.value.find(item=> item.equipmentCode == el.equipmentCode)
       if(isHas){}else{
         equipmentTableData.value.push(el);
       }
     })
     // equipmentTableData.value.push(...list);
   }
 }


  // 删除子表
  const subDelete = (row: any, index: number) => {
    if(activeChild.value === 'staff'){
      staffTableData.value.splice(index, 1)
    }
    if(activeChild.value === 'equipment'){
      equipmentTableData.value.splice(index, 1)
    }
    if(activeChild.value === 'workshop'){
      workshopTableData.value.splice(index, 1)
    }
  };

  // const mesWorkShopTypeTreeData = ref<any>([]);
  // const getMesWorkShopTypeTreeData = async () => {
  //   let list = await getWorkShopTree(3);
  //   mesWorkShopTypeTreeData.value = list.data.result ?? [];
  // };
  // getMesWorkShopTypeTreeData();

  const choosePersonRef = ref();

  const choosePerson = ()=>{
    choosePersonRef.value.openDialog({
      factoryCode:ruleForm.value.factoryCode
    });
  }

  const onChoosePersonFinish =  (data:any)=>{
    ruleForm.value.teamManageId =  data.id;
    ruleForm.value.teamManageName =  `[${data.id}]${data.nickName}`;
  }

  const mesFactoryFactoryCodeDropdownList = ref<any>([]);
const getMesFactoryFactoryCodeDropdownList = async () => {
	let list = await getMesFactoryFactoryCodeDropdown();
	mesFactoryFactoryCodeDropdownList.value = list.data.result ?? [];
};
getMesFactoryFactoryCodeDropdownList();

	// 页面加载时
	onMounted(async () => {
	});

	//将属性或者函数暴露给父组件
	defineExpose({ openDialog });
</script>
<style scoped>
 :deep(.el-tabs .el-tabs__header .el-tabs__item){
  font-size:12px !important;
   text-align: center;
}
</style>




