<template>
  <div class="calendar-dialog">
    <el-row :gutter="10">
      <!--table数据-->
      <el-col :span="24" :xs="24">
        <div class="main-right-box">
          <!--    搜索条件    -->
          <div class="main-search-box">
            <el-form
              :model="queryParams"
              ref="queryForm"
              size="small"
              :inline="true"
              v-show="showSearch"
            >
              <el-form-item label="机构名称">
                <org-tree
                  v-model="queryParams.orgId"
                  @defaultKey="getDefaultKey"
                  @checkChange="changeCheckBox"
                  @click="handleNodeClick"
                  :showCheckSub="false"
                  :defaultCheckSub="false"
                  ref="orgTree"
                ></org-tree>
              </el-form-item>
            </el-form>
          </div>

          <div style="display: flex">
            <div style="width: 65%">
              <el-calendar v-model="calendarDate">
                <!-- <template
                  slot="dateCell"
                  slot-scope="{date, data}">
                  <p :class="data.isSelected ? 'is-selected' : ''">
                    {{ data.day.split('-').slice(1).join('-') }} {{ data.isSelected ? '✔️' : ''}}
                  </p>
                </template> -->
                <template slot="dateCell" slot-scope="{ data }">
                  <div class="card-group" @click="selectedDate(data)">
                    <!-- <div
                      :class="
                        data.isSelected
                          ? 'is-selected card-calendar-text'
                          : 'card-calendar-text'
                      "
                    >
                      <span>{{ getDate(data.day) }}</span>
                      <el-icon
                        class="el-icon-check"
                        v-if="data.isSelected"
                      ></el-icon>
                    </div> -->
                    <div v-if="isSetedWorkTime(data)" :class="getSelectedTdClass(data)">
                      <span
                        v-for="(item, index) in tableList"
                        :key="index"
                        class="card"
                      >
                        <div v-if="item.ymdDate === data.day" class="card-flag">
                          <div :class="getDayClass(data, item)">
                            <span>{{ getDate(data.day) }}</span>
                            <el-icon
                              class="el-icon-check"
                              v-if="data.isSelected"
                            ></el-icon>
                          </div>
                          <div :class="'card' + getColorIndexByWorkTime(data,item)">
                            <div class="visits-val">
                              {{ item.isDuty === "1" ? "值班" : "" }}
                            </div>
                          </div>
                        </div>
                      </span>
                    </div>
                    <div v-else :class="getSelectedTdClass(data)">
                      <span class="card">
                        <div class="card-flag">
                          <div :class="getDayClass(data, null)">
                            <span>{{ getDate(data.day) }}</span>
                            <el-icon
                              class="el-icon-check"
                              v-if="data.isSelected"
                            ></el-icon>
                          </div>
                          <div :class="'card' + getColorIndexByWorkTime(data,null)">
                            <div class="visits-val">{{ "" }}</div>
                          </div>
                        </div>
                      </span>
                    </div>
                  </div>
                </template>
              </el-calendar>
            </div>
            <div
              style="
                width: 35%;
                background-color: #fff;
                margin-left: 10px;
                box-shadow: 2px 2px 8px #ccc;
              "
            >
              <el-form
                :model="formData"
                :rules="formData.isEnable ? currentRules : {}"
                size="small"
                ref="form"
                label-position="right"
                label-width="120px"
                label-prefix=":"
                :disabled="!canSave()"
              >
                <el-row :gutter="20">
                  <!-- <el-col :span="24">
                    <el-form-item prop="orgName" label="机构：" >
                      <span>{{formData.orgName}}</span>
                    </el-form-item>
                  </el-col> -->
                  <el-col :span="24">
                    <el-form-item label="日期：">
                      <span>{{ formData.ymdDate }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="星期：">
                      <span>{{ parseTime(formData.ymdDate, "dddd") }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item prop="isEnable" label="状态：">
                      <template>
                        <el-radio-group
                          v-model="formData.isEnable"
                          @change="onEnableChange(formData)"
                        >
                          <el-radio text-color="#48bb78" label="1"
                            >营业</el-radio
                          >
                          <el-radio text-color="#f56565" label="0"
                            >歇业</el-radio
                          >
                        </el-radio-group>
                      </template>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item prop="isEnable" label="值班打卡：">
                      <template>
                        <el-radio-group v-model="formData.isDuty">
                          <el-radio text-color="#48bb78" label="1">是</el-radio>
                          <el-radio text-color="#f56565" label="0">否</el-radio>
                        </el-radio-group>
                      </template>
                    </el-form-item>
                  </el-col>
                  <el-col v-if="formData.isEnable == '1'" :span="24">
                    <el-form-item prop="workTime" label="上班时间：">
                      <template>
                        <el-time-select
                          :picker-options="pickerOptions"
                          v-model="formData.workTime"
                        />
                      </template>
                    </el-form-item>
                  </el-col>
                  <el-col v-if="formData.isEnable == '1'" :span="24">
                    <el-form-item prop="workOffTime" label="下班时间：">
                      <template>
                        <el-time-select
                          :picker-options="pickerOptions"
                          v-model="formData.workOffTime"
                        />
                      </template>
                    </el-form-item>
                  </el-col>
                  <el-col v-if="formData.isEnable == '1'" :span="24">
                    <el-form-item prop="openTime" label="营业开始：">
                      <template>
                        <el-time-select
                          :picker-options="pickerOptions"
                          v-model="formData.openTime"
                        />
                      </template>
                    </el-form-item>
                  </el-col>
                  <el-col v-if="formData.isEnable == '1'" :span="24">
                    <el-form-item prop="closeTime" label="营业结束：">
                      <template>
                        <el-time-select
                          :picker-options="pickerOptions"
                          v-model="formData.closeTime"
                        />
                      </template>
                    </el-form-item>
                  </el-col>
                  <el-col v-if="canSave()" :span="24">
                    <el-form-item>
                      <el-button type="primary" @click="onSubmit"
                        >保存</el-button
                      >
                    </el-form-item>
                  </el-col>
                  <el-col v-if="canSave()" :span="24">
                    <el-form-item>
                      <el-button type="primary" @click="submitCopyMouth"
                        >复制到全月并保存</el-button
                      >
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <dialog-template ref="modalTemplate" @ok="getList"></dialog-template>
  </div>
</template>

<script>
import OrgTree from "@/components/orgTree/orgQuerySelector.vue";
import { mapGetters } from "vuex";
import { tableList } from "./api";
import DataRangePicker from "@/components/dateTime/daterange.picker.vue";
import dayjs from "dayjs";
import { timeCheck } from "@/utils/ruoyi";
import { editWorkTime, addWorkTimeDay } from "@/views/system/workTimeSet/api";
import DialogTemplate from "./dialog.template";

//初始化查询日期

// let sDate =new Date(dayjs().subtract(1, 'month').startOf('month'));
// let eDate =  new Date(dayjs().add(1, 'month').endOf('month'));
export default {
  // emits: ['selectedDate'],
  /**  得先引入字典才能使用 */
  dicts: ["sys_business_type", "sys_org_type"],
  /** 引入基础minxins*/
  components: { DataRangePicker, OrgTree, DialogTemplate },
  data() {
    return {
      nowTime: null,
      isNeedLoadedCalendarDate: true,
      // 遮罩层
      loading: false,
      calendarDate: new Date(),
      tableList: null,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        checkSub: false,
        orgId: null,
        pageNum: 1,
        pageSize: 200,
        range: [
          new Date(dayjs().subtract(1, "month").startOf("month")),
          new Date(dayjs().add(1, "month").endOf("month")),
        ],
        noWorkTime: false,
      },
      formData: {},
      // formDataRules: {
      //   isEnable: [{ required: true, message: "请选择状态" }],
      //   workTime: [{ required: true, message: "请输入上班时间" }],
      //   workOffTime: [{ required: true, message: "请输入下班时间" }],
      //   openTime: [{ required: true, message: "请输入营业开始时间" }],
      //   closeTime: [{ required: true, message: "请输入营业结束时间" }],
      // },
    };
  },
  mounted() {
    let dayBtn = document.querySelector(
      ".el-calendar__button-group .el-button-group>button:nth-child(2)"
    );
    dayBtn.disabled=true;
    let dayBtnText = document.querySelector(
      ".el-calendar__button-group .el-button-group>button:nth-child(2)>span"
    );
    dayBtnText.textContent=dayjs(this.calendarDate).format("YYYY-MM");
    
    let prevBtn = document.querySelector(
      ".el-calendar__button-group .el-button-group>button:nth-child(1)"
    );

    prevBtn.addEventListener("click", () => {
      this.judgeDate(this.calendarDate);
      // dayBtn.innerHTML(dayjs(this.calendarDate).format("YYYY-MM"))
      dayBtnText.textContent=dayjs(this.calendarDate).format("YYYY-MM");
    });
    
   
    // console.log("dayBtnText",dayBtnText,dayBtnText.textContent)
    // dayBtnText.innerHTML("xxxx")
    // dayBtn.addEventListener("click", () => {
    //   this.judgeDate(this.calendarDate);
    // });
    let nextBtn = document.querySelector(
      ".el-calendar__button-group .el-button-group>button:nth-child(3)"
    );
    nextBtn.addEventListener("click", () => {
      this.judgeDate(this.calendarDate);
      dayBtnText.textContent=dayjs(this.calendarDate).format("YYYY-MM");
    });

    let parent = document.querySelector(
      ".el-calendar__header .el-calendar__button-group .el-button-group"
    );

    // 创建一个颜色含义图示
    let btnDuty = this.createButton("营业", "btnDuty", "10px");
    let btnUnDuty = this.createButton("歇业", "btnUnDuty", "10px");
    let btnUnSetWorkTime = this.createButton("未配置", "btnUnSetWorkTime", "100px");
    let btnTemplate = this.createButton("按周配置", "btnTemplate", "10px");
    btnTemplate.onclick = function () {
      // 触发事件
      showWorkTimeTemp();
    };
    var that = this;
    function showWorkTimeTemp() {
      // 事件内容
      that.showTemplateDailog();
    }
    parent.insertBefore(btnTemplate, parent.firstChild);
    parent.insertBefore(btnUnSetWorkTime, parent.firstChild);
    parent.insertBefore(btnUnDuty, parent.firstChild);
    parent.insertBefore(btnDuty, parent.firstChild);
  },
  computed: {
    ...mapGetters(["orgId"]),
    pickerOptions() {
      return {
        start: "00:00",
        end: "24:00",
        step: "00:05",
      };
    },
    currentRules: function () {
      if (!this.canSave()) {
        return {};
      } else {
        return {
          isEnable: [{ required: true, message: "请选择状态" }],
          workTime: [{ required: true, message: "请输入上班时间" }],
          workOffTime: [{ required: true, message: "请输入下班时间" }],
          openTime: [{ required: true, message: "请输入营业开始时间" }],
          closeTime: [{ required: true, message: "请输入营业结束时间" }],
        };
      }
    },
  },
  created() {
    this.getNowTime();
  },
  watch: {
    calendarDate(val, oldVal) {
      if (
        val &&
        dayjs(val).format("YYYY-MM") != dayjs(oldVal).format("YYYY-MM")
      ) {
        console.log("calendarDate", val);
        this.judgeDate(val);
      }
    },
  },
  methods: {
    dayjs,
    createButton(btnContent, backgroundColorCss, marginRight) {
      let button = document.createElement("button");
      button.type = "button"; // 类型
      button.className = `el-button el-button--plain el-button--mini ${backgroundColorCss}`; // Calendar默认按钮样式
      button.textContent = btnContent; // 文本
      button.style.cssText = `color:white;margin-left:auto;margin-right:${marginRight}`; // 样式
      return button;
    },
    showTemplateDailog() {
      this.$refs.modalTemplate.show(this.queryParams.orgId);
    },
    judgeDate(calendarDate) {
      console.log(
        "judgeDate calendarDate",
        dayjs(calendarDate).format("YYYY-MM-DD")
      );
      let sDate = new Date(
        dayjs(calendarDate).subtract(1, "month").startOf("month")
      );
      let eDate = new Date(dayjs(calendarDate).add(1, "month").endOf("month"));
      this.queryParams.range = [sDate, eDate];     
      this.isNeedLoadedCalendarDate=true; 
      this.getList();
    },
    selectedDate(data) {
      console.log("selectedDate--->prefix", data);
      this.loadFormData(data.day);
    },
    loadFormData(day) {
      // console.log('selectedDate--->prefix', data)
      let selectedData = null;
      if (this.tableList && this.tableList.length > 0) {
        let index = this.tableList.findIndex((x) => x.ymdDate === day);
        if (index > -1) {
          selectedData = this.tableList[index];
          this.formData = selectedData;
        } else {
          this.formData = this.reset(day);
        }
      } else {
        this.formData = this.reset(day);
      }

      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
      // this.$refs.form.clearValidate();
      console.log("selectedDate--->suffix", selectedData);
    },
    calendarDateChanged() {
      if (this.isNeedLoadedCalendarDate) {
        // this.loadFormData(dayjs().format("YYYY-MM-DD"));
        this.loadFormData(dayjs(this.calendarDate).format("YYYY-MM-DD"));
        this.isNeedLoadedCalendarDate = false;
      }
    },
    reset(day) {
      return {
        orgId: this.queryParams.orgId,
        isEnable: "1",
        isDuty: "0",
        openTime: null,
        closeTime: null,
        workTime: null,
        workOffTime: null,
        ymdDate: day,
      };
    },
    isSetedWorkTime(data) {
      // console.log("isSetedWorkTime",data,this.tableList)
      if (this.tableList && this.tableList.length > 0) {
        // console.log("isSetedWorkTime indexOf",this.tableList.findIndex(x=>x.ymdDate === data.day))
        if (this.tableList.findIndex((x) => x.ymdDate === data.day) > -1) {
          return true;
        }
      }
      return false;
    },
    getDayClass(data, item) {
      let tempColorIndex = this.getColorIndexByWorkTime(data,item);
      return data.isSelected
        ? "is-selected" + " " + "card-text" + tempColorIndex
        : "card-text" + tempColorIndex;
    },
    getSelectedTdClass(data)
    {
      if(data.isSelected)
      {
        return 'tdClass tdSelected';
      }
      else{
        return 'tdClass';
      }
      
    },
    getColorIndexByWorkTime(data,item) {
      // if( data.isSelected) return "4";
      if (item) return item.isEnable == "1" ? "2" : "3";
      else return "1";
    },
    getDate(day) {
      return dayjs(day).format("MM-DD");
    },
    getNowTime() {
      const dateObj = new Date(); // 获取当前时间对象
      const year = dateObj.getFullYear(); // 获取年份
      const month = String(dateObj.getMonth() + 1).padStart(2, "0"); // 获取月份，并补齐两位数
      const day = String(dateObj.getDate()).padStart(2, "0"); // 获取日期，并补齐两位数
      this.nowTime = `${year}-${month}-${day}`;
    },
    getDefaultKey(key) {
      this.queryParams.orgId = key;
      this.getList();
    },
    /** 下穿状态改变*/
    changeCheckBox() {
      this.queryParams.checkSub = !this.queryParams.checkSub;
      this.getList();
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      console.log(this.queryParams, "pages");
      tableList(this.queryParams)
        .then((response) => {
          this.tableList = response.rows;
          this.total = response.total;
          this.loading = false;
          this.calendarDateChanged();
        })
        .catch((err) => {
          this.loading = false;
        });
    },

    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.orgId = data.id;
      this.getList();
    },
    canSave() {
      console.log(
        "canSave",
        this.calendarDate,
        dayjs(this.calendarDate).startOf("day"),
        dayjs(this.calendarDate).startOf("day").isBefore(dayjs())
      );
      if (dayjs(this.calendarDate).startOf("day").isBefore(dayjs())) {
        return false;
      }
      return true;
    },
    onSubmit() {
      this.$refs.form.validate((isValidate) => {
        if (!isValidate) return;
        if (
          !timeCheck([
            this.formData.workTime,
            this.formData.openTime,
            this.formData.closeTime,
            this.formData.workOffTime,
          ])
        ) {
          this.$message.error(
            `请按照（上班时间<营业时间<营业结束<下班时间）顺序配置`
          );
          return false;
        }
        editWorkTime(this.formData).then((res) => {
          this.$message.success("保存成功");
          this.getList();
        });
      });
    },

    /* 重置搜索 */
    resetForm(name) {
      this.queryParams.isEnable = null;
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.queryParams.orgId = this.orgId;
      this.queryParams.checkSub = true;
      this.queryParams.noWorkTime = false;
      this.$refs["orgTree"].setCheckSub(this.queryParams.checkSub);
      this.queryParams.range = [
        dayjs().startOf("month"),
        dayjs().endOf("month"),
      ];
      this.getList();
    },
    submitCopyMouth() {
      if (!this.formData.ymdDate) return this.$message.error("请选择日期");
      if (this.formData.isEnable === null)
        return this.$message.error("请选择营业状态");
      if (this.formData.isEnable == "1") {
        if (!this.formData.openTime)
          return this.$message.error("请选择开始时间");
        if (!this.formData.closeTime)
          return this.$message.error("请选择结束时间");
        if (!this.formData.workTime)
          return this.$message.error("请选择上班时间");
        if (!this.formData.workOffTime)
          return this.$message.error("请选择下班时间");
        if (!timeCheck([this.formData.openTime, this.formData.closeTime]))
          return this.$message.error("开始时间不能大于结束时间");
        if (!timeCheck([this.formData.workTime, this.formData.workOffTime]))
          return this.$message.error("上班时间不能大于下班时间");
      }
      let data = {
        orgIdList: [this.formData.orgId],
        workTimeList: this.copyDataToMonth(),
      };
      console.log("submitCopyMouth", data);
      addWorkTimeDay(data).then((res) => {
        this.$message.success("保存成功");
        this.getList();
      });
    },
    copyDataToMonth() {
      let startOfMonthDay = dayjs(this.formData.ymdDate).startOf("month");
      let endOfMonthDay = dayjs(this.formData.ymdDate).endOf("month");
      let dataList = [];
      while (startOfMonthDay.isBefore(endOfMonthDay)) {
        let temp = { ...this.formData };
        temp.ymdDate = startOfMonthDay.format("YYYY-MM-DD");
        dataList.push(temp);
        startOfMonthDay = startOfMonthDay.add(1, "day");
      }
      return dataList;
    },
  },
};
</script>
<style lang="scss">
$border: 25px;

