<template>
  <div class="common-page device-manage">
    <div class="title">
      <div><input type="button" id="title-btn-left" value="<" class="title-btn-hover" @click="lastMonthCalender()"/>
      </div>
      <div class="show_year_month">
        <div>
          <label id="showMonth">{{ showMonth }}<span style="font-size:22px"> 月 </span></label>
          <el-button id="planSlotBtn" size="mini" type="success" icon="el-icon-date" plain circle @click="showPlanDateSlot()">创建计划</el-button>
        </div>
        <div>
          <label id="showYear">{{ showYear }}年{{ showMonth }}月份生产计划表</label>
        </div>
      </div>
      <div><input type="button" id="title-btn-right" value=">" class="title-btn-hover" @click="nextMonthCalender()"/>
      </div>
    </div>
    <div class="table">
      <div class="tableRow">
        <div class="tbTitle">周一</div>
        <div class="tbTitle">周二</div>
        <div class="tbTitle">周三</div>
        <div class="tbTitle">周四</div>
        <div class="tbTitle">周五</div>
        <div class="tbTitle">周六</div>
        <div class="tbTitle">周日</div>
      </div>
      <div v-for="(weekArr,r) in showMonthCalender" class='tableRow'>
        <div v-for="(day,c) in weekArr" :class='day.cssClass' @click="openPlanView(day)">
          <div v-if="day.totalPlan>0">
            <div style="width: 100%;display:flex">
              <div style="width: 30%;text-align: center">
                <div style="font-size:38px;font-weight:800">{{ day.day }}</div>
              </div>
              <div style="width: 70%;font-size:12px;text-align:center;padding-top:2px">
                计划产量：<span style="font-size:18px;font-weight:400;color:#228b22;">{{ day.totalPlan }}</span> 吨<br>
                实际产出：<span style="font-size:18px;font-weight:400;color:#356eec">{{ day.totalProduce }}</span> 吨<br>
              </div>
            </div>
            <div style="width:100%;font-size:12px;padding-left:5px;">采点分配概览：</div>
            <div class="fbListBox">
              <div v-for="item in day.sumList" :style="{width:item.pv+'%',height:'2px',margin:'2px',background:'#8fbc8f'}">
                <div :style="{width:item.av+'%',height:'2px',background:'#00a0e9'}"></div>
              </div>
            </div>
          </div>
          <div v-else>
            <div style="width: 100%;display:flex">
              <div style="width: 30%;text-align: center">
                <div style="font-size:38px;font-weight:800">{{ day.day }}</div>
              </div>
              <div style="width: 70%;font-size:12px;text-align:center;padding-top:10px">当日无计划</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="calender-footer">
      <div class="button-group">
        <span id="plusYear" class="cal" @click="minusOneYear()">-</span>
        <div id="year" class="inp">{{ inputYear }} 年</div>
        <span id="minusYear" class="cal" @click="plusOneYear()">+</span>
      </div>
      <div class="button-group" style="font-size:14px;line-height: initial;">
        总储量<span style="color:#e83764;font-size:20px;"> {{totalReserves}} </span>万吨
      </div>
      <div class="button-group" style="font-size:14px;line-height: initial;">
        剩余储量<span style="color:#f58c21;font-size:20px;"> {{totalSurplus}} </span>万吨
      </div>
      <div class="button-group" style="font-size:14px;line-height: initial;">
        本月计划累计<span style="color:#228b22;font-size:20px;"> {{monthPlanSum}} </span>万吨
      </div>
      <div class="button-group" style="font-size:14px;line-height: initial;">
        本月实际产出<span style="color:#356eec;font-size:20px;"> {{monthProduceSum}} </span>万吨
      </div>
      <div class="button-group">
        <span id="minusMonth" class="cal" @click="lastMonthCalender()">-</span>
        <div id="month" class="inp">{{ inputMonth }} 月</div>
        <span id="plusMonth" class="cal" @click="nextMonthCalender()">+</span>
      </div>
    </div>
    <el-dialog title="当日生产计划明细" :visible.sync="dialogPlanVisible" width="60%">
