<template>
	<div class="editTargetDiaBase-box">
		<el-dialog
		:visible.sync="isShow"
		:close-on-click-modal="false"
		:modal-append-to-body='false'
		@close="cancelHandle"
		custom-class="dialog"
		center
		width="700px"
    :title="saveScence==='saveOther' ? $t('StatisticAnalysis.ChartRelevance.save_other'):$t('StatisticAnalysis.ChartRelevance.save_edb')"
		v-dialogDrag>
			<div class="dialog-main">
				<el-form
				ref="targetForm"
				label-position="left"
				label-width="120px"
				hide-required-asterisk
				:model="formData"
				:rules="formRules">
					<el-form-item :label="$t('Table.edb_name')" prop="edb_name">
						<el-input
						v-model="formData.edb_name"
						style="width: 80%"
						:placeholder="$t('Table.edb_name')"></el-input>
					</el-form-item>
					<el-form-item :label="$t('Edb.Detail.select_catalogue')" prop="menu">
						<cascader
						v-model="formData.menu"
						:options="options"
						clearable
						cascaderWidth="width:80%"
						:placeholder="
							$t('CustomAnalysisPage.select_appropriate_category')
						"
						:config="{ emitPath: false, checkStrictly: true }"
						/>
					</el-form-item>
					<el-form-item :label="$t('Table.frequency')" prop="frequency">
						<span slot="label">{{$t('Table.frequency')}}</span>
						<el-select 
						v-model="formData.frequency" 
						:placeholder="$t('CustomAnalysisPage.select_frequency')" 
						style="width:80%"
						clearable>
							<el-option
								v-for="item in frequencyArr"
								:key="item.value"
								:label="item.label"
								:value="item.value">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item :label="$t('Table.unit')" prop="unit">
						<span slot="label">{{$t('Table.unit')}}</span>
						<selectUnit 
							v-model="formData.unit" 
							style="width: 80%"
						/>
					</el-form-item>
				</el-form>
			</div>
			<div class="dia-bot">
				<el-button type="primary" style="margin-right:20px" @click="addTarget">{{$t('Dialog.confirm_save_btn')}}</el-button>
				<el-button type="primary" plain @click="cancelHandle">{{$t('Dialog.cancel_btn')}}</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { dataBaseInterface } from '@/api/api.js';
import * as preDictEdbInterface from '@/api/modules/predictEdbApi.js';
import chartRelevanceApi,{ statisticFeatureInterface } from '@/api/modules/chartRelevanceApi.js';
import { unitArr,frequencySelectList } from '@/utils/defaultOptions';
import selectUnit from '@/components/selectUnit.vue';
export default {
	components: { selectUnit },
	props: {
		isShow: {
			type: Boolean,
		},
		chartData: {
			type: Object,
		},
		source: {
			type: Number
		},
		saveScence: { //saveOther另存为 ''保存
      type:String,
      default: ''
    },
	},
	watch: {
		'isShow': {
			handler(newval) {
				newval && this.getMenu();
				const { ChartName } = this.chartData;
				this.formData.edb_name = this.saveScence==='saveOther' ? `${ChartName}(1)` : ChartName;
			}
		}
	},
    computed:{
        formRules(){
            return {
                edb_name:[
                    { required: true, message: /* '指标名称不能为空' */this.$t('Edb.Valids.name_msg'), trigger: 'blur' },
                ],
                menu:[
                    { required: true, message: /* '所属目录不能为空' */this.$t('Edb.Valids.menu_msg'), trigger: 'blur' },
                ],
                frequency:[
                    { required: true, message: /* '频率不能为空' */this.$t('Edb.Valids.fre_msg'), trigger: 'blur' },
                ],
                unit:[
                    { required: true, message: /* '单位不能为空' */this.$t('Edb.Valids.unit_msg'), trigger: 'blur' },
                ],
            }
        }
    },
	data () {
		return {
			formData: {
				edb_name:'',
				menu:'',
				frequency: '',
				unit:''
			},
			options:  [],
			unitArr,
			levelProps: {
				label: 'ClassifyName',
				value: 'ClassifyId',
				children: 'Children',
				emitPath: false,
				checkStrictly: true
			},
			frequencyArr:frequencySelectList(),
		};
	},
	methods: {
		/* 获取目录结构 */
		async getMenu() {
			let res;
			//统计特征区分原指标是否预测，保存到预测指标库或/eta指标库
			if(this.$route.path==='/statisticFeatureChartEditor'&&this.$parent.oldEdbInfoType) {
        res = await preDictEdbInterface.classifyListV2()
				if(res.Ret !== 200) return
      }else {
				res = await dataBaseInterface.menuListV3({ClassifyType:2})
				if(res.Ret !== 200) return
			}
			this.filterNodes(res.Data.AllNodes||[]);
			this.options = res.Data.AllNodes || [];
		},
		filterNodes(arr,n) {
			arr.length && arr.forEach(item => {
				item.Children && item.Children.length && this.filterNodes(item.Children,n)
				if(!item.Children.length) {
					delete item.Children
				}
			})
		},
		/* 保存 */
		async addTarget() {
			await this.$refs.targetForm.validate()
			const { edb_name,menu,frequency,unit } = this.formData;

			//统计图的2 3 4对应source8 9 10但其实图表source又是7 8 9 别问为什么这样搞问后端 我也乱的一批
      const sourceMap = {
				1: 1, 
        2: 8,
        3: 9,
        4: 10
      }
      let Source;
      if(['/relevancechartEditor','/relevancechartEditorV2'].includes(this.$route.path)) {
        Source = this.source;
      }else if(this.$route.path==='/statisticFeatureChartEditor') {
        Source = sourceMap[this.source]
      }

			let params = {
				Source,
				IsSaveAs: this.saveScence==='saveOther',
        EdbName: edb_name,
				Frequency: frequency,
				Unit: unit,
        ClassifyId: menu,
        ...this.$parent.chartInfo
			}

			let res = null;
      if(['/relevancechartEditor','/relevancechartEditorV2'].includes(this.$route.path)) {
        res = await chartRelevanceApi.saveEdb(params);
      }else if(this.$route.path==='/statisticFeatureChartEditor') {
        res = await statisticFeatureInterface.saveEdb(params);
      }
			
			if(res.Ret !== 200) return
			this.$message.success(/* '保存成功' */this.$t('MsgPrompt.saved_msg'));
			this.cancelHandle();
			this.$emit('saveBack',{source:this.source})
      
		},
		cancelHandle() {
			this.formData = {
				edb_name:'',
				menu:'',
				frequency: '',
				unit:''
			}
			this.$emit('update:isShow',false)
		}
	},
}
</script>
<style lang='scss'>
.editTargetDiaBase-box {
	.dialog-main {
		padding-left: 50px;
	}
	.el-cascader .el-input {
		width: 100%;
	}
	.dia-bot {
		margin: 52px 0 30px;
		display: flex;
		justify-content: center;

	}
}
</style>