<template>
  <a-drawer
    title="计划预测"
    width="70vw"
    :visible="visible"
    @close="onClose"
    :closable="true"
    :maskClosable="true"
  >
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="fetchData">
        <a-row :gutter="24">
          <a-col :xl="12" :lg="12" :md="12" :sm="24">
            <a-form-item label="日期">
              <a-date-picker valueFormat="YYYY-MM-DD" placeholder="请选择开始日期" class="query-group-cust" v-model="params.calMonthStart"></a-date-picker>
              <span class="query-group-split-cust"></span>
              <a-date-picker valueFormat="YYYY-MM-DD" placeholder="请选择结束日期" class="query-group-cust" v-model="params.calMonthEnd"></a-date-picker>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="fetchData" icon="search">查询</a-button>
              <a-button type="primary" @click="mounted1111" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-table
      :columns="columns"
      :dataSource="deviceData"
      :scroll="{ x: 'max-content' }"
      :rowKey="record => record.id"
      bordered
      :loading="loading"
      size="middle"
    >
      <template slot="deviceName" slot-scope="text,record">
        <div>
          {{record.deviceName}}({{record.deviceCode}})
        </div>
      </template>
    </a-table>
  </a-drawer>
</template>

<script>
import { getDateRange } from "@/utils/util";
import { getAction, postAction } from '@/api/manage' // 替换成你的请求工具

export default {
  name: 'PlanvCalendarChart',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      deviceData: [],
      dateRange: [],
      columns: [],
      params: {
        calMonthStart: '',
        calMonthEnd: ''
      },
      loading: false,
    }
  },
  watch: {
    visible(newVal, oldVal) {
      if(newVal) this.mounted1111()
    }
  },
  methods: {
    async fetchData() {
      // 更新 dateRange
      const start = new Date(this.params.calMonthStart);
      const end = new Date(this.params.calMonthEnd);
      this.dateRange = getDateRange(this.params.calMonthStart, this.dateDiff(start, end) + 1);

      const devices = await this.loadDevice();
      const statusList = await  this.loadData();

      // 生成 statusMap[deviceId][date] = 状态
      const statusMap = {}
      statusList.forEach(s => {
        if (!statusMap[s.deviceId]) statusMap[s.deviceId] = {}
        statusMap[s.deviceId][s.calDay] = s.rapairRange_dictText
      })

      // 构造设备数据，每个设备带有 statusMap
      this.deviceData = devices.map(device => ({
        ...device,
        statusMap: statusMap[device.id] || {},
      }))

      // 构造表格列
      this.buildColumns()
    },
    // 获取设备列表
    loadDevice() {
      return getAction('/device/buDevice/list', {
        pageNo: 1,
        pageSize: 10000,
      }).then(res => {
        if (res.success) return res.result.records || res.result
        this.$message.warning(res.message || '获取设备失败')
        return []
      })
    },
    // 获取检修计划数据
    loadData() {
      this.loading = true;
      return postAction('/plan/planV/generate', this.params).then(res => {
        if(res.success) {
          return getAction('/plan/planV/list', this.params).then(res => {
            console.log('list',res)
            if (res.success) {
              this.loading = false;
              return res.result.records || res.result
            }
            this.$message.warning(res.message || '获取状态失败')
            this.loading = false;
            return []
          })
        }else{
          this.$message.error("计划生成失败");
        }
      })
    },

    buildColumns() {
      this.columns = [
        {
          title: '设备名称',
          dataIndex: 'deviceName',
          fixed: 'left',
          scopedSlots: { customRender: 'deviceName' },
        },
        ...this.dateRange.map(date => ({
          key: date,
          width: '100px',
          title: () => {
            const weekday = this.getWeekday(date) // 如：'周六'
            const isWeekend = weekday === '星期六' || weekday === '星期天'
            return this.$createElement(
              'div',
              {
                style: {
                  color: isWeekend ? 'red' : '#333',
                  fontSize: '14px',
                  textAlign: 'center',
                }
              },
              `${date} (${weekday})`
            );
          },
          customRender: row => {
            const status = (row.statusMap && row.statusMap[date]) || '';
            const bgColor = this.getStatusColor(status);
            return this.$createElement(
              'div',
              {
                style: {
                  background: bgColor,
                  color: '#fff',
                  textAlign: 'center',
                  padding: '4px',
                  borderRadius: '4px',
                  fontSize: '14px',
                  minHeight: '30px',
                }
              },
              status || ''
            );
          },
        })),
      ]
    },
    // 获取日期之间的天数差
    dateDiff(startDate, endDate) {
      const diffTime = endDate.getTime() - startDate.getTime();
      return Math.floor(diffTime / (1000 * 3600 * 24));
    },
    getWeekday(dateStr) {
      const days = ['天', '一', '二', '三', '四', '五', '六'];
      const date = new Date(dateStr);
      return '星期' + days[date.getDay()];
    },
    getStatusColor(status) {
      const colorMap = {
        '周巡检': '#52c41a',
        '月检': '#fae457',
        '双月检': '#f89d1b',
        '三月检': '#fa6565',
        '半年检': '#64aaee',
        '年检': '#2741f3',
        '维修': '#fd0000',
      };
      return colorMap[status] || 'transparent'
    },
    onClose() {
      this.$emit('close')
    },
    mounted1111() {
      this.dateRange = getDateRange(new Date(), 30)
      this.params.calMonthStart = this.dateRange[0]
      this.params.calMonthEnd = this.dateRange[29]
      this.fetchData()
    }
  },

}
</script>

<style scoped>

</style>
