<template>
	<div ref="mainDiv" class="l-layout">
    <PageTitle text="데이터 TREND" />
		<v-row ref="searchFilter">
			<v-col :cols="12">
				<v-card class="searchFilter">
					<v-row align="center" no-gutters>
						<v-col :cols="6">
							<DatepickerTimeSelectBox
								:parentPrgmId="myPrgmId"
								:label="'기간'"
                :labelCols="12"
                :textCols="8"
                :iconShow="true"
								:selectFromDtUntilTodayFg="true"
								:selectToDtUntilTodayFg="true"
								:selectBoxTimeItemList="selectBoxTimeItemList"
							/>
						</v-col>
            <v-col :cols="2" style="padding: 0px">
              <div style="height: 30px"></div>
							<CheckBoxLabelChange
								:parentPrgmId="myPrgmId"
								:label="'RawData'"
								valueNm="useFg"
								:icon="false"
								:required="true"
								:location="'rear'"
								:textCols="1"
								:labelCols="2"
								:disabledCheckOption="'chkEqualDayHourFg'"
                :isDarkMode="isDarkMode"
							/>
						</v-col>
            <v-col :cols="4" class="text-right">
              <div style="height: 30px"></div>

              <!-- <v-btn :ripple="false" @click="downloadExcelFile">액셀</v-btn> -->
              <!-- <v-btn :ripple="false" @click="search">조회</v-btn> -->
              <!-- <a-button
                style="height: 40px"
                class="basic-button"
                @click="downloadExcelFile"
                >액셀</a-button
              > -->
              <a-button
                style="height: 40px"
                @click="downloadExcelFile"
                v-bind="$attrs"
                type="default"
                class="btn-default"
                icon="file-excel"
                >액셀</a-button
              >
              <!-- <a-button icon="search" class="search-button" type="primary" @click="search"
                >조회</a-button
              > -->

              <a-button
                style="height: 40px"
                icon="search"
                class="search-button"
                type="primary"
                @click="search"
                >조회</a-button
              >
						</v-col>
					</v-row>
				</v-card>
			</v-col>
		</v-row>
		<v-row ref="contents">
      <v-col :cols="12" style="height: 100%; padding: 0px">
				<!-- <v-card class="pb-5"> -->
        <v-col :cols="12" style="height: 300px">
					<v-card class="pb-5 px-2">
						<div class="d-flex align-center justify-space-between pa-4">
							<v-col :cols="3" style="height: 100%">
                <v-card-title class="pa-0 custom-title-4">TAG 리스트</v-card-title>
							</v-col>
							<v-col :cols="3" style="height: 100%" class="text-right">
                <!-- <v-btn :ripple="false" @click="btnActions('add')">TAG 추가</v-btn>
                <v-btn :ripple="false" @click="btnActions('remove')">TAG 삭제</v-btn
                > -->
                <a-button class="basic-button" @click="btnActions('add')"
                  >TAG 추가</a-button
                >
                <a-button class="basic-button" @click="btnActions('remove')"
                  >TAG 삭제</a-button
								>
								<component
									ref="TagTrndTagPop"
									:is="'TagTrndTagPop'"
									:label="'test'"
									:parentPrgmId="myPrgmId"
									@gridEditingFinish="gridEditingFinish"
									@closePopEvent="closePopEvent"
								/>
							</v-col>
						</div>
            <div class="h100 px-5" style="height: calc(100% - 70px)">
							<div ref="gridParent" class="w100 h100">
								<component
									:ref="gridName"
									class="tagTrndGrid"
									:is="loadGrid ? 'Grid' : null"
									:gridName="gridName"
									:parentPrgmId="myPrgmId"
									@getRowsData="getRowData"
								/>
							</div>
						</div>
					</v-card>
				</v-col>
				<v-col
					v-show="!dumyChartFg"
					:cols="12"
					v-for="(item, index) in tagList"
					:key="'key_' + index"
					style="height: 65%"
				>
					<v-card class="pb-5 px-2">
						<div class="d-flex align-center justify-space-between">
              <v-card-title class="d-flex align-center justify-space-between pa-5">{{
                item
              }}</v-card-title>
						</div>
						<div :ref="'chartParent' + index" style="height: 90%">
							<component
								class="w100 h100"
								:is="loadChart ? 'Chart' : null"
								:parentPrgmId="myPrgmId"
								:chartName="chartNameList[index]"
								:ref="chartNameList[index]"
							/>
						</div>

						<!-- <div class="d-flex align-center justify-space-between">
							<v-card-title class="pa-0">{{'test'}}</v-card-title>
						</div>
						<div :ref="'chartParent'" style="height: 75%">
							<component
								class="w100 h100"
								:is="loadChart ? 'Chart' : null"
								:parentPrgmId="myPrgmId"
								:chartName="chartName"
								:ref="chartName"
							/>
						</div> -->
					</v-card>
				</v-col>
        <v-col v-show="dumyChartFg" :cols="12" style="height: 60%">
					<v-card class="pb-5 px-2">
						<div class="d-flex align-center justify-space-between">
              <v-card-title class="d-flex align-center justify-space-between pa-5">{{
                "ICHEON.HVAC.EQP_HT_CH004.UT_HT_CH201.CHI_AMP_1A_PV"
              }}</v-card-title>
						</div>
            <div :ref="'chartParent' + 0" style="height: 100%; overflow: visible">
							<component
                style="margin-top: -45px; width: 100%; height: 450px"
								class="w100 h100"
								:is="'Chart'"
								:parentPrgmId="myPrgmId"
								:chartName="chartNameList[0]"
								:ref="chartNameList[0]"
							/>
						</div>
					</v-card>
				</v-col>
				<!-- </v-card> -->
			</v-col>
		</v-row>
	</div>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import mixinGlobal from "@/mixin/global.js";
