
<template>
    <div>
        <el-card>
            <el-button size="mini" plain @click="useBack">返回</el-button>
            <el-divider></el-divider>
            <el-form size="mini" :model="form" :rules="rules" ref="form" label-width="auto">
                <el-row :gutter="10">
                    <el-col :span="1.5">
                        <el-form-item label="年份" prop="year" >
                            <el-date-picker
                                v-model="form.year"
                                type="year"
                                value-format="yyyy-MM-dd"
                                clearable
                                >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="1.5">
                        <el-form-item label="模板名称" prop="name">
                            <el-input
                                v-model="form.name"
                                style="width: 200px"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="1.5">
                        <el-form-item label="开始日期" prop="startTime">
                            <el-date-picker
                                v-model="form.startTime"
                                clearable
                                type="date"
                                value-format="yyyy-MM-dd"
                                style="width: 200px"
                                >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="1.5">
                        <el-form-item label="结束日期" prop="deadlineTime">
                            <el-date-picker
                                v-model="form.deadlineTime"
                                clearable
                                type="date"
                                value-format="yyyy-MM-dd"
                                style="width: 200px"
                                >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="1.5">
                        <el-form-item label="周期" prop="cycle">
                            <el-select v-model="form.cycle" clearable>
                                <el-option
                                v-for="dict in dict.type.mk_periodic_unit"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="1.5">
                        <el-form-item label="按列展开">
                            <el-select v-model="form.unfold" clearable>
                                <el-option
                                v-for="dict in dict.type.mk_expansion_mode"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>
        <el-card style="height:800px">
            <div style='position: relative;'>
                <el-tabs v-model="activeName" @tab-click="useSwitchTab">
                    <el-tab-pane label="指标" name="indexs">
                        <el-table :data="indexs" height="600px" size="size" v-horizontal-scroll>
                            <el-table-column label="序号" type="index" width="50" align="center" fixed/>
                            <el-table-column show-overflow-tooltip label="指标" align="center" width="200" prop="target">
                                <template slot-scope="scope">
                                    <el-select v-model="scope.row.target" size="mini" clearable>
                                        <el-option
                                        v-for="dict in dict.type.mk_index_type"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                        ></el-option>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column fixed="right" label="操作" align="center" width="150">
                                <template slot-scope="scope">
                                    <el-button type="text" size="mini" @click="useRowRemove(scope.$index,scope.row)">删行</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-tab-pane>
                    <el-tab-pane label="维度" name="dimensionalitys">
                        <el-table :data="dimensionalitys" height="600px" size="size" v-horizontal-scroll>
                            <el-table-column label="序号" type="index" width="50" align="center" fixed/>
                            <el-table-column show-overflow-tooltip label="维度" align="center" width="200" prop="dimensionality">
                                <template slot-scope="scope">
                                    <el-select v-model="scope.row.dimensionality" size="mini" clearable>
                                        <el-option
                                        v-for="dict in dict.type.mk_dimensionality"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                        ></el-option>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column fixed="right" label="操作" align="center" width="150">
                                <template slot-scope="scope">
                                <el-button type="text" size="mini" @click="useRowRemove(scope.$index,scope.row)">删行</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-tab-pane>
                    <el-tab-pane label="周期" name="cycles">
                        <el-table :data="form.cycles" height="600px" size="size" v-horizontal-scroll>
                            <el-table-column label="序号" type="index" width="50" align="center" fixed/>
                            <el-table-column show-overflow-tooltip label="周期" align="center" width="250" prop="name">
                                <template slot-scope="scope">
                                    <el-input
                                        size="mini"
                                        v-model="scope.row.name"
                                        style="width: 200px"
                                        clearable
                                    />
                                </template>
                            </el-table-column>
                            <el-table-column show-overflow-tooltip label="开始日期" align="center" width="200" prop="startTime">
                                <template slot-scope="scope">
                                    <el-date-picker
                                        v-model="scope.row.startTime"
                                        size="mini"
                                        clearable
                                        type="date"
                                        value-format="yyyy-MM-dd"
                                        style="width: 150px"
                                        >
                                    </el-date-picker>
                                </template>
                            </el-table-column>
                            <el-table-column show-overflow-tooltip label="结束日期" align="center" width="200" prop="deadlineTime">
                                <template slot-scope="scope">
                                    <el-date-picker
                                        v-model="scope.row.deadlineTime"
                                        size="mini"
                                        clearable
                                        type="date"
                                        value-format="yyyy-MM-dd"
                                        style="width: 150px"
                                        >
                                    </el-date-picker>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-tab-pane>
                </el-tabs>
                <el-button @click="useRowAdd" v-if="activeName == 'indexs' || activeName == 'dimensionalitys'" size='mini' style='position: absolute;right:10px;top:5px;'>增行</el-button>
                <el-button @click="useResetCycle" v-if="activeName == 'cycles'" size='mini' style='position: absolute;right:10px;top:5px;'>重算周期</el-button>
            </div>
        </el-card>
        <el-card>
            <div class="btn_group">
                <el-col :span="1.5">
                    <el-button size="mini" plain @click="useBack">取消</el-button>
                </el-col>
                <el-col :span="1.5" style="margin: 0 10px;">
                    <el-button type="primary" size="mini" plain @click="useSave">保存</el-button>
                </el-col>
            </div>
        </el-card>
    </div>
