﻿<template>
	<div class="mesWorkGroup-container">
		<el-dialog v-model="state.isShowDialog" v-if="state.isShowDialog" :width="800" draggable="" :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<!--<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit /> </el-icon>-->
					<span>{{ props.title }}</span>
				</div>
			</template>
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
				<el-row :gutter="35">
					<el-form-item v-show="false">
						<el-input v-model="state.ruleForm.id" />
					</el-form-item>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="工作组编码" prop="workGroupCode">
							<el-input v-model="state.ruleForm.workGroupCode" 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="workGroupName">
							<el-input v-model="state.ruleForm.workGroupName" 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="productionLineCode">
							<el-select clearable filterable v-model="state.ruleForm.productionLineCode" placeholder="请选择产线">
								<el-option v-for="(item,index) in mesProductionLineProductionLineCodeDropdownList" :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="personCodes">-->
<!--							<el-input v-model="state.ruleForm.personCodes" placeholder="请输入人员编码，多个逗号分割" maxlength="800" 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="personNames">-->
<!--							<el-input v-model="state.ruleForm.personNames" placeholder="请输入人员名称，多个逗号分割" maxlength="800" show-word-limit clearable />-->

<!--						</el-form-item>-->

<!--					</el-col>-->
				</el-row>
			</el-form>
      <el-tabs  :model-value="'item'">
        <el-tab-pane label="人员明细"  name="item"></el-tab-pane>
      </el-tabs>
      <el-button icon="el-icon-plus" type="primary" @click="subAdd" class="subaddBtn">新增</el-button>
      <!--   人员   -->
      <el-table   :data="personTableData" style="width: 100%" tooltip-effect="light" row-key="id" border="">
        <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>
			<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>
	</div>
</template>
<style lang="scss" scoped>
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>
<script lang="ts" setup>
    import { ref,onMounted, reactive } from "vue";
	import { ElMessage } from "element-plus";
	import type { FormRules } from "element-plus";
	import { addMesWorkGroup, updateMesWorkGroup, detailMesWorkGroup } from "/@/api/mes/mesWorkGroup";
	import { pageMesWorkGroup, deleteMesWorkGroup } from '/@/api/mes/mesWorkGroup';
	import { getMesProductionLineProductionLineCodeDropdown } from '/@/api/mes/mesWorkGroup';

  	import { formatDate } from '/@/utils/formatTime';
    import ChooseUser from "/@/businessComponents/chooseUser.vue";
    import {pageMesProductionLine} from "/@/api/mes/mesProductionLine";

	//父级传递来的参数
	var props = defineProps({
		title: {
		type: String,
		default: "",
	},
	});
	//父级传递来的函数，用于回调
	const emit = defineEmits(["reloadTable"]);
	const ruleFormRef = ref();
    const state = reactive({
    isShowDialog: false,
    ruleForm: {} as any,
});


    const personTableData = ref([]);
    const chooseUserRef = ref();
    const subAdd = () => {
      if(!state.ruleForm.productionLineCode) return ElMessage.warning('请选择产线');
        chooseUserRef.value.openDialog({
          productionLineCode:state.ruleForm.productionLineCode
        });
    };
    // 删除子表
    const subDelete = (row: any, index: number) => {
        personTableData.value.splice(index, 1);
    };
    const onChooseFinish = (data: any) => {
      console.log(data);
      let list: any[] = (data?.rows || []).map((item: any) => ({
        ...item,
        realName: item.realName,
        account: item.account,
      }));
      personTableData.value.push(...list);
    };




    //自行添加其他规则
	const rules = ref<FormRules>({
		workGroupCode: [{required: true, message: '请输入工作组编码！', trigger: 'blur',},],
		workGroupName: [{required: true, message: '请输入工作组名称！', trigger: 'blur',},],
	});

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

	});

	// 打开弹窗
	const openDialog = async (row: any) => {
		// state.ruleForm = JSON.parse(JSON.stringify(row));
    personTableData.value = [];
		// 改用detail获取最新数据来编辑
		let rowData = JSON.parse(JSON.stringify(row));
		if (rowData.id){
      let data = (await detailMesWorkGroup(rowData.id)).data.result;
      state.ruleForm = data;
      // -人员
      personTableData.value = (data.personCodes || '')
          .split(',')
          .filter((item) => item)
          .map((item, index) => {
            return {
              account: item || '',
              realName: (data.personNames || '').split(',').filter((item) => item)?.[index] || '',
            };
          });
    } else{
      state.ruleForm = rowData;
    }
		state.isShowDialog = true;
	};

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

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

	// 提交
	const submit = async () => {
		ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
			if (isValid) {
				let values = state.ruleForm;
        // 人员绑定
        values.personCodes = personTableData.value.map((item: any) => item.account).join(',');
        values.personNames = personTableData.value.map((item: any) => item.realName).join(',');
				if (state.ruleForm.id == undefined || state.ruleForm.id == null || state.ruleForm.id == "" || state.ruleForm.id == 0) {
					await addMesWorkGroup(values);
				} else {
					await updateMesWorkGroup(values);
				}
				closeDialog();
			} else {
				ElMessage({
					message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
					type: "error",
				});
			}
		});
	};

	const mesProductionLineProductionLineCodeDropdownList = ref<any>([]);
	const getMesProductionLineProductionLineCodeDropdownList = async () => {
		let list = await getMesProductionLineProductionLineCodeDropdown();
		mesProductionLineProductionLineCodeDropdownList.value = list.data.result ?? [];
	};
	getMesProductionLineProductionLineCodeDropdownList();






	//将属性或者函数暴露给父组件
	defineExpose({ openDialog });
</script>