<!--      <div class="toolbar" style="margin-bottom:15px;display:flex">-->
<!--        <el-button size="mini" type="primary" icon="el-icon-plus" @click="showPlanDateSlot()">批量选取日期</el-button>-->
<!--        <div v-show="showDateSlot">-->
<!--          <label class="el-form-item-label" style="margin-left:150px;">选择起止日期：</label>-->
<!--          <el-date-picker v-model="planSDate" type="date" placeholder="选择开始日期"></el-date-picker>-->
<!--          ~-->
<!--          <el-date-picker v-model="planEDate" type="date" placeholder="选择结束日期"></el-date-picker>-->
<!--        </div>-->
<!--      </div>-->
      <el-table :data="planData" border show-summary>
        <el-table-column property="minePoint" label="采区名称" align="center"></el-table-column>
        <el-table-column property="plan" label="计划量(T)" align="center">
          <template slot-scope="scope">
            <el-input placeholder="请输入计划量(T)" v-model="scope.row.plan" clearable></el-input>
<!--            <el-input placeholder="请输入计划量(T)" v-model="scope.row.plan" clearable :disabled="planValIsReadonly"></el-input>-->
          </template>
        </el-table-column>
        <el-table-column property="actualProduction" label="实际产出(T)" align="center">
          <template slot-scope="scope">
            <el-input placeholder="请输入实际产出(T)" v-model="scope.row.actualProduction" clearable></el-input>
          </template>
        </el-table-column>
<!--        <el-table-column property="actualProduction" label="实际产出(T)" align="center"></el-table-column>-->
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelPlanView()">取消</el-button>
<!--        <el-button v-show="!planValIsReadonly" type="primary" @click="submitPlanView()">提交</el-button>-->
        <el-button type="primary" @click="submitPlanView()">提交</el-button>
      </div>

    </el-dialog>
    <el-dialog title="创建生产计划" :visible.sync="showDateSlot" width="60%">
      <div class="toolbar" style="margin-bottom:15px;display:flex">
        <div>
          <label class="el-form-item-label" style="margin-left:150px;">选择起止日期：</label>
          <el-date-picker v-model="planSDate" type="date" placeholder="选择开始日期"></el-date-picker>
          ~
          <el-date-picker v-model="planEDate" type="date" placeholder="选择结束日期"></el-date-picker>
        </div>
      </div>
      <el-table :data="planData" border show-summary>
        <el-table-column property="minePoint" label="采区名称" align="center"></el-table-column>
        <el-table-column property="plan" label="计划量(T)" align="center">
          <template slot-scope="scope">
            <el-input placeholder="请输入计划量(T)" v-model="scope.row.plan" clearable></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelPlanView()">取消</el-button>
        <el-button type="primary" @click="submitPlanView()">提交</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import {Tools, HttpReq, Dates} from '@/assets/js/common.js';