// 更改elementplus组件的样式
.calendar-dialog {
  
// // 日历边框背景颜色
// :deep(.el-calendar-table td, .el-calendar-table tr:first-child td, .el-calendar-table tr td:first-child) {
//   border-color: $border !important;
// }
// // 日历取消的背景
// :deep(.el-calendar-table td.is-selected) {
//   background-color: $hoverOrSelectBG;
// }
// /* 日历单元格鼠标滑过背景色 */
// :deep(.el-calendar-table .el-calendar-day:hover) {
//   background-color: $hoverOrSelectBG !important;
// }



// .is-selected, .is-today {
//   color: #37e2ce;
//   background-color: $hoverOrSelectBG !important;
// }
  .el-calendar-table .el-calendar-day {
    padding: 0;
  }

  .el-icon {
    height: 8px;
  }

  .card-group.card-calendar-text {
    display: flex;
    justify-content: space-between;
  }

  .el-calendar {
    box-shadow: 0 0 12px 0 #e4e7ed;

    .el-calendar-table {
      thead {
        background-color: #f5f7fa;
      }
    }
  }
}
</style>
<style lang="scss" scoped>
$titleHeight: 25px;
$dutyColor: rgb(47, 133, 90);
$unSetWorkTime: #bdbdbd;
$unDutyColor: rgb(183, 121, 31);
$btnTemplate: #008CD6;
$hoverOrSelectedBG:#7a8185;

