﻿<template>
	<div class="mesProductionLine-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="productionLineCode">
							<el-input v-model="ruleForm.productionLineCode" 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="productionLineName">
							<el-input v-model="ruleForm.productionLineName" 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="productionLineTypeCode">
							<el-select clearable filterable v-model="ruleForm.productionLineTypeCode"
								placeholder="请选择产线类别" @change="detail">
								<el-option
									v-for="(item, index) in mesProductionLineTypeProductionLineTypeCodeDropdownList"
									:key="index" :value="item.value" :label="`[${item.value}]` + 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="sign">
							<el-input v-model="ruleForm.sign" disabled 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="workShopCode">
							<el-select clearable filterable v-model="ruleForm.workShopCode" placeholder="请选择所属车间">
								<el-option v-for="(item, index) in mesWorkShopFactoryCodeDropdownList" :key="index"
									:value="item.value" :label="`[${item.value}]` + 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="holidayType">
							<el-select clearable filterable v-model="ruleForm.holidayType" placeholder="请选择公休日类型">
								<el-option v-for="(item,index) in mesHolidayTypeHolidayTypeDropdownList" :key="index" :value="item.value" :label="item.label" />
								
							</el-select>

						</el-form-item>

					</el-col> -->
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="备注" prop="remark">
							<el-input v-model="ruleForm.remark" placeholder="请输入备注" type="textarea" 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="sorts">
							<el-input-number v-model="ruleForm.sorts" placeholder="请输入排序" clearable />

						</el-form-item>

					</el-col>
				</el-row>
			</el-form>
      <el-tabs  v-model="activeChild">
        <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-button icon="el-icon-plus" type="primary" @click="subAdd" class="subaddBtn">新增</el-button>
      <!--   设备  -->
      <el-table v-if="activeChild == 'equipment'" :data="equipmentTableData || []" style="width: 100%"  tooltip-effect="light" row-key="id" border="">
        <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>
      <!--   人员   -->
      <el-table  v-if="activeChild == 'person'"  :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>
      <!--   产品   -->
      <el-table  v-if="activeChild == 'product'"  :data="productTableData || []" style="width: 100%"  tooltip-effect="light" row-key="id" border="">
        <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-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-equipment title="选择设备" ref="chooseEquipmentRef" :is-any="true" @finish="onChooseFinish"></choose-equipment>
    <!--   选择产品  -->
    <choose-product title="选择产品" ref="chooseProductRef" :is-any="true" type="2" @finish="onChooseFinish"></choose-product>
    <!--   选择人员  -->
    <choose-user title="选择人员" ref="chooseUserRef" :is-any="true" @finish="onChooseFinish"></choose-user>
	</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 { addMesProductionLine, updateMesProductionLine, detailMesProductionLine } from "/@/api/mes/mesProductionLine";
import { getMesProductionLineTypeProductionLineTypeCodeDropdown } from '/@/api/mes/mesProductionLine';
import { getMesWorkShopFactoryCodeDropdown } from '/@/api/mes/mesProductionLine';
import { getMesHolidayTypeHolidayTypeDropdown } from '/@/api/mes/mesProductionLine';
import chooseEquipment from '/@/businessComponents/chooseEquipment.vue';
import chooseProduct from '/@/businessComponents/chooseMaterial.vue';
import ChooseUser from "/@/businessComponents/chooseUser.vue";
let fullScreen = ref(false);
//父级传递来的参数
var props = defineProps({
	title: {
		type: String,
		default: "",
	},
});
//父级传递来的函数，用于回调
const emit = defineEmits(["reloadTable"]);
const ruleFormRef = ref();
const isShowDialog = ref(false);
const ruleForm = ref<any>({});
//自行添加其他规则
const rules = ref<FormRules>({
	productionLineCode: [{ required: true, message: '请输入产线编码！', trigger: 'blur', },],
	productionLineTypeCode: [{ required: true, message: '请输入选择产线类别！', trigger: 'blur', },],
	productionLineName: [{ required: true, message: '请输入产线名称！', trigger: 'blur', },],
	// holidayType: [{ required: true, message: '请选择公休日类型！', trigger: 'change', },],
});

const activeChild = ref('equipment');
const equipmentTableData = ref([]);
const personTableData = ref([]);
const productTableData = ref([]);

const chooseUserRef = ref();
const chooseEquipmentRef = ref();
const chooseProductRef = ref();