</template>

<script>
import {
  addTargetTemplate,
  updateTargetTemplate,
  getTargetTemplate,
} from "@/api/business/spd/starget/targetTemplate";

export default {
  name: "targettemplateDetail",
  dicts: ["mk_periodic_unit","mk_expansion_mode","mk_index_type","mk_dimensionality"],
  components: {},
  props: ['openMode','row'],
  data() {
    return {
      form:{
        year:'',
        name:'',
        startTime:'',
        deadlineTime:'',
        cycle:'',
        unfold:'',
        indexs:[],
        dimensionalitys:[],
        cycles:[],
      },
      //表单校验
      rules: {
        year: [
          { required: true, message: "年份不能为空", trigger: "blur" },
        ],
        name: [
          { required: true, message: "目标名称不能为空", trigger: "blur" },
        ],
        startTime: [
          { required: true, message: "开始日期不能为空", trigger: "blur" },
        ],
        deadlineTime: [
          { required: true, message: "结束日期不能为空", trigger: "blur" },
        ],
        cycle: [
          { required: true, message: "周期不能为空", trigger: "blur" },
        ],
      },
      activeName: 'indexs',
    };
  },
  computed: {
    indexs(){
        return this.form.indexs.filter(
            ({ delFlag }) => delFlag !== "2"
        );
    },
    dimensionalitys(){
        return this.form.dimensionalitys.filter(
            ({ delFlag }) => delFlag !== "2"
        );
    }
  },
  async created() {
    switch(this.openMode){
        case "add":
            var date = new Date();
            this.form.year = date.getFullYear() + '-' + '01' + '-' + '01';
            this.form.startTime = date.getFullYear() + '-' + '01' + '-' + '01';
            this.form.deadlineTime = date.getFullYear() + '-' + '12' + '-' + '31';
            this.form.cycle = 'month';
            break;
        case "edit":
            await this.fetchTemplate(this.row.id);
            break;
        case "see":
            await this.fetchTemplate(this.row.id);
            break;
    }
  },
  methods: {
    //保存
    async useSave() {
        this.$refs["form"].validate(async (valid) => {
            if (valid) {
                try {
                    let checkRes = this.checkBeforeSave(this.form);
                    if(!checkRes){
                        return;
                    }
                    this.loading = true;
                    let res = null;
                    console.log("1111",1111);
                    if (this.openMode === "add") {
                        res = await addTargetTemplate(this.form);
                    }
                    if (this.openMode === "edit") {
                        res = await updateTargetTemplate(this.form);
                    }
                    if (res.code === 200) {
                        this.$modal.msgSuccess("保存成功");
                        this.useBack();
                    }
                } catch (err) {
                    console.error(err);
                } finally {
                    this.loading = false;
                }
            } else {
                return false;
            }
        });
    },
    //保存前校验
    checkBeforeSave(form){
        if(form.indexs){
            let arr = form.indexs.filter(item => item.delFlag != '2');
            if(arr.length < 1){
                this.$modal.msgError("指标页签不能为空！");
                return false;
            }
            arr = arr.filter(item => !item.target);
            if(arr.length > 0){
                this.$modal.msgError("指标页签不能存在空数据！");
                return false;
            }
        }else{
            this.$modal.msgError("指标页签不能为空！");
            return false;
        }
        if(form.dimensionalitys){
            let arr = form.dimensionalitys.filter(item => item.delFlag != '2');
            if(arr.length < 1){
                this.$modal.msgError("维度页签不能为空！");
                return false;
            }
            arr = arr.filter(item => !item.dimensionality);
            if(arr.length > 0){
                this.$modal.msgError("维度页签不能存在空数据！");
                return false;
            }
        }else{
            this.$modal.msgError("维度页签不能为空！");
            return false;
        }
        if(form.cycles){
            let arr = form.cycles.filter(item => item.delFlag != '2');
            if(arr.length < 1){
                this.$modal.msgError("周期页签不能为空！");
                return false;
            }
        }else{
            this.$modal.msgError("周期页签不能为空！");
            return false;
        }
        return true;
    },
    //查询详情
    async fetchTemplate(id) {
      try {
        // try
        this.loading = true;
        const { code, data } = await getTargetTemplate(id);
        if (code === 200) {
          this.form = data;
          return true;
        } else {
          return false;
        }
      } catch (err) {
        // catch
        console.error(err);
      } finally {
        // finally
        this.loading = false;
      }
    },
    //增行
    async useRowAdd() {
        let row = {};
        if(this.activeName == "indexs"){
            row = {
                target: null,
            }
        }
        if(this.activeName == "dimensionalitys"){
            row = {
                dimensionality: null,
            }
        }
        this.form[this.activeName].push({
            delFlag: "0",
            $index: new Date().getTime(),
            ...row,
        });
        console.log("this.form[this.activeName]",this.form[this.activeName]);
    },
    //删行
    async useRowRemove(index,row) {
      if (row.id) {
        this.form[this.activeName].forEach(e => {
          if(e.id == row.id){
            e.delFlag = '2'
          }
        });
      }else{
        this.form[this.activeName].splice(index, 1);
      }
      console.log("this.form[this.activeName]",this.form[this.activeName]);
    },
    //切换多页签
    useSwitchTab(){

    },
    //返回
    useBack(){
        this.$parent.useOpenDetail();
        this.$parent.useSearch();
    },
    //重算周期
    useResetCycle(){
      if(!this.form.startTime || !this.form.deadlineTime || !this.form.cycle){
        this.$modal.msgError("开始日期、结束日期、周期不能存在空值！");
        return;
      }
      if(this.form.startTime > this.form.deadlineTime){
        this.$modal.msgError("开始日期不能大于结束日期！");
        return;
      }
      this.form.cycles = [];
      var cycles = [];
      var start = new Date(this.form.startTime);
      var deadline = new Date(this.form.deadlineTime);
      start.setHours( 0, 0, 0);
      deadline.setHours( 0, 0, 0);
      if(this.form.cycle == 'period'){
        cycles.push({
          name:this.formatDateTime(start, 'yyyy-MM-dd') + '到' + this.formatDateTime(deadline, 'yyyy-MM-dd'),
          startTime:this.formatDateTime(start, 'yyyy-MM-dd'),
          deadlineTime:this.formatDateTime(deadline, 'yyyy-MM-dd'),
        });
      }else{
        while(deadline >= start){
          if(this.form.cycle == 'day'){
            var cy = {
              name:this.formatDateTime(start, 'yyyy-MM-dd'),
              startTime:this.formatDateTime(start, 'yyyy-MM-dd'),
              deadlineTime:this.formatDateTime(start, 'yyyy-MM-dd'),
            }
            cycles.push(cy);
            start.setDate(start.getDate()+1);
          }
          if(this.form.cycle == 'week'){
            var cy = {};
            let date = this.formatDateTime(start, 'yyyy-MM-dd');
            cy.startTime = this.formatDateTime(start, 'yyyy-MM-dd');
            start.setDate(start.getDate()+6);
            cy.deadlineTime = this.formatDateTime(start, 'yyyy-MM-dd');
            cy.name = date + '到' + this.formatDateTime(start, 'yyyy-MM-dd');
            cycles.push(cy);
            start.setDate(start.getDate()+1);
          }
          if(this.form.cycle == 'month'){
            var cy = {};
            cy.name = this.formatDateTime(start, 'yyyy-MM');
            cy.startTime = this.formatDateTime(start, 'yyyy-MM-dd');
            let arr = cy.startTime.split('-');
            start = this.getLastDay(arr[0],arr[1]);
            console.log('start',start);
            cy.deadlineTime = this.formatDateTime(start, 'yyyy-MM-dd');
            cycles.push(cy);
            start.setDate(start.getDate()+1);
          }
          if(this.form.cycle == 'season'){
            var cy = {};
            let date = this.formatDateTime(start, 'yyyy-MM');
            cy.startTime = this.formatDateTime(start, 'yyyy-MM-dd');
            start.setDate(start.getDate()+90);
            cy.deadlineTime = this.formatDateTime(start, 'yyyy-MM-dd');
            cy.name = date + '到' + this.formatDateTime(start, 'yyyy-MM');
            cycles.push(cy);
            start.setDate(start.getDate()+1);
          }
        }
        cycles[cycles.length - 1].deadlineTime = deadline;
      }
      this.form.cycles = cycles;
      console.log('this.form.cycles',this.form.cycles);
    },
    //日期名称格式化
    formatDateTime(date, format) {
      const o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
        'H+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        S: date.getMilliseconds(), // 毫秒
        a: date.getHours() < 12 ? '上午' : '下午', // 上午/下午
        A: date.getHours() < 12 ? 'AM' : 'PM', // AM/PM
      };
      if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      for (let k in o) {
        if (new RegExp('(' + k + ')').test(format)) {
          format = format.replace(
            RegExp.$1,
            RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
          );
        }
      }
      return format;
    },
    getLastDay(year, month) {
      return new Date(new Date(`${month<12?year:++year}-${month==12?1:++month} 00:00`).getTime() - 1);
    }
  },
};
</script>

<style scoped lang="scss">
.btn_group {
  width: 100%;
  margin: 20px 0;
  display: flex;
  justify-content: right;
} 
</style>
