<template>
  <div class="create-form-cont">
    <el-form
      ref="formRef"
      label-position="left"
      hide-required-asterisk
      inline
      label-width="0"
      :model="formData"
      :rules="formRules"
    >
      <el-form-item prop="dateSeries">
        <el-input v-model="formData.dateSeries" placeholder="请选择日期序列" @focus="selectArea='date'" @change="changeFormat('date')" @keyup.native="e => { e.keyCode===13 && initSelect()}" :class="{'select': selectArea==='date'}"></el-input>
      </el-form-item>
      <el-form-item prop="valueSeries">
        <el-input v-model="formData.valueSeries" placeholder="请选择数值序列" @focus="selectArea='value'" @change="changeFormat('value')" @keyup.native="e => { e.keyCode===13 && initSelect()}" :class="{'select': selectArea==='value'}"></el-input>
      </el-form-item>

      <el-form-item prop="edbName">
        <el-input v-model="formData.edbName" placeholder="指标名称" @focus="initSelect"></el-input>
      </el-form-item>
      <el-form-item prop="classify">
        <el-cascader
          v-model="formData.classify"
          :options="classifyOption"
          style="width: 100%"
          @focus="initSelect"
          :props="{
            label: 'ClassifyName',
            value: 'ClassifyId',
            children: 'Children',
            emitPath: false,
            checkStrictly: true
          }"
          clearable
          placeholder="请选择所属目录"
        />
      </el-form-item>
      <el-form-item prop="frequency">
        <el-select
          v-model="formData.frequency"
          placeholder="请选择频率"
          style="width: 100%"
          @focus="initSelect"
          clearable
        >
          <el-option
            v-for="item in frequencyArr"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="unit">
        <selectUnit v-model="formData.unit" @click.native="initSelect"/>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="handleSaveTarget">保存</el-button>
        <el-button type="primary" plain @click="$parent.backHandle('into-detail')">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {dataBaseInterface} from '@/api/api.js'
