<template>
  <div id="detail">
    <detail-frame :title="mainTitle" returns="/plan/index">
      <el-row :gutter="10" type="flex">
        <el-col :span="12">
          <el-card header="全年计划信息">
            <el-form :model="info" label-width="60px" size="small" @submit.native.prevent>
              <el-form-item label="年份">
                {{ info.year }}
              </el-form-item>
              <el-form-item label="标题" prop="title">
                {{ info.title }}
              </el-form-item>
              <!-- <el-form-item label="备注" prop="remark">
                <el-input v-model="info.remark" type="textarea" :autosize="{ minRows: 3, maxRows: 5 }"></el-input>
              </el-form-item> -->

              <el-collapse v-model="collapse" accordion>
                <el-collapse-item title="上报可行时间列表" name="1">
                  <data-table :fields="fields" :data="selected" :opera="opera" @delete="toDelete" :height="heights"></data-table>
                </el-collapse-item>
              </el-collapse>
              <el-form-item>
                <el-row type="flex" align="middle" justify="space-around" style="margin-top:20px">
                  <el-col :span="6">
                    <el-button type="primary" @click="savePlan">上报选择时间</el-button>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
        <el-col :span="16" :style="`width:${widths}px`">
          <el-card ref="card" v-if="info.year">
            <calendar :year="info.year" :useDraft="false" @eventClick="eventClick" :events="events"></calendar>
          </el-card>
        </el-col>
      </el-row>
    </detail-frame>
  </div>
</template>