export default {
  name: 'productionPlan',
  components: {},
  data() {
    return {
      dialogPlanVisible: false,
      showDateSlot: false,
      planValIsReadonly: true,
      totalReserves: 50190,
      totalSurplus: 20204,
      monthPlanSum: 351,
      monthProduceSum: 365,
      //底部输入框中的年月
      inputYear: '',
      inputMonth: '',
      //一个月的日历
      showMonthCalender: [],
      //头部中间的年月
      showMonth: '',
      showYear: '',
      planData: [],
      planSDate: '',
      planEDate: '',
    }
  },
  mounted() {
    var that = this;
    this.$nextTick(() => {
      this.updateWebPage();
    })
  },
  methods: {
    openPlanView(day) {
      this.dialogPlanVisible = true;
      this.planSDate = day.year + '-' + day.month + '-' + day.day;
      this.planEDate = this.planSDate;
      this.planData = [];
      if (this.planSDate < new Date().toJSON().substr(0, 10)) {
        this.planValIsReadonly = true;
      } else {
        this.planValIsReadonly = false;
      }
      HttpReq.truckDispatching.tPlanGetOneDayPlanByTime({
        day: this.planSDate
      }).then((res) => {
        if (res.code == 200) {
          this.planData = res.data || [];
        }
      })
    },
    submitPlanView(){
      const This = this;
      // this.planSDate = this.planSDate.toJSON?this.planSDate.toJSON().substr(0,10):this.planSDate;
      // this.planEDate = this.planEDate.toJSON?this.planEDate.toJSON().substr(0,10):this.planEDate;
      let d = new Date(this.planSDate);
      this.planSDate=`${d.getFullYear()}-${('0' + (d.getMonth() + 1)).substr(-2)}-${('0' + (d.getDate())).substr(-2)}`;
      d = new Date(this.planEDate);
      this.planEDate=`${d.getFullYear()}-${('0' + (d.getMonth() + 1)).substr(-2)}-${('0' + (d.getDate())).substr(-2)}`;
      if(this.planSDate>this.planEDate){
        This.$notify({
          title: '注意：计划开始时间不能大于结束时间！',
          type: 'warning',
          duration: 2500
        });
        return;
      }
      HttpReq.truckDispatching.tPlanChangeTPanDay({
        startTime: this.planSDate,
        endTime: this.planEDate,
        username: this.$store.state.user.user.nickName,
        tPlanDayList:this.planData
      }).then((res) => {
        if (res.code == 200) {
          This.$notify({
            title: res.msg,
            type: 'success',
            duration: 2500
          });
          This.cancelPlanView();
          This.updateWebPage();
        }else{
          This.$notify({
            title: '提交失败！',
            type: 'warning',
            duration: 2500
          });
        }
      })
    },
    showPlanDateSlot() {
      this.showDateSlot = !this.showDateSlot;
      document.getElementById("planSlotBtn").blur();
      let d=new Date();
      if(d.getMonth()+1===Number(this.showMonth)){
        this.planSDate = this.showYear + '-' + this.showMonth + '-' + ('0' + d.getDate()).substr(-2);
      }else{
        this.planSDate = this.showYear + '-' + this.showMonth + '-01';
      }
      this.planEDate = this.showYear + '-' + this.showMonth + '-'+this.monthDays(Number(this.showYear), Number(this.showMonth)-1);
      this.planData = [];
      HttpReq.truckDispatching.tPlanGetOneDayPlanByTime({}).then((res) => {
        if (res.code == 200) {
          this.planData = res.data || [];
        }
      })
    },
    cancelPlanView() {
      this.dialogPlanVisible = false;
      this.showDateSlot = false;
    },
    //计算日期对应周几
    dateMapWeekDay(year, month, date) {
      let weekDay = new Date(year, month, date).getDay();
      return weekDay === 0 ? 7 : weekDay;
    },
    //一个月有多少天
    monthDays(year, month) {
      if (month < 0)
        return new Date(year - 1, 12, 0).getDate();
      else
        return new Date(year, month + 1, 0).getDate();
    },
    //实际生成日历
    produceMonthCalender(lastMonthDays, curMonthDays, firstWeekOfDay, lastWeekDay, currentDay) {
      let createCalender = [];
      //上一个月显示几天
      let prev = firstWeekOfDay - 1;
      //从上个月的几号开始显示
      let prevDay = lastMonthDays - prev + 1;
      //下个月从1号开始显示
      let nextDay = 1;
      let day = 1;
      let month = Number(this.showMonth);
      let year = Number(this.showYear);
      for (let curRow = 0; curRow < 6; curRow++) {
        let weekTempArr = [];
        for (let weekDay = 1; weekDay <= 7; weekDay++) {
          let dayObj = {totalPlan: 0, totalProduce: 0};
          if (prev > 0) {//显示上个月日期
            dayObj.cssClass = 'prev';
            dayObj.month = month - 1;
            if (dayObj.month === 0) {
              dayObj.month = 12;
              dayObj.year = year - 1;
            } else {
              dayObj.year = year;
            }
            dayObj.day = prevDay;
            prev--;
            prevDay++;
          } else {
            //显示当月日期
            if (day <= curMonthDays) {
              if (currentDay === day) {
                dayObj.cssClass = 'curDay';
              } else {
                dayObj.cssClass = '';
              }
              dayObj.day = day;
              dayObj.month = month;
              dayObj.year = year;
              day++;
            } else {//显示下个月日期
              dayObj.cssClass = 'next';
              dayObj.month = month + 1;
              if (dayObj.month === 13) {
                dayObj.month = 1;
                dayObj.year = year + 1;
              } else {
                dayObj.year = year;
              }
              dayObj.day = nextDay;
              nextDay++;
            }
          }
          dayObj.month=('0'+dayObj.month).substr(-2);
          dayObj.day=('0'+dayObj.day).substr(-2);
          dayObj.cssClass += ' tableCell';
          weekTempArr.push(dayObj);
        }
        createCalender.push(weekTempArr)
      }
      this.showMonthCalender = createCalender;
      let startTime = createCalender[0][0].year + '-' + createCalender[0][0].month + '-' + createCalender[0][0].day;
      let endTime = createCalender[5][6].year + '-' + createCalender[5][6].month + '-' + createCalender[5][6].day;
      HttpReq.truckDispatching.tPlanGetDayByTime({
        startTime,endTime
      }).then((res) => {
        if (res.code == 200) {
          for (let curRow = 0; curRow < 6; curRow++) {
            for (let weekDay = 0; weekDay < 7; weekDay++) {
              let dayObj = createCalender[curRow][weekDay];
              let resData = res.data[curRow * 7 + weekDay];
              let maxVal = resData.maxSite || 1;
              dayObj.totalPlan = resData.totalPlan;
              dayObj.totalProduce = resData.totalProduce;
              dayObj.sumList = resData.sumList || [];
              dayObj.sumList.forEach((item) => {
                item.pv = Math.round(item.plan / maxVal * 100);
                item.av = Math.min(100, Math.round(item.actualProduction / item.plan * 100));
              });
              if (dayObj.totalPlan) {
                dayObj.cssClass = 'planCell '+ dayObj.cssClass;
              }
            }
          }
        }
      })
    },
    //生成指定年，月的日历
    monthCalender(year, month) {
      let lastMonthDays = this.monthDays(year, month - 1);
      let monthDays = this.monthDays(year, month);
      let weekOfDay = this.dateMapWeekDay(year, month, 1);
      let lastWeekDay = this.dateMapWeekDay(year, month, monthDays);
      //如果是当前年月就标记今天
      let currentDay = -1;
      let nowDate = new Date();
      if (year === nowDate.getFullYear() && month === nowDate.getMonth()) {
        currentDay = nowDate.getDate();
      }
      this.produceMonthCalender(lastMonthDays, monthDays, weekOfDay, lastWeekDay, currentDay);
    },
    //生成上个月日历
    lastMonthCalender() {
      let curYear = Number(this.inputYear);
      let lastMonth = Number(this.inputMonth) - 1 - 1;//-1是本月对应js中的月份===>实际是1月，在js中表示1月：0，再-1才是上一个月
      if (lastMonth >= 0) {
        this.updateWebPage(curYear, lastMonth + 1);
      } else {
        this.updateWebPage(curYear - 1, 12);
      }
    },
    //生成下个月日历
    nextMonthCalender() {
      let curYear = Number(this.inputYear);
      let nextMonth = Number(this.inputMonth);//已经是curMonth + 1
      if (nextMonth > 11) {
        this.updateWebPage(curYear + 1, 1);
      } else {
        this.updateWebPage(curYear, nextMonth + 1);
      }
    },
    //更新页面的数据
    updateWebPage(year, month) {
      if (year === undefined || year === null) {
        year = new Date().getFullYear();
        month = new Date().getMonth() + 1;
      }
      this.inputYear = year + "";
      this.inputMonth = ('0'+month).substr(-2);
      this.showYear = year + "";
      this.showMonth = ('0'+month).substr(-2);
      this.monthCalender(year, month - 1);
      HttpReq.truckDispatching.tPlanGetProductionStatistics({
        yearMonth: this.showYear+'-'+this.showMonth
      }).then((res) => {
        if (res.code == 200) {
          this.totalReserves=res.data.totalReserves;
          this.totalSurplus=res.data.remainingReserves;
          this.monthPlanSum=res.data.masterPlan;
          this.monthProduceSum=res.data.actualOutput;
        }
      })
    },
    //生成指定年月日历
    changeYearOrMonth(yearVal, monthVal) {
      try {
        this.checkTime(yearVal, monthVal);
        this.updateWebPage(Number(yearVal), Number(monthVal));
      } catch (e) {
        confirm(e);
      }
    },
    //生成上一年日历
    minusOneYear() {
      this.changeYearOrMonth(Number(this.inputYear) - 1 + "", this.inputMonth);
    },
    //生成下一年日历
    plusOneYear() {
      this.changeYearOrMonth(Number(this.inputYear) + 1 + "", this.inputMonth);
    },
    //检查输入框的年，月是否合法
    checkTime(year, month) {
      if (!month.match(/^\d+$/)) {
        throw '【月份】错误：' + month;
      }
      if (Number(month) < 1 || Number(month) > 12) {
        throw '【月份】错误：' + month;
      }
      if (!year.match(/^\-?\d+$/)) {
        throw '【年份】错误：' + year;
      }
    },
  },
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
#title-btn-left, #title-btn-right {
  margin: 20px 0px 20px 0px;
  padding: 0px 15px 0px 15px;
  font-size: 40px;
  border: 0px;
  background: rgb(251, 250, 250);
}