export default {
  data() {
    return {
      selectArea: '',
      formData: {
        edbInfoId: 0,
        dateSeries: '',
        valueSeries: '',
        dateArr:[],
        valueArr: [],
				edbName:'',
				classify:'',
				frequency: '',
				unit:'',
      },
      formRules: {
        // dateSeries: [{ required: true, message: '日期序列不能为空', trigger: 'blur' }],
        // valueSeries: [{ required: true, message: '数值序列不能为空', trigger: 'blur' }],
        edbName: [{ required: true, message: '指标名称不能为空', trigger: 'blur' }],
        classify: [{ required: true, message: '目录不能为空', trigger: 'blur' }],
        frequency: [{ required: true, message: '频率不能为空', trigger: 'blur' }],
        unit: [{ required: true, message: '单位不能为空', trigger: 'blur' }],
      },
      frequencyArr:['日度','周度','旬度','月度','季度','年度'],
      classifyOption: [],

      isLockUpdate: false,//防止手动改变公式设置选区出发hook事件又更新公式和值 手动设置值即可
    };
  },
  methods: {

    /* 选区时更新公式 */
    setFormula(formula,arr) {
      if(!this.selectArea) return
      //更新日期序列公式
      if(this.selectArea === 'date') {
        this.formData.dateArr = arr;
        this.formData.dateSeries = formula
      }else if(this.selectArea === 'value') {
        //更新数值序列公式
        this.formData.valueArr = arr;
         this.formData.valueSeries = formula
      }

      console.log(this.formData)
    },

    /* 获取分类 */
		getMenu() {
			dataBaseInterface.menuListV3().then((res) => {
				if (res.Ret !== 200) return
        this.filterNodes(res.Data.AllNodes||[]);
				this.classifyOption = res.Data.AllNodes || [];
			});
		},
    
    filterNodes(arr) {
			arr.length &&
				arr.forEach((item) => {
					item.Children.length && this.filterNodes(item.Children);
					if (!item.Children.length) {
						delete item.Children;
					}
				});
		},

    /* 改变公式 */
    changeFormat(type) {
      this.isLockUpdate = true;
      this.setRangeShow(type==='date'?this.formData.dateSeries:this.formData.valueSeries)
      
      let rangeArr = luckysheet.getRangeAxis();

      //检查选取是否满足同行/同列
      if(!this.$parent.checkRangeVaild(rangeArr[0])){
        type==='date'?this.formData.dateSeries = '':this.formData.valueSeries ='';
        return this.$message.warning('序列只允许选择同行或同列');
      } 

      let rangeCells = luckysheet.getRangeValue().flat().map(_=>_?_.m:'');
      //更新公式关联的数据数组
      type==='date' ? this.formData.dateArr = rangeCells : this.formData.valueArr = rangeCells;
      console.log(this.formData)
      this.isLockUpdate = false;
    },

    initSelect() {
      this.selectArea = ''
    },

    initData(data=null) {
      this.initSelect()
      if(data) {
        this.formData = {
          edbInfoId: data.EdbInfoId,
          dateSeries: data.DateSequenceStr,
          valueSeries: data.DataSequenceStr,
          dateArr:[],
          valueArr: [],
          edbName: data.EdbName,
          classify: data.ClassifyId,
          frequency: data.Frequency,
          unit: data.Unit,
        }

        let sheetName = data.DateSequenceStr.substr(0,data.DateSequenceStr.indexOf('!'))
        let order = luckysheet.getAllSheets().find(_ => _.name===sheetName) ? luckysheet.getAllSheets().find(_ => _.name===sheetName).order : 0;

        this.setRangeShow([data.DateSequenceStr,data.DataSequenceStr],order);
      }else {
        this.formData = {
          edbInfoId: 0,
          dateSeries: '',
          valueSeries: '',
          dateArr:[],
          valueArr: [],
          edbName:'',
          classify:'',
          frequency: '',
          unit:'',
        }
        
        luckysheet.setRangeShow(['A1','A1'])
      }
    },

    /* 解析公式显示选区 */
    setRangeShow(range,order=null) {
      
      //初始化多选区
      let rangeArr = [];
      if(Array.isArray(range)) {
        range.forEach(_ => {
          rangeArr.push(this.splitFormula(_))
        })
      }else {
        rangeArr = [this.splitFormula(range)]
      }
      order!==null && luckysheet.setSheetActive(order)
      console.log(rangeArr)
      
      let rowLen = luckysheet.getSheet().data.length;
      let filterRangeArr = []
      rangeArr.forEach(item =>{
        filterRangeArr.push(this.filterFormula(item,rowLen))
      })
      console.log(filterRangeArr)
      luckysheet.setRangeShow(filterRangeArr)
    },

    /* 处理超过表格行无法显示选区的问题 超过后截止到最后一行 */
    filterFormula(item,rowLen) {
      let cellArr = item.split(':');
      if(!cellArr[1]) return item

      let numStr = cellArr[1].replace(/[^0-9]/ig,""); 
      let letterStr = cellArr[1].replace(/[^a-z]+/ig,"");
      
      let lastNum = Number(numStr) > rowLen ? rowLen : Number(numStr);
      
      return `${cellArr[0]}:${letterStr}${lastNum}`
    },

    /* 解析公式 */
    splitFormula(formula) {
      let str = formula.substr(formula.indexOf('!')+1).replace(/\$/g,'')
      return str
    },

    /* 保存 */
    handleSaveTarget: _.debounce(async function() {
      if(!this.formData.dateSeries) return this.$message.warning('日期序列不能为空')
      if(!this.formData.valueSeries) return this.$message.warning('数值序列不能为空')

      await this.$refs.formRef.validate();
      this.initSelect();
      this.$emit('save')
    },300),
  },
  
  mounted() {
    this.getMenu()
  },
};
</script>
<style scoped lang="scss">
.create-form-cont {
  background: #fff;
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  padding: 20px 20px 0;
  .el-form-item {
    margin-bottom: 20px;
    /* .select {
      &::before {
        content: '';
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        border: 2px dashed #18ad18;
        border-radius: 4px;
      }
    } */
  }
}
</style>

<style lang="scss">
  .create-form-cont {
    .select .el-input__inner {
       border: 2px dashed #18ad18;
      border-radius: 4px;
    }
  }
</style>
