<template>
  <a-drawer
    title="检修计划日历"
    width="60vw"
    :visible="visible"
    @close="onClose"
  >
<!--    <div>-->
<!--      <div class="tag-list">-->
<!--        <a-tag v-for="tag in tagssss" :key="tag.name" :color="tag.color">-->
<!--          {{ tag.name }}-->
<!--        </a-tag>-->
<!--      </div>-->
<!--    </div>-->
    <a-calendar @panelChange="handlePanelChange" @select="selectDate">
      <div slot="dateCellRender" slot-scope="value" class="events">
        <div v-if="getDayData(value)" class="container">
          <div v-for="ga in getDayData(value)" :key="ga.rapairRange_dictText" style="margin-left: 5px">
            <a-tag color="#108ee9" style="font-size: 14px;font-weight: bolder">{{ ga.rapairRange_dictText}}</a-tag>
            <div v-for="item in ga.items" :key="item.id" style="margin-top: 5px">
              <a-tag :color="getWorkOrderStatusColor(item)" @click="createOrder(item)" @contextmenu.prevent="handleRightClick($event,item.id)">{{ item.deviceId_dictText}}</a-tag>
            </div>
          </div>
        </div>
      </div>
      <div slot="monthCellRender" slot-scope="value">
        <div v-if="getMonthData(value)" class="notes-month">
          <section>{{ getMonthData(value) }}</section>
          <span>任务数量</span>
        </div>
      </div>
    </a-calendar>
    <div>
      <color-legend :title="'计划任务状态'" :layout="'horizontal'" :legend-items="legendItems" />
    </div>

    <a-modal
      title="日期任务详情"
      :visible="modelVisible"
      @ok="handleSubmit"
      @cancel="closeModel"
    >
      <a-form :form="modelForm" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }" >
        <a-form-item label="检修任务">
          <j-dict-select-tag placeholder="要生成计划的修程" dict-code="repair_range" v-model="modelForm.rapairRange" />
        </a-form-item>
        <a-form-item label="设备">
          <j-search-select-tag placeholder="要生成计划的设备" dict="bu_device,device_name,id" v-model="modelForm.deviceId" />
        </a-form-item>
      </a-form>
    </a-modal>
    <work-order-modal v-if="workOrderVisible" ref="workOrderModal" @ok="closeWorkOrder" @close="closeWorkOrder"></work-order-modal>
  </a-drawer>
</template>

<script>
import { deleteAction, getAction, postAction } from '@api/manage'
import dayjs from 'dayjs'
import WorkOrderModal from '@views/workOrder/modules/WorkOrderModal.vue'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { mixinDevice } from '@/utils/mixin'
import ColorLegend from '@comp/ColorLegend/index.vue'