.show_year_month {
  /* margin: 10px 0px 10px 0px; */
  display: flex;
  flex-direction: column;
}

#showMonth {
  font-size: 60px;
  color: forestgreen;
}

#showYear {
  font-size: 16px;
  color: darkseagreen;
}

.title-btn-hover:hover, .title-btn-hover:active {
  cursor: pointer;
}

.title {
  width: 100%;
  padding: 10px 15px 90px 15px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  background: rgb(250, 250, 250);
  text-align: center;
  font-size: 20px;
  height: 60px;
}

.cal {
  background: rgb(230, 224, 224);
  border: 1px;
  width: 30px;
  font-size: 20px;
  text-align: center;
  margin: 0;
  padding: 0;
}

.cal:hover {
  cursor: pointer;
}

.cal:active {
  cursor: default;
}

.inp {
  width: 100px;
  font-size: 20px;
  text-align: center;
  margin: 0;
  background: rgb(250, 250, 250);
  border-color: rgb(174, 177, 177);
  border: 1px;
}

.table {
  display: table;
  width: 100%;
  background: #fafafa;
  padding: 0 5px;
}

.tableRow {
  display: table-row;
  background-color: snow;
}

.tableCell {
  display: table-cell;
  border: 1px solid rgba(100, 100, 100, 0.1);
  height: 90px;
  width: 14%;
  background: rgba(169, 169, 169, 0.3);
  cursor: pointer;
}