@mixin btn-o($btnBgColor) {  
  background-color: $btnBgColor;
}

@mixin card-o($bgColor) {
  position: relative;
  display: block;
  width: 100%;
  height: 100%;
  font-size: 15px;
  color: #FFF;
  background-color: $bgColor;
}

@mixin card-text-o($bgColor) {
  display: flex;
  justify-content: space-between;
  height: $titleHeight;
  max-height: $titleHeight;
  min-height: $titleHeight;
  padding-left:10px;
  padding-top:5px;
  font-size: 20px;
  color: #FFF;
  background-color: $bgColor;
}



.calendar-dialog {
  ::v-deep .el-calendar{
    .el-calendar__header{
        .el-calendar__button-group{
          .el-button-group{
            .btnDuty{
              @include btn-o($dutyColor);
            }
            .btnUnDuty{
              @include btn-o($unDutyColor);
            }
            .btnUnSetWorkTime{
              @include btn-o($unSetWorkTime);
            }
            .btnTemplate{
              @include btn-o($btnTemplate);
            }
          }
        }
      }
  }
  .tdSelected{
      // background-color: $hoverOrSelectedBG;
      border: 5px solid #f14704;
      ::v-deep .card{
        .card-flag{
          .card1 .card-text1 .card2 .card-text2 .card3 .card-text3{
            // background-color: $hoverOrSelectedBG !important;
          }
        }
      }
    }
  .card-group {
    width: 100%;
    height: 100%;

    .card-calendar-text {
      height: $titleHeight;
      max-height: $titleHeight;
      min-height: $titleHeight;
    }

    .card {
      position: relative;
      // top: -$titleHeight;
    }

    .card-flag {
      height: calc(100% - $titleHeight);
    }

    .card1 {
      @include card-o($unSetWorkTime);
    }

    .card-text1 {
      @include card-text-o($unSetWorkTime);
    }

    .card2 {
      @include card-o($dutyColor);
    }

    .card-text2 {
      @include card-text-o($dutyColor);
    }

    .card3 {
      @include card-o($unDutyColor);
    }

    .card-text3 {
      @include card-text-o($unDutyColor);
    }
    .card4 {
      @include card-o($hoverOrSelectedBG);
    }

    .card-text4 {
      @include card-text-o($hoverOrSelectedBG);
    }

    .tdClass{
      height: 100%;
    }

  

    .tdClass :hover .card1{
      cursor: pointer;
      background-color: $hoverOrSelectedBG;
    }
    .tdClass :hover .card-text1{
      cursor: pointer;
      background-color: $hoverOrSelectedBG;
    }

    .tdClass :hover .card2{
      cursor: pointer;
      background-color: $hoverOrSelectedBG;
    }
    .tdClass :hover .card-text2{
      cursor: pointer;
      background-color: $hoverOrSelectedBG;
    }

    .tdClass :hover .card3{
      cursor: pointer;
      background-color: $hoverOrSelectedBG;
    }
    .tdClass :hover .card-text3{
      cursor: pointer;
      background-color: $hoverOrSelectedBG;
    }   

    .visits-val {
      position: absolute;
      right: 0;
      bottom: 0;
    }
  }
  .card-group:focus,
  .card-group:hover {
    background-color: #33a3de;
  }
}
</style>

