<template>
	<lay-container fluid="true" class="content-box">
		<FormulaView :teamId="dataInfoObj.FTeamID" :halfId="dataInfoObj.FMaterialHalfIDs"></FormulaView>		
		<lay-layer area="90%" v-model="showFreezingColumnSettingBox" title="固定列设置" :end="closeFreezingSetting">
			<FreezingColumnSetting v-if="showFreezingColumnSettingBox" :columns="originalColumns" :freezingColumns="freezingColumnSetting" @cancelClick="setFreezingColumnsSetting"></FreezingColumnSetting>
		</lay-layer>
		<lay-table id="dataTable" v-if="dataColumn.length>0" height="320px" :columns="dataColumn"
				   :data-source="dataList" :cellStyle="cellStyle" :cellClassName="cellClassName">
			<template v-slot:toolbar v-if="dataInfoObj.FCanEdit!=2">
				<lay-button size="sm" @click="saveBatch" type="primary" :disabled="editColumn.length===0">保存
				</lay-button>
				<lay-input :class="this.isShow ? 'isShow' : 'isHidden'" v-model="inputCodeValue" :readonly="true">
					<template #prepend>半成品编号：</template>
				</lay-input>
				<lay-input :class="this.isShow ? 'isShow' : 'isHidden'" v-model="inputDescValue" :readonly="true">
					<template #prepend>描述：</template>
				</lay-input>
				<lay-button size="sm" type="primary" style="float:right;" :disabled="editColumn.length===0" @click="_clickFreezingColumnSetting()">固定项
				</lay-button>
			</template>
			<template v-for="item in editColumn" v-slot:[item.key]="{ data }">
				<lay-select v-if="item.key=='FTypeID1'" size="sm" v-model="data['FTypeID1']"
							@change="_changeType(data,1)" :showEmpty="false">
					<lay-select-option v-for="(tIdv,tIdx) in typeList[0]" :key="tIdx" :value="tIdv.FID"
									   :label="tIdv.FName"></lay-select-option>
				</lay-select>
				<lay-select v-else-if="item.key=='FTypeID2'" size="sm" v-model="data['FTypeID2']"
							@change="_changeType(data,2)" :showEmpty="false">
					<lay-select-option v-show="data.FTypeID1==tIdv.FParentID" v-for="(tIdv,tIdx) in typeList[1]"
									   :key="tIdx" :value="tIdv.FID" :label="tIdv.FName"></lay-select-option>
				</lay-select>
				<lay-select v-else-if="item.selectType" size="sm" v-model="data[item.key]" :showEmpty="false">
					<lay-select-option v-for="(tIdv,tIdx) in selectDataMap['FType'+item.selectTypeId]" :key="tIdx"
									   :value="tIdv.FValue" :label="tIdv.FName"></lay-select-option>
				</lay-select>
				<lay-input v-else-if="!item.dataType" size="sm" v-model="data[item.key]"></lay-input>
			</template>
		</lay-table>
		<OperateLog v-if="dataInfoObj.FTeamID" ref="OperateLog" :dataInfoObj="dataInfoObj"></OperateLog>
	</lay-container>
</template>

<style scoped>
	.content-box {
		margin: 30px 10px;
		display: block;
		position: relative;
		clear: both;
		float: none;
		min-height: 740px;
	}

	.row-select td {
		overflow: inherit;
	}

	.layui-select {
		width: 100%;
	}

	.edit {
		color: green;
	}

	:deep(.edit-item .layui-input) {
		border-color: #5FB878 !important;
	}

	:deep(.edit-item .layui-input:hover) {
		border-color: #009688 !important;
		color: #009688;
	}
	.isShow{
		width: 370px;
		height:30px;
		border: none;
	}
	.isHidden{
		display: none;
	}
	.isBomHidden{
		display: none;
	}