.tableCell:hover {
  color: rgb(255, 255, 255);
  background: rgba(234, 153, 30, 0.5);
}

.tbTitle {
  display: table-cell;
  border: 1px solid rgba(100, 100, 100, 0.1);
  text-align: center;
  background: #f4f4f5;
  height: 20px;
}

.planCell {
  background: rgba(166, 204, 173, 0.3)
}

.container {
  padding: 0;
  margin: 0;
  top: 40px;
  left: 40px;
  display: flex;
  width: 50%;
  box-shadow: 10px 10px 5px #935f5f;
}

.calender-footer {
  padding: 10px;
  margin: 0;
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  /* justify-content: flex-end */
  justify-content: space-between;
  background: rgb(250, 250, 250);
}

.prev, .next {
  color: rgb(120, 121, 120, 0.7);
  //background-color: rgb(234, 153, 30, 0.1);
}

.curDay {
  background: rgba(166, 204, 173, 0.9);
}

.button-group {
  margin: 0;
  padding: 0;
  display: flex;
}

.cal-footer-time {
  font-size: 20px;
  text-align: start;
  font-family: sans-serif;
}
.fbListBox {
  width: 100%;
  height: 34px;
  padding-left: 10px;
  padding-right: 10px;
  overflow-y: auto;
  overflow-x: hidden;
}
.fbListBox::-webkit-scrollbar {
  width: 0;
  height: 0;
}
</style>