export default {
  name: 'PlanCalendarDrawer',
  mixins: [JeecgListMixin, mixinDevice],
  components: { ColorLegend, WorkOrderModal },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    deviceType:{
      type: String,
      default: undefined,
      required: false,
    }
  },
  data () {
    return {
      planList: [], // 当前月份的数据
      currentYearMonth: '', // 当前年月
      modelVisible: false,
      modelForm: {},
      planId: null,
      workOrderVisible: false,
      // 包含 12 种标准色（兼容更多分类）
      legendItems: [
        { id: -1, color: '#02ffff', label: '未创建' },
        { id: 0, color: '#5fa27fc5', label: '已创建' },
        { id: 1, color: '#fa8c16', label: '已分配' },
        { id: 2, color: '#fc35cc', label: '已派工' },
        { id: 3, color: '#13aec2', label: '已开工' },
        { id: 4, color: '#a5e701', label: '已完成' },
        { id: 5, color: '#c77401', label: '未开工' },
        { id: 6, color: '#d4380d', label: '已超时' }
      ]
    }
  },
  watch: {
    visible(newVal, oldVal) {
      if(newVal) this.mounted1111()
    }
  },
  methods: {
    // 处理日历面板切换事件
    handlePanelChange(value,mode) {
      if(mode === 'month') {
        this.currentYearMonth = value.format('YYYY-MM');
        this.loadData(this.currentYearMonth);
      }
    },
    mounted1111() {
      // 初始化加载当前月份的数据
      this.currentYearMonth = dayjs().format('YYYY-MM');
      this.loadData(this.currentYearMonth);
    },
    // 加载数据
    loadData(yearMonth) {
      let params = {}
      params.calMonth = yearMonth;
      if(this.deviceType) {
        params.deviceTypeId = this.deviceType
      }
      // 从后端加载数据
      getAction("/plan/plan/list",params).then((res) => {
        if (res.success) {
          this.planList = res.result.records||res.result;
        }
        if(res.code===510){
          this.$message.warning(res.message)
        }
      })
    },
    getDayData(value) {
      const dateStr = value.format('YYYY-MM-DD');
      const events = this.planList.filter(item => item.calDay === dateStr);
      if(events.length>0){
        // 根据 rapairRange 分类
        const groupedData = events.reduce((result, item) => {
          const key = item.rapairRange_dictText; // 分类依据
          if (!result[key]) {
            result[key] = []; // 初始化分类数组
          }
          result[key].push(item); // 将对象添加到对应的分类中
          return result;
        }, {});

        // 将结果转换为数组形式
        return Object.keys(groupedData).map(key => ({
          rapairRange_dictText: key,
          items: groupedData[key]
        }));
      }else return null;
    },
    getMonthData(value) {
      if (value.month() === 8) {
        return 233
      }
    },
    onClose() {
      this.$emit('close')
    },
    // 点击日期事件
    selectDate(value) {
      if(!this.planId){
        this.modelForm.calDay = value.format('YYYY-MM-DD');
        this.modelVisible = true;
      }
    },
    handleSubmit(){
      postAction("/plan/plan/add", this.modelForm).then((res) => {
        if (res.success) {
          this.loadData(this.currentYearMonth);
          this.modelVisible = false;
          this.$message.success(res.message);
        } else {
          this.$message.warning(res.message);
        }
      });
    },
    closeModel(){
      this.modelForm = {};
      this.modelVisible = false;
    },
    deleteDevicePlan(devicePlanId) {
      this.planId = devicePlanId;
      var that = this;
      this.$confirm({
        title: "确认删除",
        content: "是否删除此检修任务?",
        onOk: function () {
          deleteAction("/plan/plan/delete", {id: devicePlanId}).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
            } else {
              that.$message.warning(res.message);
            }
          }).finally(()=>{
            that.loadData(that.currentYearMonth);
            that.planId = null;
          });
        }
      });
    },
    //拦截任务标签右键点击事件
    handleRightClick(event,id) {
      event.preventDefault(); // 阻止默认的右键菜单
      this.deleteDevicePlan(id);
    },
    //从检修计划创建工单
    createOrder(item) {
      console.log(item);
      if (item.workOrder != null) {
        return;
      }
      this.planId = item.id;
      this.workOrderVisible = true;

      this.$nextTick(() => {
        this.$refs.workOrderModal.add(item);
        this.$refs.workOrderModal.title = "新增";
        this.$refs.workOrderModal.disableSubmit = false;
      })
    },
    closeWorkOrder() {
      this.planId = null;
      this.workOrderVisible = false;
    },
    getWorkOrderStatusColor(item) {
      if(item.workOrder){
        const legend = this.legendItems.find(x=>x.id===item.workOrder.status)
        return legend.color
      }
      return 'cyan'
    },
  },
}
</script>

<style scoped>
.events {
  list-style: none;
  margin: 0;
  padding: 0;
}
.events .ant-badge-status {
  overflow: hidden;
  white-space: nowrap;
  width: 100%;
  text-overflow: ellipsis;
  font-size: 12px;
}
.notes-month {
  text-align: center;
  font-size: 28px;
}
.notes-month section {
  font-size: 28px;
}
.container {
  display: flex; /* 使用 flexbox 布局 */
  flex-direction: row;
  justify-content: flex-start; /* 水平起始对齐 */
}
.tag-list {
  display: flex;
}
</style>