</style>
<script>
	import {
		ref
	} from 'vue';
	import {
		getListByTeamId,
		updateBatchById2
	} from "/src/api/api/view";
	import {
		getBasicRoleList
	} from "/src/api/api/user";
	import {
		getDataCode,
		commonSave
	} from "/src/api/api/common";

	import {
		getInfoData,
		changeInfoData
	} from "/src/api/api/materialType";
	import OperateLog from "./OperateLog.vue";
	import FormulaView from "./FormulaView.vue";
	import FreezingColumnSetting from './FreezingColumnSetting.vue';

	export default {
		components: {
			OperateLog,
			FormulaView,
			FreezingColumnSetting
		},
		setup() {
			const dataColumn = ref([]);
			const dataList = ref([]);
			const editColumn = ref([]);
			const selectDataMap = ref(null);
			const typeList = ref([
				[],
				[]
			]);
			const userPower = ref([
				[],
				[]
			]);
			const cellStyle = function(row, column, rowIndex, columnIndex) {
				let back = column.table == "TFS_ViewMaterial" ? "background:rgb(246, 246, 246) !important;" : ""
				return back;
			}
			const cellClassName = function(row, column, rowIndex, columnIndex) {
				return column.cellClass || "";
			}
			const inputCodeValue = ref("");
			const inputDescValue = ref("");
			const visible2 = ref(false)
			const changeVisible2 = function() {
				visible2.value = !visible2.value
			};
			const showFreezingColumnSettingBox = ref(false);
			const freezingColumnSetting = ref([]);
			const originalColumns = ref([]);
			const tmpDataColumn = ref([]);
			return {
				dataColumn,
				dataList,
				editColumn,
				selectDataMap,
				typeList,
				userPower,
				cellStyle,
				cellClassName,
				inputCodeValue,
				inputDescValue,
				isShow: false,
				isBomShow :false,
				visible2,
				changeVisible2,
				showFreezingColumnSettingBox,
				freezingColumnSetting,
				originalColumns,
				tmpDataColumn
			};
		},
		props: {
			dataInfoObj: {
				type: Object,
				default: () => {},
			},
			viewDataList: {
				type: Object,
				default: () => [],
			}
		},
		mounted() {
			this.getUserPower();
		},
		methods: {
			async getUserPower() {
				if (this.dataInfoObj.FCanEdit != 2) {
					this.userPower[0] = (await getBasicRoleList({
						FRoleType: 40,
						FViewType: this.dataInfoObj.FViewType
					}) || []).map(it => parseInt(it.F2))
					this.userPower[1] = (await getBasicRoleList({
						FRoleType: 44,
						FViewType: this.dataInfoObj.FViewType
					}) || []).map(it => parseInt(it.F2))
				}
				this.initPage(layer.load(2));
			},
			async initPage(idx) {
				let _data = await getListByTeamId({
					teamId: this.dataInfoObj.FTeamID,
					viewType: this.dataInfoObj.FViewType
				});

				if(this.dataInfoObj.FViewType == 1){
					this.inputCodeValue = _data.rows[0].HalfCode;
					this.inputDescValue = _data.rows[0].HalfDesc;
					this.isShow = true;
				}else if(this.dataInfoObj.FViewType == 2 || this.dataInfoObj.FViewType == 3 || this.dataInfoObj.FViewType == 4){
					this.isBomShow = true;
				}

				this.typeList[0] = _data.types.filter(s => s.FDepth == 1) || [];
				this.typeList[1] = _data.types.filter(s => s.FDepth != 1) || [];
				let dataColumn = _data.columns || [];
				let editColumn = dataColumn.filter(it => {
					let b = false;
					if (this.dataInfoObj.FCanEdit != 2) {
						if (it.fieldType == 7) b = this.userPower[1].indexOf(it.id) >= 0;
						else b = this.userPower[0].indexOf(it.id) >= 0;
						if (b) {
							it.customSlot = it.key;
							it.cellClass = "edit-item"
						}
					}
					return b;
				});
				if (editColumn.length > 0) {
					if (this.selectDataMap == null) {
						let dataTypeIds = editColumn.filter(it => {
							it.selectType = it.dataType.startsWith('select:');
							if (it.selectType) {
								it.selectTypeId = it.dataType.substring(7)
							}
							return it.selectType;
						}).map(it => it.selectTypeId);
						if (dataTypeIds.length > 0) {
							this.selectDataMap = await getDataCode({
								FType: dataTypeIds.join(",")
							});
						}
					}
					// //修改项移到前面
					// if (this.dataInfoObj.FCanEdit != 2) {
					// 	let tempColumn1 = dataColumn.filter(s => s.customSlot) || [];
					// 	let tempColumn2 = dataColumn.filter(s => s.customSlot == undefined) || [];
					// 	dataColumn = [...tempColumn1, ...tempColumn2];
					// }
				}
				let col7 = dataColumn.filter(s => s.fieldType == 7) || [];
				_data.rows.forEach((item) => {
					let k3Code = item.FBaseMaterialDesc;
					if(k3Code.indexOf("@") > 0){
						item.FK3Code = k3Code.substr(0, k3Code.indexOf("@"));
						item.FK3Name = k3Code.substr(k3Code.indexOf("@") +1);
					}else{
						item.FK3Code = "";
						item.FK3Name = "";
					}
					if(k3Code.lastIndexOf(".") > 0){
						item.FK3ShortCode = item.FK3Code.substr(item.FK3Code.lastIndexOf(".")+1);
					}else{
						item.FK3ShortCode = "";
					}
					let info = _data.infos.find(s => s.FDataID == item.FMaterialID) || null;
					if (info != null) {
						col7.forEach((col) => {
							item[col.key] = info[col.key] || item[col.key] || "";
						});
					}
					item.FTypeID1 = (item.FTypeID1 == 0 || item.FTypeID1 == -1) ? "" : item.FTypeID1;
					item.FTypeID2 = (item.FTypeID2 == 0 || item.FTypeID2 == -1) ? "" : item.FTypeID2;
				});
				let saveId = this.dataInfoObj.FViewType + "_" + this.dataInfoObj.FID;
				localStorage.setItem('EditView' + saveId, JSON.stringify(_data.rows));
				this.editColumn = editColumn;
				this.dataList = _data.rows;
				this.dataColumn = dataColumn;
				this.originalColumns = this.deepCopy(dataColumn);

				setTimeout(function() {
					layer.close(idx);
				}, 500);
			},
			cancelClick(isRefresh) {
				isRefresh = isRefresh == undefined ? false : isRefresh;
				this.$emit('cancelClick', isRefresh);
			},
			async _changeType(data, type) {
				if (type == 1) {
					data.FTypeID2 = -1;
				} else {
					if (data.FTypeID2) {
						let result = await getInfoData({
							"FDataID": data.FTypeID2,
							"FType": 1
						}) || null;
						if (result != null && result.FID) {
							let col7 = this.dataColumn.filter(s => s.fieldType == 7) || [];
							col7.forEach((item) => {
								if (item.table == "TFS_MaterialInfo") {
									data[item.key] = result[item.key] || data[item.key] || "";
								}
							});
						}
					}
				}
			},
			async saveBatch() {
				let idx = layer.load(2);
				let updateObj = {
					LogList: [],
					FTeamID: this.dataInfoObj['FTeamID'],
					FViewType: this.dataInfoObj.FViewType
				};
				let saveId = this.dataInfoObj.FViewType + "_" + this.dataInfoObj.FID;
				let cacheDataList = JSON.parse(localStorage.getItem('EditView' + saveId));
				this.dataList.forEach((row, index) => {
					let cache = cacheDataList[index];
					let dataObj = {};
					for (let col of this.editColumn) {
						let valTemp = row[col.key];
						if (valTemp != cache[col.key]) {
							if (!dataObj[col.table]) {
								dataObj[col.table] = {};
								dataObj[col.table].FMaterialID = row["FMaterialID"];
							}
							dataObj[col.table][col.key] = valTemp;
							if (col.key == "FTypeID1" || col.key == "FTypeID2") {
								let temps = this.typeList[col.key == "FTypeID1" ? 0 : 1] || [];
								let temp = temps.find(s => s.FID == valTemp) || null;
								valTemp = temp == null ? "" : temp.FName;
							}
							updateObj.LogList.push(col.title + "：" + (valTemp == "" ? "删除" : valTemp));
						}
					}
					for (let key in dataObj) {
						if (!updateObj[key]) updateObj[key] = [];
						updateObj[key].push(dataObj[key]);
					}
				});
				let updateLog = updateObj.LogList.join("、");
				if (updateLog != "") {
					delete updateObj.LogList
					// 发送保存请求
					let _result = await updateBatchById2(updateObj);
					if (_result.Code === 200) {
						await commonSave({
							teamId: updateObj.FTeamID,
							type: this.dataInfoObj['FType'],
							desc: updateLog
						}, "OperateLog");
						let $this = this;
						//$this.initPage();
						localStorage.setItem('EditView' + saveId, JSON.stringify(this.dataList));
						setTimeout(function() {
							layer.close(idx);
							layer.msg('保存成功');
							$this.$emit('cancelClick', true, true);
							$this.$refs.OperateLog._getPageList();
						}, 500);
					}
				} else {
					layer.close(idx);
					layer.msg('您没有做任何更改')
				}
			},
			_clickFreezingColumnSetting() {
				this.dataColumn = ref([]);
				this.showFreezingColumnSettingBox = true;
			},
			setFreezingColumns() {
				this.tmpDataColumn = this.deepCopy(this.originalColumns);
				let freezingColumns = [];
				if (this.freezingColumnSetting && this.freezingColumnSetting.length > 0) {
					this.freezingColumnSetting.forEach(column => {
						let colIndex = this.tmpDataColumn.findIndex(d => d.key === column);
						if (colIndex >= 0) {
							let fc = this.tmpDataColumn.splice(colIndex, 1)[0];
							if (fc) {
								fc.fixed = "left";
								freezingColumns.push(fc);
							}
						}
					})

					this.dataColumn = freezingColumns.concat(this.tmpDataColumn);
				} else {
					this.dataColumn = this.tmpDataColumn;
				}
			},
			setFreezingColumnsSetting(fcs) {
				this.freezingColumnSetting = fcs;
				if (fcs && fcs.length > 0) {
				} else {
					this.dataColumn = this.originalColumns;
				}
				this.showFreezingColumnSettingBox = false;
			},
			closeFreezingSetting() {
				this.setFreezingColumns();
			},
			deepCopy(arr) {
				return JSON.parse(JSON.stringify(arr))
			}
		}
	}
</script>
