<template>
  <div>
    <div v-if="showType === 'list'"
         class="g-cnt">
      <el-row :gutter="15">
        <el-col :span="6">
          <div class="m-sizer">
            <div class="item">
              <el-cascader class="customer_cascader"
                           ref="myCascader"
                           size="big"
                           v-model="fmData.orgId"
                           :options="partyOptions"
                           :props="partyOptionsProps"
                           :show-all-levels="false"
                           @change="handleChangeParty"></el-cascader>
            </div>
            <div class="item">
              <el-radio v-model="fmData.isSelf"
                        label="1">本人创建的活动</el-radio>
              <el-radio v-model="fmData.isSelf"
                        label="0">本组织所有活动</el-radio>
            </div>
          </div>

          <div class="m-date">
            <div class="date-top">
              {{ currentDate.year }}年{{ currentDate.month + 1 }}月
            </div>
            <div class="date-big">{{ currentDate.date }}</div>
            <div class="date-week">{{ currentDate.dayFormat }}</div>
          </div>

          <div class="m-list"
               v-if="
              currentDateData.activityList.length > 0 ||
              currentDateData.scheduleList.length > 0
            ">
            <div class="list-title">今日活动/日程</div>
            <div class="list">
              <div class="item"
                   :key="item.activityId"
                   v-for="item in currentDateData.activityList">
                <div class="item-title">
                  {{ item.theme }}
                </div>
                <div class="item-prop">
                  <span>活动类型：</span>
                  <span>{{ item.actTypeName }}</span>
                </div>
                <div class="item-prop">
                  <span>开始时间：</span>
                  <span>{{ item.holdTime }}</span>
                </div>
                <div class="item-prop">
                  <span>活动地点：</span>
                  <span>{{ item.address }}</span>
                </div>
                <div class="item-prop">
                  <span>参加组织：</span>
                  <span>{{ item.joinOrgs.join("、") }}</span>
                </div>
                <div v-if="item.isMe"
                     class="item-ope">
                  <el-button type="primary"
                             v-if="item.isPublish === '0'"
                             size="mini"
                             @click="handleClickHuodong('publish', item)">发布</el-button>
                  <el-button type="success"
                             size="mini"
                             @click="handleClickHuodong('edit', item)">编辑</el-button>
                  <el-button size="mini"
                             @click="handleClickHuodong('del', item)">删除</el-button>
                </div>
              </div>

              <div class="item"
                   :key="item.scheduleId"
                   v-for="item in currentDateData.scheduleList">
                <div class="item-title">
                  {{ item.title }}
                </div>
                <div class="item-prop">
                  <span>提醒时间：</span>
                  <span>{{ item.remindTime }}</span>
                </div>
                <div class="item-prop">
                  <span>备注说明：</span>
                  <span>{{ item.remark }}</span>
                </div>
                <div class="item-ope">
                  <el-button type="success"
                             size="mini"
                             @click="handleClickRicheng('edit', item)">编辑</el-button>
                  <el-button size="mini"
                             @click="handleClickRicheng('del', item)">删除</el-button>
                </div>
              </div>
            </div>
          </div>

          <div class="m-ope">
            <el-button type="warning"
                       style="width: 48%"
                       @click="addHudong">添加活动计划</el-button>
            <el-button style="width: 48%"
                       @click="addRicheng">添加日程</el-button>
          </div>
        </el-col>

        <el-col :span="18">
          <div class="m-cal">
            <div class="hd">
              <div class="hd-year">
                <el-date-picker v-model="currentYearStr"
                                value-format="yyyy"
                                type="year"
                                placeholder="选择年度"
                                size="big"
                                style="width: 150px;">
                </el-date-picker>
              </div>
              <div class="hd-month">
                <div class="month-item"
                     :class="{ 'z-on': m - 1 == currentMonth }"
                     :key="'month' + m"
                     @click="currentMonth = m - 1"
                     v-for="m in 12">
                  <el-badge :value="monthData[m-1]"
                            :hidden="monthData[m-1] == 0"
                            class="item">
                    <div class="month-text">{{ m }}月</div>
                  </el-badge>
                </div>
              </div>
              <div class="hd-btn">
                <el-button type="primary"
                           size="big"
                           @click="handleAddYearPlan">生成年度活动计划</el-button>
              </div>
            </div>
            <calendar :currentYear="currentYear"
                      :currentMonth="currentMonth"
                      @rangeChange="handleRangeChange"
                      @clickDate="handleChangeDate">
              <template v-slot:date-item="{ item, index }">
                <div class="tip"
                     v-if="
                    rangeData[item.dateId] &&
                    rangeData[item.dateId].activityList.length > 0
                  ">
                  <div class="tip-num"
                       v-if="rangeData[item.dateId].activityList.length > 1">
                    {{ rangeData[item.dateId].activityList.length }}
                  </div>

                  <div class="tip-text">
                    <span class="z-on">
                      {{ rangeData[item.dateId].activityList[0].actTypeName }}</span>
                    {{
                      rangeData[item.dateId].activityList[0].isPublish==='0'
                        ? "(未发布)"
                        : "(已发布)"
                    }}
                  </div>
                  <div class="tip-cnt">
                    {{ rangeData[item.dateId].activityList[0].topic }}
                  </div>

                  <div class="all-list"
                       :class="computeAllListClass(index)">
                    <div class="item"
                         :key="item.activityId"
                         v-for="item in rangeData[item.dateId].activityList">
                      <div class="item-title">
                        {{ item.theme }}
                      </div>
                      <div class="item-prop">
                        <span>活动类型：</span>
                        <span>{{ item.actTypeName }}</span>
                      </div>
                      <div class="item-prop">
                        <span>开始时间：</span>
                        <span>{{ item.holdTime }}</span>
                      </div>
                      <div class="item-prop">
                        <span>活动地点：</span>
                        <span>{{ item.address }}</span>
                      </div>
                      <div class="item-prop">
                        <span>参加组织：</span>
                        <span>{{ item.joinOrgs.join("、") }}</span>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="corn"
                     v-if="
                    rangeData[item.dateId] &&
                    rangeData[item.dateId].scheduleList.length > 0
                  ">
                  <div class="corn-num">
                    {{ rangeData[item.dateId].scheduleList.length }}
                  </div>
                  <div class="corn-text">日程</div>

                  <div class="all-list"
                       :class="computeAllListClass(index)">
                    <div class="item"
                         :key="item.scheduleId"
                         v-for="item in rangeData[item.dateId].scheduleList">
                      <div class="item-title">
                        {{ item.title }}
                      </div>
                      <div class="item-prop">
                        <span>提醒时间：</span>
                        <span>{{ item.remindTime }}</span>
                      </div>
                      <div class="item-prop">
                        <span>备注说明：</span>
                        <span>{{ item.remark }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </template>
            </calendar>
          </div>
        </el-col>
      </el-row>
    </div>

    <div v-if="showType === 'yearplan'">
      <yearplan-list :currentYearStr="currentYearStr"
                     @handleOk="handleAddPlanOk"
                     @handleClose="handleAddPlanClose"></yearplan-list>
    </div>

    <el-dialog v-if="showAdd"
               :visible.sync="showAdd"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :title="addDiaTitle"
               width="850px"
               top="5vh"
               class="dialog-h"
               @closed="showAdd = false">
      <add-activity ref="ref_add_form"
                    :formType="formType"
                    :icPartyActId="icPartyActId"
                    @handleOk="handleOk"
                    @handleClose="handleClose"></add-activity>
    </el-dialog>

    <el-dialog v-if="showSchedule"
               :visible.sync="showSchedule"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :title="scheduleDiaTitle"
               width="850px"
               top="5vh"
               class="dialog-h"
               @closed="showSchedule = false">
      <schedule-form ref="ref_schedule_form"
                     :formType="formType"
                     :scheduleId="scheduleId"
                     @handleOk="handleOk"
                     @handleClose="handleClose">
      </schedule-form>
    </el-dialog>
  </div>
</template>

<script>
import { requestPost, requestGet } from "@/js/dai/request";
import nextTick from "dai-js/tools/nextTick";
import calendar from "./cpts/calendar";
import yearplanList from "../orgActivity/activivityList/yearplanList";
import addActivity from "../orgActivity/activivityList/addActivity";
import scheduleForm from "../orgActivity/activivityList/scheduleForm";

function doAfter (fn) {
  return new Promise(async (resolve) => {
    while (!fn()) {
      await nextTick(100);
    }
    resolve();
  });
}

export default {
  name: "party-calendar",
  components: {
    calendar,
    yearplanList,
    addActivity,
    scheduleForm,
  },
  data () {
    let todayObj = new Date();

    return {
      currentYearStr: todayObj.getFullYear() + "",
      currentMonth: todayObj.getMonth(),
      currentDate: {
        year: "",
        month: "",
        date: "",
        day: "",
      },

      currentDateData: {
        scheduleList: [],
        activityList: [],
      },

      monthData: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],

      rangeDateList: [],
      rangeData: {},

      partyOptions: [],
      partyOptionsProps: {
        multiple: false,
        value: "id",
        label: "partyOrgName",
        children: "children",
        checkStrictly: true,
        emitPath: false,
      },

      fmData: {
        orgId: "",
        isSelf: "1",
        yearId: "",
      },

      showAdd: false,
      formType: "add",
      addDiaTitle: "添加活动计划",
      showSchedule: false,
      scheduleDiaTitle: "添加日程提醒",
      showType: "list",

      icPartyActId: "",
      scheduleId: "",
    };
  },
  computed: {
    currentYear () {
      return parseInt(this.currentYearStr);
    },
    apiParams () {
      const { currentYear, fmData } = this;
      return {
        yearId: currentYear,
        orgId: fmData.orgId,
        isSelf: fmData.isSelf,
      };
    },
  },
  watch: {
    "fmData.orgId": function (val) {
      console.log("orgId", val);
      this.getCurrentDateData();
      this.getRangeData();
    },
    "fmData.isSelf": function (val) {
      console.log("isSelf", val);
      this.getCurrentDateData();
      this.getRangeData();
    },
    currentYear: function (val) {
      console.log("watch--currentYear", val);
      this.getMonthData();
    },
  },
  async mounted () {
    await this.getPartyOptions();
    this.getMonthData();
  },
  methods: {
    // 添加活动
    addHudong () {
      this.icPartyActId = "";
      this.addDiaTitle = "新增活动计划";
      this.formType = "add";
      this.showAdd = true;
    },

    // 添加日程
    addRicheng () {
      this.formType = "schedule";
      this.scheduleId = ''
      this.showSchedule = true;
    },

    // 点击活动操作
    handleClickHuodong (type, item) {
      console.log(type, item);
      this.icPartyActId = item.activityId;

      if (type == "publish") {
        // 发布
        this.$confirm("确认发布活动?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.publishActivity();
          })
          .catch((err) => {
            if (err == "cancel") {
              // this.$message({
              //   type: "info",
              //   message: "已取消发布"
              // });
            }
          });
      } else if (type == "edit") {
        // 编辑
        this.addDiaTitle = "修改活动计划";
        this.formType = "edit";
        this.showAdd = true;
      } else if (type == "del") {
        //  删除
        this.$confirm("活动删除后不可恢复，您确定要删除吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.cancelActivity();
          })
          .catch((err) => {
            if (err == "cancel") {
            }
          });
      }
    },

    async publishActivity () {
      const url = `/resi/partymember/icPartyAct/publish/${this.icPartyActId}`;

      const { data, code, msg } = await requestPost(url, {});

      if (code === 0) {
        this.$message.success("发布成功！");
        this.refreshData();
      } else {
        this.$message.error("操作失败！");
      }
    },

    async cancelActivity () {
      const url = "/resi/partymember/icPartyAct/del";

      let params = [];
      params.push(this.icPartyActId);

      const { data, code, msg } = await requestPost(url, params);

      if (code === 0) {
        this.$message.success("删除成功！");
        this.refreshData();
      } else {
        this.$message.error("操作失败！");
      }
    },

    // 点击日程操作
    handleClickRicheng (type, item) {
      console.log(type, item);
      this.scheduleId = item.scheduleId;
      if (type == "edit") {
        // 编辑
        this.scheduleDiaTitle = "修改日程提醒";
        this.formType = "schedule";
        this.showSchedule = true;
      } else if (type == "del") {
        //  删除
        this.$confirm("日程提醒删除后不可恢复，您确定要删除吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.cancelSchedule();
          })
          .catch((err) => {
            if (err == "cancel") {
            }
          });
      }
    },

    async cancelSchedule () {
      const url = "/resi/partymember/icSchedule/del";

      let params = [];
      params.push(this.scheduleId);

      const { data, code, msg } = await requestPost(url, params);

      if (code === 0) {
        this.$message.success("删除成功！");
        this.refreshData();
      } else {
        this.$message.error("操作失败！");
      }
    },

    //刷新日历
    refreshData () {
      this.getMonthData();
      this.getRangeData();
      this.getCurrentDateData();
    },

    handleChangeParty () { },

    handleChangeDate (item) {
      console.log("handleChangeDate");
      this.currentYearStr = item.year + "";
      this.currentMonth = item.month;
      this.currentDate = { ...item };

      this.getCurrentDateData();
    },

    computeAllListClass (index) {
      let x = index % 7;
      let y = Math.floor(index / 7);
      if (x < 3) {
        if (y < 3) {
          return "z-top-left";
        } else {
          return "z-bottom-left";
        }
      } else {
        if (y < 3) {
          return "z-top-right";
        } else {
          return "z-bottom-right";
        }
      }
    },

    handleRangeChange (arr) {
      this.rangeDateList = arr;
      this.getRangeData();
    },

    async getRangeData () {
      const arr = this.rangeDateList;
      const url = "/resi/partymember/icPartyAct/homeSearch";

      if (!this.apiParams.orgId || arr.length == 0) return;

      const { data, code, msg } = await requestPost(url, {
        ...this.apiParams,
        startDate: arr[0].dateId,
        endDate: arr[arr.length - 1].dateId,
      });
      if (code === 0) {
        if (Array.isArray(data)) {
          let rangeData = {};
          arr.forEach((item) => {
            rangeData[item.dateId] = {
              ...item,
              scheduleTotal: 0,
              activityTotal: 0,
              scheduleList: [],
              activityList: [],
            };
            let curr = data.find((val) => val.dateId == item.dateId);
            if (curr) {
              rangeData[item.dateId].scheduleList = curr.scheduleList;
              rangeData[item.dateId].activityList = curr.activityList;
              rangeData[item.dateId].scheduleTotal = curr.scheduleTotal;
              rangeData[item.dateId].activityTotal = curr.activityTotal;
            }
          });
          this.rangeData = rangeData;
          console.log("rangeData", this.rangeData);
        }
      } else {
        this.$message.error(msg);
      }
    },

    async getMonthData () {
      const url = "/resi/partymember/icPartyAct/homeMonthTotal";

      if (!this.apiParams.orgId) return;

      const { data, code, msg } = await requestPost(url, {
        ...this.apiParams,
      });
      if (code === 0) {
        if (Array.isArray(data)) {
          data.forEach((item, index) => {
            this.monthData[index] = parseInt(item.count);
          });
          console.log("--------------monthData", this.monthData);
        }
      } else {
        this.$message.error(msg);
      }
    },

    async getCurrentDateData () {
      const url = "/resi/partymember/icPartyAct/actAndScheduleList";

      if (!this.apiParams.orgId) return;

      const { data, code, msg } = await requestPost(url, {
        ...this.apiParams,
        dateId: this.currentDate.dateId,
      });
      if (code === 0) {
        this.currentDateData.scheduleList = data.scheduleList || [];
        this.currentDateData.activityList = data.activityList || [];
      } else {
        this.$message.error(msg);
      }
    },

    async getPartyOptions () {
      const url = "/resi/partymember/icPartyOrg/getSearchTreelist";
      let params = {
        customerId: localStorage.getItem("customerId"),
        agencyId: localStorage.getItem("agencyId"),
      };

      const { data, code, msg } = await requestGet(url, params);
      if (code === 0) {
        if (Array.isArray(data) && data.length > 0) {
          this.partyOptions = data;
          this.fmData.orgId = data[0].id;
        }
      } else {
      }
    },

    handleAddYearPlan () {
      this.showType = "yearplan";
    },

    handleAddPlanOk () {
      this.showType = "list";
      this.refreshData();
    },
    handleAddPlanClose () {
      this.showType = "list";
    },

    handleClose () {
      this.formType = "";
      this.showAdd = false;
      this.showSchedule = false;
    },

    handleOk () {
      this.handleClose();
      this.refreshData();
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/scss/c/config.scss";
@import "@/assets/scss/c/function.scss";

$blue: #3e8ef7;
$red: #f33;

.g-cnt {
  background-color: #ffffff;
  padding: 20px;
}
.m-cal {
  .hd {
    display: flex;
    margin-bottom: 20px;
    .hd-year {
      margin-top: 6px;
    }
    .hd-month {
      display: flex;

      .month-item {
        position: relative;
        margin-left: 10px;

        /deep/ .el-badge__content {
          z-index: 1;
        }

        &.z-on {
          .month-text {
            background-image: url("../../../../assets/img/modules/communityparty/rili2.png");
            color: #e60000;
          }
        }
        .month-text {
          position: relative;
          z-index: 0;
          width: 50px;
          height: 50px;
          background-image: url("../../../../assets/img/modules/communityparty/rili1.png");
          text-align: center;
          border-radius: 8px;
          line-height: 66px;
          color:#666666;
          font-size: 14px;
          font-weight:bold;
          cursor: pointer;
        }
      }
    }

    .hd-btn {
      margin-top: 6px;
      margin-left: auto;
    }
  }

  .all-list {
    position: absolute;
    z-index: 100;
    padding: 0 10px;
    width: 300px;
    max-height: 200px;
    overflow-y: auto;
    background-color: rgba(#ffffff, 0.9);
    box-shadow: 0 0 10px 3px rgba(#000, 0.1);
    text-align: left;
    color: #999;
    transition: all ease 0.13s;
    transform: scale(0);

    &.z-top-left {
      right: -300px;
      top: 0;
    }
    &.z-top-right {
      left: -300px;
      top: 0;
    }
    &.z-bottom-left {
      right: -300px;
      bottom: 0;
    }
    &.z-bottom-right {
      left: -300px;
      bottom: 0;
    }
    .item {
      padding: 10px 0;
      border-top: 1px dashed rgba(#000, 0.2);
      &:first-child {
        border-top: none;
      }
    }
  }

  .tip {
    position: relative;
    margin: 0 0px;
    padding: 3px 2px 3px 12px;
    line-height: 18px;
    box-shadow: 0 0 10px 5px #eee;
    background-color: #ffffff;
    font-size: 14px;
   
    cursor: pointer;
    color: #666666;
    z-index: 99999;
 
    &:hover {
      .all-list {
        transform: scale(1);
        background:#ffCC00;
        color:#000000;
        font-size:14px;
        border:2px #ff9900 solid;
        border-radius:5px;
        line-height:20px;
      }
    }
    .tip-num {
      position: absolute;
      z-index: 10;
      top: -7px;
      right: -7px;
      border-radius: 100%;
      width: 22px;
      height: 22px;
      line-height: 20px;
      text-align: center;
      font-size: 12px;
      text-align: center;
      color: #ffffff;
      background-color: #ff3300;
      border:#ffffff 2px solid;
    }
    .z-on {
      color: $red;
      font-weight:bold;
    }
    .tip-text {
      @include toe;
      text-align: left;
    }
    .tip-cnt {
      @include toe;
      text-align: left;
      font-size: 10px;
    }

    &::before {
      position: absolute;
      background: url("../../../../assets/img/modules/communityparty/ding.png");
      content: "";
      left: -20px;
      top: -23px;
      bottom: 0;
      margin: auto;
      display: block;
      width: 28px;
      height: 28px;

    }
  }

  .corn {
    position: absolute;
    right: 0;
    top: 0;
    color: #ffffff;
    cursor: pointer;

    &:hover {
      .all-list {
        transform: scale(1);
        background:#ffCC00;
        color:#000000;
        font-size:14px;
        border:2px #ff9900 solid;
        border-radius:5px;
        line-height:20px;
      }
    }
    .corn-num {
      position: absolute;
      z-index: 10;
      top: -10px;
      right: -14px;
      border-radius: 100%;
      width: 22px;
      height: 22px;
      line-height: 20px;
      text-align: center;
      font-size: 12px;
      font-weight:bold;
      text-align: center;
      color: #ffffff;
      background-color: #F56C6C;
      border:#ffffff 2px solid;
    }
    .corn-text {
      position: relative;
      z-index: 1;
      font-size: 14px;
      line-height: 27px;
      font-weight: bold;
      padding-right: 5px;
    }

    &::before {
      content: "";
      display: block;
      position: absolute;
      z-index: 0;
      top: 0;
      right: 0;
      width: 0px;
      height: 0;
      border-top: 25px solid #E60000;
      border-right: 28px solid #E60000;
      border-bottom: 25px solid transparent;
      border-left: 28px solid transparent;
    }
  }
}
.m-sizer {
  .item {
    margin-bottom: 20px;
  }
}

.m-date {
  text-align: center;
  color: $blue;
  line-height: 1.5;
  background-color: #f3f4f5;
  padding: 20px;
  .date-top {
    font-size: 24px;
  }
  .date-big {
    font-size: 100px;
  }
  .date-week {
    font-size: 24px;
  }
}

.m-list {
  margin-top: 20px;
  .list-title {
    width: 100px;
    text-align: center;
    line-height: 24px;
    background-color: $red;
    color: #ffffff;
  }
  .list {
    .item {
      border-top: 1px solid #eee;
      padding: 10px 0;
      line-height: 1.5;
      overflow: hidden;
      .item-title {
        font-weight: bold;
      }
      .item-prop {
        margin: 4px 0;
      }

      .item-ope {
        margin-top: 10px;
        float: right;
      }
    }
  }
}
.m-ope {
  margin-top: 40px;
  display: flex;
  justify-content: space-between;
}
</style>