const subAdd = () => {
  if (activeChild.value === 'person') {
    chooseUserRef.value.openDialog({});
  }
  if (activeChild.value === 'equipment') {
    chooseEquipmentRef.value.openDialog({});
  }
  if (activeChild.value === 'product') {
    chooseProductRef.value.openDialog({});
  }
};


// 删除子表
const subDelete = (row: any, index: number) => {
  if (activeChild.value === 'person') {
    personTableData.value.splice(index, 1);
  }
  if (activeChild.value === 'equipment') {
    equipmentTableData.value.splice(index, 1);
  }
  if (activeChild.value === 'product') {
    productTableData.value.splice(index, 1);
  }
};

const onChooseFinish = (data: any) => {
  console.log(data);
  if (activeChild.value === 'person') {
    let list: any[] = (data?.rows || []).map((item: any) => ({
      ...item,
      realName: item.realName,
      account: item.account,
    }));
    list.forEach(el=>{
      let isHas = personTableData.value.find(item=> item.account == el.account)
      if(isHas){}else{
        personTableData.value.push(el);
      }
    })

  }
  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);
  }
  if (activeChild.value === 'product') {
    let list: any[] = (data?.rows || []).map((item: any) => ({
      ...item,
      productName: item.materialName,
      productCode: item.materialCode,
    }));
    list.forEach(el=>{
      let isHas = productTableData.value.find(item=> item.productCode == el.productCode)
      if(isHas){}else{
        productTableData.value.push(el);
      }
    })
    // productTableData.value.push(...list);
  }

};







// 打开弹窗
const openDialog = async (row: any) => {
	// ruleForm.value = JSON.parse(JSON.stringify(row));
	// 改用detail获取最新数据来编辑
  activeChild.value = 'equipment';
  personTableData.value = [];
  equipmentTableData.value = [];
  productTableData.value = [];

  getMesProductionLineTypeProductionLineTypeCodeDropdownList();
getMesWorkShopFactoryCodeDropdownList();
// getMesHolidayTypeHolidayTypeDropdownList();

	let rowData = JSON.parse(JSON.stringify(row));
	if (rowData.id){
    let data = (await detailMesProductionLine(rowData.id)).data.result;
    ruleForm.value = data;
    ruleForm.value.sign = ruleForm.value.productionLineTypeCodeInfo?.sign;
    // 映射子表
    // -人员
    personTableData.value = (data.personCodes || '')
        .split(',')
        .filter((item) => item)
        .map((item, index) => {
          return {
            account: item || '',
            realName: (data.personNames || '').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] || '',
          };
        });
    // -产品
    productTableData.value = (data.productCodes || '')
        .split(',')
        .filter((item) => item)
        .map((item, index) => {
          return {
            productCode: item || '',
            productName: (data.productNames || '').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 detail = (r) => {
	console.log(r)
	ruleForm.value.sign = mesProductionLineTypeProductionLineTypeCodeDropdownList.value.filter(item => item.value == r)[0].sign
};
// 提交
const submit = async () => {
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			let values = ruleForm.value;
      // 人员绑定
      values.personCodes = personTableData.value.map((item: any) => item.account).join(',');
      values.personNames = personTableData.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.productCodes = productTableData.value.map((item: any) => item.productCode).join(',');
      values.productNames = productTableData.value.map((item: any) => item.productName).join(',');
			if(values.workShopCode){
				var _t = mesWorkShopFactoryCodeDropdownList.value.find((u:any)=> u.value==values.workShopCode);
				values.factoryCode = _t.factoryCode;
			}
			if (ruleForm.value.id == undefined || ruleForm.value.id == null || ruleForm.value.id == "" || ruleForm.value.id == 0) {
				await addMesProductionLine(values);
			} else {
				await updateMesProductionLine(values);
			}
			closeDialog();
		} else {
			ElMessage({
				message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
				type: "error",
			});
		}
	});
};

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

const mesWorkShopFactoryCodeDropdownList = ref<any>([]);
const getMesWorkShopFactoryCodeDropdownList = async () => {
	let list = await getMesWorkShopFactoryCodeDropdown();
	mesWorkShopFactoryCodeDropdownList.value = list.data.result ?? [];
};




const mesHolidayTypeHolidayTypeDropdownList = ref<any>([]); 
	const getMesHolidayTypeHolidayTypeDropdownList = async () => {
		let list = await getMesHolidayTypeHolidayTypeDropdown();
		mesHolidayTypeHolidayTypeDropdownList.value = list.data.result ?? [];
	};




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

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