<script>
import detailFrame from '@frame/layout/admin/detail-frame';
import calendar from '@frame/components/calendar';
import dataTable from '@frame/components/data-table';
import _ from 'lodash';
import { mapState, createNamespacedHelpers } from 'vuex';
const { mapActions } = createNamespacedHelpers('trainplan');
const { mapActions: schPlan } = createNamespacedHelpers('schPlan');
export default {
  metaInfo: { title: '计划详情' },
  name: 'detail',
  props: {},
  components: { detailFrame, calendar, dataTable },
  data: () => ({
    info: {},
    form: {},
    events: [],
    collapse: '1',
    fields: [
      // { label: '期数', prop: 'termnum' },
      { label: '名称', prop: 'name' },
      { label: '总人数', prop: 'number', format: item => `${item}人` },
    ],
    opera: [
      {
        label: '删除',
        icon: 'el-icon-delete',
        method: 'delete',
        confirm: true,
      },
    ],
    heights: 250,
    selected: [],
  }),
  created() {
    this.search();
    this.searchSch();
  },
  mounted() {},
  methods: {
    ...mapActions(['fetch', 'create', 'update']),
    ...schPlan({
      schQuery: 'query',
      schPlanCreate: 'create',
      schPlanUpdate: 'update',
    }),
    async searchSch() {
      let res = await this.schQuery({ planid: this.id, schid: _.get(this.user, 'schid', '99991') });
      if (this.$checkRes(res)) {
        let data = JSON.parse(JSON.stringify(res.data));
        if (res.data.length > 0) {
          this.$set(this.info, `schplanid`, data[0]._id);
          let list = _.flatten(data.map(i => i.term));
          list = list.map(i => {
            if (i.type === '0') i.name = `第${i.termnum}期`;
            else if (i.type) {
              let fRes = _.find(this.events, f => f.termid === i.termid && f.type === i.type);
              i.name = fRes.name || fRes.title;
            } else return {};
            return i;
          });
          this.$set(this, `selected`, list);
        }
      }
    },
    //查询计划
    async search() {
      const res = await this.fetch(this.id);
      if (this.$checkRes(res)) this.$set(this, `info`, res.data);
      let midArr = JSON.parse(JSON.stringify(res.data));
      let events = [];
      events = _.flatten(
        midArr.termnum.map(item => {
          item.batchnum.map(i => {
            i.term = item.term;
            i.termid = item._id; //需要使用期id
            i.id = i._id;
            i.start = JSON.parse(JSON.stringify(i.startdate));
            i.end = JSON.parse(JSON.stringify(i.enddate));
            i.title = JSON.parse(JSON.stringify(i.name));
            delete i.startdate, delete i.enddate, delete i.name;
            return i;
          });
          return item.batchnum;
        })
      );
      let vac = midArr.festivals.map(i => {
        let object = {};
        object.id = i._id;
        object.start = i.begindate;
        object.end = i.finishdate;
        object.rendering = 'background';
        object.color = 'red';
        object.editable = false;
        return object;
      });
      this.$set(this, `events`, events.concat(vac));
    },
    //日历事件点击事件
    eventClick({ event }) {
      let arr = this.events.filter(fil => fil.id == event.id);
      let object = {};
      if (arr.length > 0) {
        //有这个事件
        object = arr[0];

        if (!_.get(object, 'editable', true)) {
          this.$message.warning('不能上报假期的时间');
          return;
        }
      } else {
        console.warn(`无对应id事件`);
        return;
      }

      let { type, termid, id } = object;
      //查重,先查期数一致,再查类型
      //期数没有,则加入;期数有,则看类型,如果是普通班级,则不加入;如果是特殊班级,则查该期是否有特殊班级的id,没有就加入
      let re = () => {
        this.$notify({
          title: '重复添加该期',
        });
      };
      let push = data => {
        this.selected.push(data);
        this.$notify({
          title: '已添加',
        });
      };
      // 需要判断期id和期类型
      let isSelected = this.selected.filter(i => i.termid === termid && i.type == type);
      if (isSelected.length > 0) {
        //因为特殊班一期有一个班,按上面条件过滤后,能确定是否有该期该种班
        re();
        // //普通班=>重复加入
        // if (type === '0') re();
        // else {
        //   // 特殊班=>使用id(batchid,批的id)判断
        //   let res = this.selected.filter(f => f.id === id);
        //   //特殊班重复加入
        //   if (res.length > 0) re();
        //   else push(this.setSchoolDate(object)); //加入
        // }
      } else {
        if (type === '0') {
          let nextArr = this.events.filter(f => f.termid === object.termid && f.type === '0');
          push(this.setSchoolDate(nextArr));
        } else push(this.setSchoolDate(object)); //加入
      }
    },
    //列表删除事件
    toDelete({ data, index }) {
      this.selected.splice(index, 1);
    },
    //保存计划事件
    savePlan() {
      // 获取已选择的时间
      let arr = JSON.parse(JSON.stringify(this.selected));
      //整理数据
      let { year, _id, remark, schplanid } = JSON.parse(JSON.stringify(this.info));
      arr = arr.map(i => {
        let obj = { termnum: i.termnum, termid: i.termid, number: i.number, type: i.type };
        i._id ? (obj.id = i._id) : '';
        return obj;
      });
      let object = { year, planid: _id, remark, term: arr, schid: _.get(this.user, 'schid', '99991') };
      let res;
      let msg;
      //需要找到条件判断是修改还是添加,默认先修改看看出现什么情况
      if (!schplanid) {
        res = this.schPlanCreate(object);
        msg = `时间上报成功`;
      } else {
        object.id = schplanid;
        res = this.schPlanUpdate(object);
        msg = `时间修改成功`;
      }
      if (this.$checkRes(res, msg)) this.$router.push({ path: '/plan/index' });
    },
    setHeight() {
      let heights = this.$refs.card.$el.clientHeight * 0.63;
      this.$set(this, `heights`, heights);
    },
    //添加上报时间
    setSchoolDate(object) {
      let data = JSON.parse(JSON.stringify(object));
      //整合出的数据需要有 期数 termnum;期id termid; 人数 number
      //因为点击普通类型,就会将这一期的所有普通类型添加进去,所以需要用data数组去计算筛选出来的所有事件的人数,期数和期id随意提取一个就好
      //特殊类型就是data是object
      //所以直接判断,如果_.isArray(data)  => 是普通类型的,按普通类型处理;反之为特殊类型,按特殊类型处理
      let res = {};
      if (_.isArray(data)) {
        res.number = data.reduce((pre, cur) => pre + parseInt(cur.class) * parseInt(cur.number), 0);
        res.termnum = JSON.parse(JSON.stringify(data[0].term));
        res.termid = JSON.parse(JSON.stringify(data[0].termid));
        res.type = JSON.parse(JSON.stringify(data[0].type));
        res.name = `第${res.termnum}期`;
      } else {
        res.number = JSON.parse(JSON.stringify(data.number));
        res.termnum = JSON.parse(JSON.stringify(data.term));
        res.termid = JSON.parse(JSON.stringify(data.termid));
        res.type = JSON.parse(JSON.stringify(data.type));
        res.name = JSON.parse(JSON.stringify(data.title));
      }
      return res;
    },
  },
  computed: {
    ...mapState(['user']),
    widths() {
      let width = (document.body.clientWidth - 200) * 0.5;
      return width > 400 ? width : 400;
    },
    id() {
      return this.$route.query.id;
    },
    mainTitle() {
      let meta = this.$route.meta;
      let main = meta.title || '';
      let sub = meta.sub || '';
      return `${main}${sub}`;
    },
    keyWord() {
      let meta = this.$route.meta;
      let main = meta.title || '';
      return main;
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.el-divider--horizontal {
  margin: 5px 0;
}
</style>