import { resize } from "@/mixin/resize.js";
import DatepickerTimeSelectBox from "~/components/common/DatepickerTimeSelectBox";
import CheckBoxLabelChange from "~/components/common/checkbox/CheckBoxLabelChange";
import Utility from "~/plugins/utility";
import BtnSearch from "~/components/common/button/BtnSearch";
import BtnExcelDownload from "~/components/common/button/BtnExcelDownload";
import DateUtility from "~/plugins/dateUtility";
import Grid from "~/components/common/Grid";
import TagTrndTagPop from "~/components/common/modal/TagTrndTagPop";
import Chart from "~/components/common/Chart";
import XLSX from "xlsx";
import PageTitle from "~/components/common/PageTitle";

let myTitle;
let myPrgmId;

export default {
	mixins: [mixinGlobal, resize],
	async asyncData(context) {
		const myState = context.store.state;
		myPrgmId = context.route.query.prgmId;
    console.log("menudata:", myState.menuData[myPrgmId]);
    await context.store.commit("setActiveMenuInfo", myState.menuData[myPrgmId]);
		myTitle = await myState.activeMenuInfo.menuNm;
	},
	meta: {
		title: () => {
			return myTitle;
		},
		prgmId: myPrgmId,
		closable: true,
	},
	components: {
		DatepickerTimeSelectBox,
		Utility,
		CheckBoxLabelChange,
		BtnSearch,
		BtnExcelDownload,
		Grid,
		TagTrndTagPop,
		Chart,
    PageTitle,
	},
	data() {
		return {
			myPrgmId: myPrgmId,
			initedFlag: false,
			selectBoxTimeItemList: {
        selectTimeValue1: "00 : 00", // selectBoxTime에 필요한 prop
				selectTimeValueList1: [], // selectBoxTime에 필요한 prop
        selectTimeValue2: "00 : 00", // selectBoxTime에 필요한 prop
				selectTimeValueList2: [], // selectBoxTime에 필요한 prop
				minInterval: 10,
			},
			useFg: false,
      gridName: "rowGrid",
			loadGrid: false,
			fromDt: Utility.setFormatDate(
				new Date(new Date().setMonth(new Date().getMonth() - 1)),
        "YYYYMMDD"
			),
      toDt: Utility.setFormatDate(new Date(), "YYYYMMDD"),
      today: Utility.setFormatDate(new Date(), "YYYYMMDD"),
      currentPagePath: "",
			loadChartList: [false, false, false, false, false],
      chartNameList: ["chart01", "chart02", "chart03", "chart04", "chart05"],
			tagList: [],
			loadChart: false,
			dumyChartFg: true,
			// chartName: 'chart01'
		};
	},
	computed: {
		chkIsFind() {
			// 조회 플래그
			return this.pageData.isFind;
		},
		chkFromDt() {
			return this.pageData.fromDt;
		},
		chkToDt() {
			return this.pageData.toDt;
		},
		chkSelectTimeValue1() {
			return this.pageData.selectTimeValue1;
		},
		chkSelectTimeValue2() {
			return this.pageData.selectTimeValue2;
		},
		chkUseFg() {
			return this.pageData.useFg;
		},
		chkTagList() {
			return this.pageData.tagList;
		},
    ...mapState({
      isDarkMode: "isDarkMode",
    }),
	},
	watch: {
		chkFromDt(val) {
			this.fromDt = val;
			this.today;
      let diff = DateUtility.diff(val, this.today, "day");
			if (diff >= 0) {
				this.setCheckBoxFg(val);
			}
		},
		chkToDt(val) {
			this.toDt = val;
			this.today;
			// 오늘 날짜 이상을 선택할 경우 -> 선택한 날짜 + 오늘 날짜로 2번 변경되어 선택한 날짜로 인해 메서드가 호출 되는 것을 방지
      let diff = DateUtility.diff(val, this.today, "day");
			if (diff >= 0) {
				this.setCheckBoxFg(val);
			}
		},
		chkIsFind(val) {
			// if (val) this.search();
		},
		chkSelectTimeValue1(val) {
			this.selectBoxTimeItemList.selectTimeValue1 = val;
			this.setCheckBoxFg(val);
		},
		chkSelectTimeValue2(val) {
			this.selectBoxTimeItemList.selectTimeValue2 = val;
			this.setCheckBoxFg(val);
		},
		chkUseFg(val) {
			this.useFg = val;
			// this.search();

			// if(this.fromDt+this.selectBoxTimeItemList.selectTimeValue1.slice(0, 2) == this.toDt+this.selectBoxTimeItemList.selectTimeValue2.slice(0, 2)){
			// 	this.useFg = val;
			// 	this.search();
			// }else{
			// 	alert('한 시간 이내일 경우만 선택할 수 있습니다.')
			// }
		},
		chkTagList(val) {
			// this.tagList = [...val];
			// chkTagList는 이벤트 감지용 무조건 grid의 row개수로 확인하고 진행
			let gridData = this.$refs[this.gridName].getData();
      let tagList = gridData.map((item) => {
				return item.tagId;
			});
			this.tagList = tagList;
			if (this.tagList.length == 0) {
				this.dumyChartFg = true;
			} else {
				this.dumyChartFg = false;
			}
			if (this.initedFlag && this.tagList.length > 0) {
				this.search();
			}
		},
	},
	async beforeCreate() {
		myPrgmId = this.$route.query.prgmId;
    await this.$store.dispatch("chkOpenTabList", {
      key: "create",
			prgmId: myPrgmId,
			defaultData: defaultData,
		});
	},
	created() {},
	async mounted() {
		this.currentPagePath = this.$router.currentRoute.fullPath;
		await this.init();
		let gridData = this.$refs[this.gridName].getData();
    let tagList = gridData.map((item) => {
			return item.tagId;
		});
		this.tagList = tagList;
		this.setPageData({
			tagList: tagList,
		});
		this.initedFlag = true;
	},
	beforeDestroy() {
		// await this.setChartNull();
		// for(var i=0; i<this.pageData.tagList; i++){

		// 	// this.$store.state.pageData[myPrgmId][this.chartNameList[i]]['xAxis'] =

		// 	Object.assign(
		// 		this.$store.state.pageData[myPrgmId][this.chartNameList[i]]['xAxis'],
		// 		[
		// 			{
		// 				data: [],
		// 				axisLabel: { interval: 0, rotate: 30 }
		// 			}
		// 		]
		// 	);

		// 	Object.assign(
		// 		this.$store.state.pageData[myPrgmId][this.chartNameList[i]]['series'],
		// 		[]
		// 	);
		// 	Object.assign(
		// 		this.$store.state.pageData[myPrgmId][this.chartNameList[i]]['legend'],
		// 		{
		// 			top: 'top',
		// 			left: 'center',
		// 			data: [],
		// 			textStyle: {
		// 				color: '#95A0A9',
		// 				fontSize: 10,
		// 			}
		// 		}
		// 	);
		// 	// this.$store.state.pageData[myPrgmId][this.chartNameList[i]]['legend'] =

		// }
    this.chkOpenTabList({ key: "destroy", prgmId: myPrgmId });
	},
	methods: {
		...mapMutations({
      setChartOption: "setChartOption",
      setChartYAxisData: "setChartYAxisData",
      setChartDetailXAxisData: "setChartDetailXAxisData",
      setChartSeries: "setChartSeries",
      setPageData: "setPageData",
		}),
		...mapActions({
      getCodeList: "modules/search/getCodeList",
      getBlocMstrList: "modules/search/getBlocMstrList",
      getAddInfoList: "modules/search/getAddInfoList",
		}),
		async init() {
			this.setPageData({
				rowGridSelectKey: 0,
				rowGridSelectData: null,
			});
			this.gridInit();
			this.setChartNull();
		},
		async search() {
			// search가 2번 타는 경우:
			// 1. fromDt: 2022-11-01 00:20 / toDt: 2022-12-09 00:00(오늘 날짜)
			// 2. fromDt를 오늘날짜로 변경 시 date 변경에 의한 search + 00:20 -> 00:00으로 변경되어 search
			if (this.tagList.length > 0) {
				await this.getTagData();
			} else {
        alert("TAG를 선택해주세요.");
			}

			this.setPageData({
				isFind: false,
			});
		},
		setCheckBoxFg(val) {
			let selectTimeValueList1 = this.selectBoxTimeItemList.selectTimeValueList1.map(
        (item) => {
					return item.value;
        }
			);
			let selectTimeValueList2 = this.selectBoxTimeItemList.selectTimeValueList2.map(
        (item) => {
					return item.value;
        }
			);
			let timeValueIndex1 = selectTimeValueList1.indexOf(
        this.selectBoxTimeItemList.selectTimeValue1
			);
			let timeValueIndex2 = selectTimeValueList2.indexOf(
        this.selectBoxTimeItemList.selectTimeValue2
			);
			if (this.fromDt == this.toDt && timeValueIndex2 - timeValueIndex1 <= 6) {
				this.setPageData({
					chkEqualDayHourFg: false,
				});
			} else {
				this.setPageData({
					chkEqualDayHourFg: true,
					useFg: false,
				});
			}
		},
		gridInit() {
			const gridHeight = this.$refs.gridParent.offsetHeight - 30;
			const myOptions = {
				columnOptions: {
					resizable: true,
				},
        header: {
          height: 38,
        },
			};
			this.setGridOption({
				gridKey: this.gridName,
				value: Object.assign(Utility.defaultGridOption(gridHeight), myOptions),
			});
			const _this = this;
			const myColumns = [
				// { header: '가이드ID', name: 'gdIdxId', align: 'center', hidden: true},
        { header: "설비그룹", name: "eqpmGrpNm", align: "left", width: 150 },
				{
          header: "설비그룹 ID",
          name: "eqpmGrpId",
          align: "center",
					hidden: true,
				},
        { header: "설비ID", name: "eqpmId", align: "left", width: 200 },
        { header: "설비명", name: "eqpmNm", align: "left", width: 200 },
        { header: "TAG ID", name: "tagId", align: "left", width: 500 },
        { header: "TAG 명", name: "tagNm", align: "left" },
        { header: "rowStat", name: "rowStat", align: "center", hidden: true },
      ];

      const newRes = [
        {
          eqpmGrpNm: "냉동기고온",
          eqpmGrpId: "UT_HT_CH201",
          eqpmId: "UT_HT_CH201",
          eqpmNm: "UT_HT_CH201",
          tagId: "ICHEON.HVAC.EQP_HT_CH004.UT_HT_CH201.CHI_AMP_1A_PV",
          tagNm: "ICHEON 고온 냉동기 201호기 - 회로1 전류A",
          // rowStat: "I",
        },
        {
          eqpmGrpNm: "냉동기고온",
          eqpmGrpId: "UT_HT_CH201",
          eqpmId: "UT_HT_CH201",
          eqpmNm: "UT_HT_CH201",
          tagId: "ICHEON.HVAC.EQP_HT_CH004.UT_HT_CH201.CHI_AMP_1A_PV",
          tagNm: "ICHEON 고온 냉동기 201호기 - 회로1 전류A",
          // rowStat: "I",
        },
			];
			this.setGridColumn({
				gridKey: this.gridName,
				value: myColumns,
			});
			this.loadGrid = true;
		},
		getRowData(data) {
			this.setPageData({
				rowGridSelectKey: data.rowKey,
				rowGridSelectData: data,
			});
		},
		async btnActions(action) {
			switch (action) {
        case "add" /*  */:
          console.log('aa:',this.tagList);
					// if(this.pageData.totalSelectedTags.split('/*wq2a/').length>5){
					if (this.tagList.length >= 5) {
            alert("TAG는 최대 5개까지 선택 가능합니다.");
					} else {
						const defaultRow = {
							eqpmGrpNm: null,
							eqpmGrpId: null,
							eqpmId: null,
							eqpmNm: null,
							tagId: null,
							tagNm: null,
              rowStat: "I",
						};
						// 바인딩할 row 추가
						this.$refs[this.gridName].addRow(defaultRow);
            this.$refs["TagTrndTagPop"].dialog = true;
					}
					break;

        case "remove":
					let nowGridData = [];
					nowGridData = this.$refs[this.gridName].getData();
					if (nowGridData.length <= 0) {
            alert("선택 된 태그가 없습니다.");
					} else {
						let tagList = [];
						tagList = this.tagList;
						let idx = tagList.indexOf(this.pageData.rowGridSelectData.tagId);
						// 삭제한 태그에 해당되는 차트의 pageData의 series, xAxis data 초기화 시켜주기
            this.$store.state.pageData[myPrgmId][this.chartNameList[idx]]["series"] = [];
            this.$store.state.pageData[myPrgmId][this.chartNameList[idx]]["xAxis"][0][
              "data"
						] = [];
            if (
              this.$store.state.pageData[myPrgmId][this.chartNameList[idx]]["xAxis"]
                .length > 1
						) {
              this.$store.state.pageData[myPrgmId][this.chartNameList[idx]]["xAxis"][1][
                "data"
              ] = [];
						}

            let newTagList = tagList.filter((item) => {
							return item != this.pageData.rowGridSelectData.tagId;
						});
						this.$refs[this.gridName].removeRow(
              "immediately",
              this.pageData.rowGridSelectKey
						);
						this.setPageData({
							// rowGridSelectData: null,
							// totalSelectedTags: newTotalSelectedTags,
							tagList: newTagList,
						});
						// let newTotalSelectedTags = this.pageData.totalSelectedTags.replace(this.pageData.rowGridSelectData.tagId+'/*wq2a/', '');
						// 마지막 row 선택 되도록 하는 로직
						let newGridData = [];
						newGridData = this.$refs[this.gridName].getData();
						if (newGridData.length > 0) {
							this.getRowData(newGridData[newGridData.length - 1]);
						}
						// focus 안됨 나중에 생각
						// this.$nextTick();
						// this.setPageData({
						// 	rowGridSelectData: newGridData[newGridData.length-1],
						// 	rowGridSelectKey: newGridData[newGridData.length-1].rowKey,
						// });
						// console.log('nowGridData', newGridData);
						// this.$nextTick(() => {
						// 	// 안됨...
						// 	if(newGridData.length>=0){
						// 		this.$refs[this.gridName].focus({
						// 			rowKey: newGridData.length-1,
						// 			columnName: 'tagId',
						// 			setScroll: true,
						// 		});
						// console.log('rowGridSelectData', this.pageData.rowGridSelectData);
						// 	}
						// });
					}
					break;

				default:
					break;
			}
		},
		gridEditingFinish(data) {
			this.$refs[this.gridName].editingFinish(data);
		},
		async getTagData() {
			let resDataDict = { tags: [] };
			let rawResDataDict = { tags: [] };
			let tagList = this.tagList;
			for (var i = 0; i < tagList.length; i++) {
				let sendParam = {};
				let bodyMap = {};
        let url = "http://58.232.11.31:1567/RTDBweapi/";
				// rawData인 경우
				// if(this.useFg){
				// 	sendParam['url'] = url + 'rawdata.do';
				// 	bodyMap['interval'] = '1000';
				// }else{
				// 	sendParam['url'] = url + 'aggdata2.do';
				// 	bodyMap['interval'] = '';
				// 	bodyMap['term'] = 'MIN1';
				// }
				// let tempTagList = this.pageData.totalSelectedTags.split('/*wq2a/');
				// let tagList = tempTagList.filter(item => item != '');
        sendParam["url"] = url + "aggdata2.do";
        bodyMap["interval"] = "";
        bodyMap["term"] = "MIN1";
				// let tagList = this.pageData.tagList;
        bodyMap["tags"] = [tagList[i]];
				// 데이터 없어서 이걸로 등록 - 시작
				// bodyMap['tags'] = ["M16A_EQID001_U-CH-012_Pump_ATRD_010001_VAL_003_Y_01호기_냉수_유량_실측값", "SEOSAN_EQID002_U-CH-017_Innter Heater Jacket_ATRD_010003_VAL_059_Y_17호기_증발_냉매_포화_온도#_실측값"]
				// bodyMap['tags'] = ["SEOSAN_EQID002_U-CH-017_Innter Heater Jacket_ATRD_010003_VAL_059_Y_17호기_증발_냉매_포화_온도#_실측값", "M16A_EQID001_U-CH-014_Chiller_ATRD_010002_VAL_018_Y_08호기_응축_냉매_포화_온도#_실측값", "M16A_EQID001_U-CH-012_Pump_ATRD_010001_VAL_008_Y_01호기_냉각탑_냉각수_공급온도_PV#_실측값"]
				// 데이터 없어서 이걸로 등록 - 끝
        bodyMap["eterm"] =
          Utility.setFormatDate(this.toDt, "YYYY-MM-DD") +
          " " +
          this.pageData.selectTimeValue2.replaceAll(" ", "").slice(0, -1) +
					1 +
          ":00";
        bodyMap["sterm"] =
          Utility.setFormatDate(this.fromDt, "YYYY-MM-DD") +
          " " +
          this.pageData.selectTimeValue1.replaceAll(" ", "") +
          ":00";
        let test = this.pageData.selectTimeValue1.replaceAll(" ", "").slice(0, -1) + 1;
        bodyMap["t"] = Utility.setFormatDate(new Date(), "YYYY-MM-DD HH:mm:ss");
				// bodyMap['t'] = "2022-07-25 10:00:00";
        sendParam["bodyMap"] = bodyMap;
				let res = await this.postApiReturn({
          apiKey: "selectTagTrndData",
          resKey: "tagTrndDatas",
					sendParam: sendParam,
				});
				if (res != null && res.length > 0) {
					res = JSON.parse(res);
					if (res.tags.length > 0) {
            resDataDict["tags"].push(res.tags[0]);
					}
				}
				let resRawData = [];
				if (this.useFg) {
					let newStermDate = Utility.setFormatDate(
            Utility.setFormatDate(this.fromDt, "YYYY-MM-DD") +
              " " +
              this.pageData.selectTimeValue1.replaceAll(" ", "") +
              ":00",
            "YYYY-MM-DD HH:mm"
					);
					newStermDate = new Date(new Date(newStermDate).getTime() - 1000);
					let sendParam2 = { ...sendParam };
          sendParam2["url"] = url + "rawdata.do";
          sendParam2["bodyMap"]["interval"] = "1000";
          sendParam2["bodyMap"]["sterm"] = Utility.setFormatDate(
						newStermDate,
            "YYYY-MM-DD HH:mm:ss"
					);
          sendParam2["bodyMap"]["eterm"] =
            Utility.setFormatDate(this.toDt, "YYYY-MM-DD") +
            " " +
            this.pageData.selectTimeValue2.replaceAll(" ", "") +
            ":01";
          delete sendParam2["bodyMap"]["term"];
					resRawData = await this.postApiReturn({
            apiKey: "selectTagTrndData",
            resKey: "tagTrndDatas",
						sendParam: sendParam2,
					});
					if (resRawData != null && resRawData.length > 0) {
						resRawData = JSON.parse(resRawData);
						if (resRawData.tags.length > 0) {
              rawResDataDict["tags"].push(resRawData.tags[0]);
						}
					}
				}
			}
			if (resDataDict != null && resDataDict.tags.length != 0) {
				await this.setChart(tagList, resDataDict, rawResDataDict);
			} else {
				this.setChartNull();
			}
		},
		async setChart(tagList, data, rawData) {
			this.loadChart = false;
			let legendNameMapper = {
        A: "AVG",
        S: "STDDEV",
				// 'CNT': 'CNT',
				// 'SUM' : 'SUM',
        M: "MAX",
        N: "MIN",
        v: "RAWDATA",
			};
			let chartDataDict = {};
			for (var i = 0; i < tagList.length; i++) {
				chartDataDict[tagList[i]] = {
					xAxisList: [],
					seriesData: [],
					legendList: [],
				};
			}

			for (var i = 0; i < tagList.length; i++) {
				//data chart data 구성하기
				let dataTagTitle = data.tags[i].tag;
				let xAxisData1 = []; // data의 x축 data 초기화 꼭 해줄 것
				let seriesData = [];
				let seriesDataDict = {};
				let keys = [];
				let legendData = [];
        if (data.tags[i] != undefined && data.tags[i]["d"].length > 0) {
          for (var j = 0; j < data.tags[i]["d"].length; j++) {
            xAxisData1.push(data.tags[i]["d"][j].t);
            keys = Object.keys(data.tags[i]["d"][j]);
						for (var idx in keys) {
							if (seriesDataDict[keys[idx]] == undefined) {
								seriesDataDict[keys[idx]] = [];
							}
							// 가져오는 모든 데이터 넣기
              seriesDataDict[keys[idx]].push(data.tags[i]["d"][j][keys[idx]]);
						}
					}
				} else {
					keys = Object.keys(legendNameMapper);
					for (var idx in keys) {
						seriesDataDict[keys[idx]] = [];
					}
				}
				for (var idx in keys) {
          if (legendNameMapper[keys[idx]] == "SUM") {
						seriesData.push({
							name: legendNameMapper[keys[idx]],
              type: "line",
							data: seriesDataDict[keys[idx]],
							xAxisIndex: 0,
							connectNulls: true,
						});
            // legendData.push(legendNameMapper[keys[idx]]);

            legendData.push({
              name: legendNameMapper[keys[idx]],
              icon: "circle",
            });
					} else if (legendNameMapper[keys[idx]] != undefined) {
						seriesData.push({
							name: legendNameMapper[keys[idx]],
              type: "line",
							data: seriesDataDict[keys[idx]],
							xAxisIndex: 0,
							connectNulls: true,
						});
            // legendData.push(legendNameMapper[keys[idx]]);

            legendData.push({
              name: legendNameMapper[keys[idx]],
              icon: "circle",
            });
					}
				}

				// data xAxisData1 추가
				// if(rawData.tags.length == 0 || !this.useFg){
        chartDataDict[dataTagTitle]["xAxisList"].push({
					data: xAxisData1,
					axisLabel: { rotate: 40 },
					// axisLabel: { interval: 0, rotate: 40 },
					// axisTick : {interval : 1},
					boundaryGap: false,
					offset: true,
					show: !this.useFg,
				});
				// }

				// data SeriesData 추가
        chartDataDict[dataTagTitle]["seriesData"] = seriesData;
				// data legend 추가
        console.log("le dat:", legendData);
        chartDataDict[dataTagTitle]["legendList"] = legendData;
				//
				//rawData chart data 구성하기
        let rawDataTagTitle = "";
				let xAxisData2 = []; // rawData의 x축 data 초기화 꼭 해줄 것
				let rawDataSeriesData = [];
				if (
					this.useFg == true &&
					rawData.tags.length > 0 &&
					rawData.tags[i] != undefined
				) {
					rawDataTagTitle = rawData.tags[i].tag;
					// rawData xAxisData2 추가
          chartDataDict[rawDataTagTitle]["xAxisList"].push({
						data: xAxisData2,
						boundaryGap: false,
            position: "bottom",
						// axisLabel: { interval: 0, rotate: 40 },
						axisLabel: { rotate: 40 },
					});
          if (rawData.tags[i]["d"].length > 0) {
            for (var j = 0; j < rawData.tags[i]["d"].length; j++) {
              xAxisData2.push(rawData.tags[i]["d"][j].t);
              if (rawData.tags[i]["d"][j]["v"] != undefined) {
                rawDataSeriesData.push(rawData.tags[i]["d"][j]["v"]);
							} else {
								// null값 처리
								rawDataSeriesData.push(NaN);
							}
						}
					}
					// rawData SeriesData 추가
          chartDataDict[rawDataTagTitle]["seriesData"].push({
            name: legendNameMapper["v"],
            type: "line",
						data: rawDataSeriesData,
						xAxisIndex: 1,
						connectNulls: true,
					});
					// rawData legend 추가
          chartDataDict[rawDataTagTitle]["legendList"].push(legendNameMapper["v"]);
				}
				let option = {
					legend: {
            top: "top",
            data: chartDataDict[tagList[i]]["legendList"],
            left: "center",
						textStyle: {
              color: "#95A0A9",
							fontSize: 10,
						},
					},
					grid: {
            left: "5%",
            right: "5%",
						// bottom: '3%',
						containLabel: true,
            top: "5%",
            bottom: "13%",
					},
					toolbox: {
						feature: {
							saveAsImage: {},
						},
					},
					// xAxis: this.useFg ==true ? chartDataDict[tagList[i]]['xAxisList'][1] : chartDataDict[tagList[i]]['xAxisList'][0],
					// xAxis: chartDataDict[tagList[i]]['xAxisList'][0],
          xAxis: chartDataDict[tagList[i]]["xAxisList"],
					dataZoom: [
						{
							show: true,
							realtime: true,
							start: 0,
							end:
                chartDataDict[tagList[i]]["xAxisList"][1] != undefined
                  ? (30 / chartDataDict[tagList[i]]["xAxisList"][1]["data"].length) * 100
                  : chartDataDict[tagList[i]]["xAxisList"][0]["data"].length > 30
                  ? (30 / chartDataDict[tagList[i]]["xAxisList"][0]["data"].length) * 100
									: 100,
						},
						{
              type: "inside",
							realtime: true,
							start: 65,
							end: 85,
						},
					],
					// yAxis: [
					// 	{
					// 		type: 'value',
					// 		position: 'left'
					// 	},
					// 	{
					// 		type: 'value',
					// 		position: 'right'
					// 	},
					// ],
					yAxis: {
            type: "value",
            position: "left",
					},
          series: chartDataDict[tagList[i]]["seriesData"],
				};
				await this.$nextTick();
        this.$store.state.pageData[this.myPrgmId][this.chartNameList[i]].series =
          option.series;
				this.$store.state.pageData[this.myPrgmId][this.chartNameList[i]].xAxis =
					option.xAxis;
        this.$store.state.pageData[this.myPrgmId][this.chartNameList[i]].dataZoom =
          option.dataZoom;
        this.$store.state.pageData[this.myPrgmId][this.chartNameList[i]].legend =
          option.legend;
				// this.setChartOption({chartKey : this.chartNameList[i], value: option});
				// this.setChartDetailXAxisData({
				// 	chartKey: this.chartNameList[i],
				// 	value: chartDataDict[tagList[i]]['xAxisList']
				// })
			}
			this.loadChart = true;
		},
		async setChartNull() {
			this.loadChart = false;
			// 차트 series data 초기화
			this.$store.state.pageData[this.myPrgmId].chart01.series = [];
			this.$store.state.pageData[this.myPrgmId].chart02.series = [];
			this.$store.state.pageData[this.myPrgmId].chart03.series = [];
			this.$store.state.pageData[this.myPrgmId].chart04.series = [];
			this.$store.state.pageData[this.myPrgmId].chart05.series = [];
			// 차트 xAxis data 초기화
			let xAxisDefault = {
				data: [],
				axisLabel: { interval: 0, rotate: 30 },
			};
			this.$store.state.pageData[this.myPrgmId].chart01.xAxis = xAxisDefault;
			this.$store.state.pageData[this.myPrgmId].chart02.xAxis = xAxisDefault;
			this.$store.state.pageData[this.myPrgmId].chart03.xAxis = xAxisDefault;
			this.$store.state.pageData[this.myPrgmId].chart04.xAxis = xAxisDefault;
			this.$store.state.pageData[this.myPrgmId].chart05.xAxis = xAxisDefault;
			// 차트 legend data 초기화
			this.$store.state.pageData[this.myPrgmId].chart01.legend.data = [];
			this.$store.state.pageData[this.myPrgmId].chart02.legend.data = [];
			this.$store.state.pageData[this.myPrgmId].chart03.legend.data = [];
			this.$store.state.pageData[this.myPrgmId].chart04.legend.data = [];
			this.$store.state.pageData[this.myPrgmId].chart05.legend.data = [];
			this.loadChart = true;
		},
    async setChartNull2() {
      this.loadChart = false;
      let option = {
        // title: {
        // 	text: tagTitle
        // },
        tooltip: {
          trigger: "axis",
        },
        legend: {
          top: "0px", // or "top"
          right: "30px",

          icon: "circle",

          data: ["AVG", "STDDEV", "MAX", "MIN", "RAWDATA"],
          textStyle: {
            color: "#95A0A9",
            fontSize: 10,
          },
        },
        grid: {
          // left: "4%",
          // right: '4%',
          // bottom: '3%',
          // containLabel: true
          top: "80",
          // bottom: 30,
        },
        toolbox: {
          orient: "horizontal", // default is horizontal
          right: "50px", // move to the left
          top: "40px",

          feature: {
            saveAsImage: {},
          },
        },
        xAxis: {
          data: ["2023-01-01", "2023-01-02", "2023-01-03", "2023-01-04", "2023-01-05"],
          axisLabel: { interval: 0, rotate: 30 },
        },
        dataZoom: [
          {
            show: true,
            realtime: true,
            start: 0,
            end: 20,
          },
          {
            type: "inside",
            realtime: true,
            start: 65,
            end: 85,
          },
        ],
        yAxis: {
          type: "value",
          position: "left",
        },
        series: [
          {
            name: "AVG",
            type: "line",
            data: [100, 120, 130, 125, 140],
            xAxisIndex: 0,
            connectNulls: true,

            itemStyle: {
              color: "#F5222D", // point color (optional)
            },
          },
          {
            name: "STDDEV",
            type: "line",
            data: [22, 23, 21, 24, 25],
            xAxisIndex: 0,
            connectNulls: true,
            itemStyle: {
              color: "#FAAD14", // point color (optional)
            },
          },
          {
            name: "MAX",
            type: "line",
            data: [60, 62, 58, 65, 63],
            xAxisIndex: 0,
            connectNulls: true,
            itemStyle: {
              color: "#31B47B", // point color (optional)
            },
          },
          {
            name: "MIN",
            type: "line",
            data: [50, 58, 40, 100, 80],
            xAxisIndex: 0,
            connectNulls: true,
            itemStyle: {
              color: "blue", // point color (optional)
            },
          },
          {
            name: "RAWDATA",
            type: "line",
            data: [60, 90, 70, 65, 100],
            xAxisIndex: 0,
            connectNulls: true,
            itemStyle: {
              color: "purple", // point color (optional)
            },
          },
        ],
      };
      if (this.dumyChartFg) {
        await this.$nextTick();
        this.setChartOption({ chartKey: this.chartNameList[0], value: option });
        this.setPageData({
          [this.chartNameList[0]]: option,
        });
      } else {
        for (var i = 0; i < this.tagList.length; i++) {
          await this.$nextTick();
          this.setChartOption({ chartKey: this.chartNameList[i], value: option });
        }
      }
      this.loadChart = true;
    },
		closePopEvent() {
			// tag를 추가안하고 popup만 열고 닫을 경우 add한 Row를 삭제
			let gridData = this.$refs[this.gridName].getData();
			if (gridData.length == 0) {
        this.$refs[this.gridName].removeRow("immediately", 0);
			} else if (
				gridData[gridData.length - 1].tagId == undefined ||
				gridData[gridData.length - 1].tagId == null
			) {
				this.$refs[this.gridName].removeRow(
          "immediately",
          gridData[gridData.length - 1].rowKey
				);
			}
		},
		downloadExcelFile() {
			if (this.tagList.length > 0) {
        this.makeExcelFile(this.chartNameList, this.tagList, "데이터_TREND.xlsx");
			}
		},
		makeExcelFile(chartNameList, tagNameList, fileName) {
			var workBook = XLSX.utils.book_new();
			for (var i = 0; i < tagNameList.length; i++) {
				let xlsData = this.makeExcelData(chartNameList[i], tagNameList[i]);
				let num = i + 1;
        let sheetName = "sheet" + num;
				// let sheetName = tagNameList[i];
				var excelData = XLSX.utils.json_to_sheet(xlsData);
				XLSX.utils.book_append_sheet(workBook, excelData, sheetName);
			}
			// 	var xlsData = this.makeExcelData(chartName);
			XLSX.writeFile(workBook, fileName);
		},
		makeExcelData(chartName, tagName) {
			let xlsData = null;
			var xlsHeader = [
        { header: "TAG ID", name: "tagId" },
        { header: "시간", name: "dttm" },
			];
      this.$store.state.pageData[myPrgmId][chartName]["legend"]["data"].map((item) => {
					xlsHeader.push({
						header: item,
						name: item,
					});
      });
			let xData =
        this.$store.state.pageData[myPrgmId][chartName]["xAxis"][1] != undefined
          ? this.$store.state.pageData[myPrgmId][chartName]["xAxis"][1]["data"]
          : this.$store.state.pageData[myPrgmId][chartName]["xAxis"][0]["data"];
      let minDataXData = this.$store.state.pageData[myPrgmId][chartName]["xAxis"][0][
        "data"
      ];
      let chartData = this.$store.state.pageData[myPrgmId][chartName]["series"];
      chartData = [{ name: "dttm", data: xData }, ...chartData];
			let chartDataDict = {};
      chartData.map((item) => {
				chartDataDict[item.name] = item.data;
			});
			let finalChartData = [];
			let minDataXDataIdx = 0;
			for (var i = 0; i < xData.length; i++) {
				let dict = {};
				if (
					minDataXData[minDataXDataIdx + 1] != undefined &&
					(xData[i] >= minDataXData[minDataXDataIdx + 1] ||
						xData[i] == minDataXData[minDataXDataIdx + 1])
				) {
					minDataXDataIdx += 1;
				}
				for (var key of Object.keys(chartDataDict)) {
          dict["tagId"] = tagName;
          if (key == "RAWDATA") {
						dict[key] = chartDataDict[key][i];
          } else if (key == "dttm") {
						dict[key] = chartDataDict[key][i];
					} else {
						dict[key] = chartDataDict[key][minDataXDataIdx];
					}
				}

				// if(i==0 && xData[i] == minDataXData[minDataXDataIdx]){
				// 	minDataXDataIdx = 0;
				// }
				// else if(xData[i] == minDataXData[minDataXDataIdx]){
				// 	minDataXDataIdx += 1;
				// }
				finalChartData.push(dict);
			}
			var tmpData = [];
			var tmpMap = {};

      finalChartData.map((item) => {
        xlsHeader.map((v) => {
					// return Object.assign(tmpMap, { [v.header]: item[v.name] || 0 });
					var value = item[v.name];
					if (value == undefined) {
						value = 0;
					}
          if (typeof value === "number") {
            value = parseFloat(Utility.setFormatIntDecimal(value, 2).replace(",", ""));
					}
					return Object.assign(tmpMap, { [v.header]: value || 0.0 });
				});
				tmpData = tmpData.concat(tmpMap);
				tmpMap = {};
			});
			xlsData = tmpData;

			return xlsData;
		},
	},
};
var dt1 = new Date();
var dt2 = new Date(dt1.setMonth(dt1.getMonth() - 1));
const defaultData = {
	isFind: false,
	/* 검색옵션 */
  cmCycle: "CYC_DAY", // 주기
	defaultRange: {
		CYC_DAY: 30,
	},
  fromDt: Utility.setFormatDate(dt2, "YYYYMMDD"),
  toDt: Utility.setFormatDate(new Date(), "YYYYMMDD"),
  selectTimeValue1: "00 : 00",
  selectTimeValue2: "00 : 00",
	useFg: false,
	chkEqualDayHourFg: true,
	// 선택된 GRID 데이터
	rowGridSelectKey: 0,
	rowGridSelectData: null,
	/* Griddata 세팅 */
	rowGrid: {
		data: [],
		column: [],
		option: {},
		defaultRow: {
			eqpmGrpNm: null,
			eqpmGrpId: null,
			eqpmId: null,
			eqpmNm: null,
			tagId: null,
			tagNm: null,
			rowStat: null,
		},
		buttonAuth: {
			add: true,
			remove: true,
			save: false,
			excel: false,
		},
	},
	tagTrndPopModalData: {},
	// totalSelectedTags: '',
	tagList: [],
	chart01: Utility.defaultChartOption(true),
	chart02: Utility.defaultChartOption(true),
	chart03: Utility.defaultChartOption(true),
	chart04: Utility.defaultChartOption(true),
	chart05: Utility.defaultChartOption(true),
};
</script>
<style lang="scss" scoped>
@import "@/assets/scss/var.scss";

::v-deep {
  .datepicker-container {
    border: none !important;
  }
}

@each $theme in dark, light {
	.v-application.#{$theme}-mode {
		.tagTrndGrid {
			.tui-grid {
				&-cell {
					&.row-insert {
						background-color: #242940;
					}
					&.row-modify {
						background-color: map-deep-get(
							$config,
							#{$theme},
              "tui-grid-cell-modify-color"
						);
					}
					&.row-removed {
						background-color: map-deep-get(
							$config,
							#{$theme},
              "tui-grid-cell-removed-color"
						);
					}
					&.row-disabled {
            color: map-deep-get($config, #{$theme}, "tui-grid-cell-disabled-color");

						.tui-grid-cell-content {
              color: map-deep-get($config, #{$theme}, "tui-grid-cell-disabled-color");
						}
					}
					&.row-selected {
						background-color: map-deep-get(
							$config,
							#{$theme},
              "tui-grid-cell-selected-color"
						);

						.tui-grid-cell-content {
              color: map-deep-get($config, #{$theme}, "activate");
						}
					}
				}
			}
		}
	}
}
</style>
