<template>
  <div class="page-container row-container">
    <section class="list-part-container" style="flex: 2">
      <!-- 搜索区 -->
      <el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true">
        <!-- <el-form-item label="年份：" prop="year">
          <el-date-picker v-model="queryParams.year" type="year" value-format="YYYY" :editable="false"
            :clearable="false" placeholder="请选择时间" @change="handleYearChange" style="width: 130px" />
        </el-form-item> -->
        <el-form-item label="工艺图纸电子化基数：" v-hasPermi="['business:conversion:query']" prop="number">
          <span v-if="!disabled">{{ number }}</span>
          <el-input v-if="disabled" v-model.trim="number" style="width: 220px; margin-left: 0px" />
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleAdd">添加</el-button>
          <el-button type="warning" @click="getList">刷新</el-button>
        </el-form-item>
      </el-form>
      <!-- 列表区 -->
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleTabClick" height="100%"
        style="margin-left: 10px; margin-right: 10px;">
        <el-tab-pane label="图表" name="first">
          <div style="position: relative;width: 100%; height: 100%; overflow-x: auto; margin-left: 20px;">
            <div ref="echartDom" id="echartDom" :style="{ height: chartHeight, width: chartWidth }" />
          </div>
        </el-tab-pane>
        <el-tab-pane label="表格" name="second">
          <el-table ref="completeTable" v-loading="loading" :data="completeList" row-key="id" height="100%" border
            highlight-current-row>
            <el-table-column label="序号" type="index" width="50" align="center"></el-table-column>
            <el-table-column label="年月" width="140" align="center">
              <template #default="scope">
                <el-date-picker v-if="scope.row.editStatus" v-model="scope.row.yearMonth" type="month"
                  value-format="YYYY-MM-DD" placeholder="选择月" clearable style="width: 100%;"
                  @change="(arg) => handleRowYearMonthChange(arg, scope.row)" />
                <div v-else>{{ scope.row.year }}-{{ scope.row.month }}</div>
              </template>
            </el-table-column>
            <el-table-column label="计划数量" type="planNum" width="120" align="center">
              <template #default="scope">
                <el-input-number v-if="scope.row.editStatus" v-model="scope.row.planNum" :min="0" :controls="false"
                  style="width: 100%;" />
                <div v-else>{{ scope.row.planNum }}</div>
              </template>
            </el-table-column>
            <el-table-column label="实际数量" type="actualNum" width="120" align="center">
              <template #default="scope">
                <el-input-number v-if="scope.row.editStatus" v-model="scope.row.actualNum" :min="0" :controls="false"
                  style="width: 100%;" />
                <div v-else>{{ scope.row.actualNum }}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="160" align="center">
              <template #default="scope">
                <el-button v-if="scope.row.editStatus" type="success" @click="handleSave(scope.row)">保存</el-button>
                <el-button v-else type="primary" @click="() => scope.row.editStatus = true">编辑</el-button>
                <el-button v-if="scope.row.editStatus" type="danger"
                  @click="() => scope.row.editStatus = false">取消</el-button>
                <el-button v-else type="danger" @click="handleDel(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 表单 -->

    </section>
  </div>
</template>

<script setup name="Conversion">
import { listConversion, addConversion } from '@/api/business/conversion'
import { listCompletion, getCompletion, addCompletion, updateCompletion, delCompletion } from '@/api/business/processCompletion'
import { ref, onMounted, reactive, computed } from 'vue'
import * as echarts from 'echarts'
import { getProcuctDrawing } from '@/api/business/drawing'
import { markRaw } from "vue"
const { proxy } = getCurrentInstance();
const disabled = ref(false)
const echartInstance = ref(null)
const itemNum = ref(0)
const echartDom = ref(null)
const procuctDrawing = ref(0)
const number = ref(0)
const rawData = ref([])
const chartHeight = ref(`${window.innerHeight - 200}px`)
const chartWidth = ref(`${window.innerWidth - 200}px`)
const months = ref(['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'])
const currentMonthIndex = computed(() => new Date().getMonth())
/** 字典 */
const { conversion_mes } = proxy.useDict("conversion_mes");
const data = reactive({
  queryParams: {
    year: new Date().getFullYear().toString()
  }
})
const loading = ref(false)
const completeList = ref([])

const activeName = ref('first')

const { queryParams } = toRefs(data)
const getWindowInfo = () => {
  initGrophSize();
};

const debounce = (fn, delay) => {
  let timer;
  return function () {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn();
    }, delay);
  }
};
const cancalDebounce = debounce(getWindowInfo, 500);

onUnmounted(() => {
  console.log('onUnmounted', '打印是否生效');
  //移除监听事件
  window.removeEventListener('resize', cancalDebounce);
})

function initGrophSize() {
  chartHeight.value = `${window.innerHeight - 200}px`
  chartWidth.value = completeList.value.length * 200 + 'px'
  console.log(chartHeight.value, chartWidth.value)
  echartInstance.value.resize()
}

function handleEdit() {
  disabled.value = !disabled.value;
}

function handleCancel() {
  disabled.value = !disabled.value;
  getList();
}

function handleDel(row) {
  proxy.$modal
    .confirm("确认删除吗？")
    .then(function () {
      delCompletion(row.id).then(res => {
        if (res.code === 200) {
          getList()
        }
      })
    })
}

function handleSave(row) {
  // console.log(number.value);
  if (row.id != null) {
    updateCompletion(row).then(res => {
      if (res.code === 200) {
        getList()
      }
    })
  } else {
    addCompletion(row).then(res => {
      if (res.code === 200) {
        getList()
      }
    })
  }
}
function sortDataByDateAsc(rawData) {
  return rawData.slice().sort((a, b) => new Date(a.date) - new Date(b.date));
}

function initChartData() {
  let months = completeList.value.map(e => e.year.concat('-', e.month, '-01'))
  months.sort((a, b) => new Date(a) - new Date(b))
  months = [...new Set(months)]
  let monthLabel = months.map(e => proxy.moment(e).format('YYYY年MM月'))
  let monthlyData = completeList.value.map(e => ({ month: proxy.moment(e.year.concat('-', e.month, '-01')).format('YYYY年MM月'), ratio: Number((e.actualNum / e.planNum).toFixed(2)) * 100, planNum: e.planNum, actualNum: e.actualNum }))
  let toData = []
  monthLabel.forEach(e => {
    // console.log(e)
    // console.log(monthlyData)
    toData.push(monthlyData.find(t => t.month == e) != null ? monthlyData.find(t => t.month == e).ratio : 0)
  })
  updateCompleteChart(monthlyData, monthLabel, toData)
}
function updateChart(monthlyData, displayMonths, selectedYear, currentYear) {
  echartInstance.value.setOption({
    title: { text: '工艺图纸电子化率' },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function (params) {
        const param = params[0];
        const monthIndex = param.dataIndex;
        const month = displayMonths[monthIndex];
        let requiredDocumentsThisMonth = 0;
        var uploadedProducts = 0;
        const sortedData = sortDataByDateAsc(rawData.value);
        if (selectedYear < 2024) {
          requiredDocumentsThisMonth = 0
        } else if (sortedData[(monthIndex - 2)]) {

          requiredDocumentsThisMonth = sortedData[(monthIndex - 2)].number;
        } else if ((selectedYear > 2023 || (selectedYear === 2024 && monthIndex >= 2)) && !sortedData[monthIndex]) {
          requiredDocumentsThisMonth = 100; // 2024年3月及以后默认值为100
        }

        if (selectedYear < 2024) {
          uploadedProducts = 0
        } else if (selectedYear === 2024 && monthIndex == 2) {
          uploadedProducts = 78
        } else if (selectedYear === 2024 && monthIndex == 3) {
          uploadedProducts = 82
        } else if (selectedYear === 2024 && monthIndex == 4) {
          uploadedProducts = 85
        } else if (selectedYear === 2024 && monthIndex == 5) {
          uploadedProducts = 81
        } else if (selectedYear <= 2024 && monthIndex <= 1) {
          uploadedProducts = 0
        }
        else {
          uploadedProducts = procuctDrawing.value;
        }

        if (requiredDocumentsThisMonth > 0) {
          var rate = (uploadedProducts / requiredDocumentsThisMonth * 100).toFixed(2)
        } else {
          var rate = 0
        }
        const mes1 = conversion_mes.value[0].label;
        const mes2 = conversion_mes.value[1].label;
        return `
                ${month}:<br/>
                ${mes1}${requiredDocumentsThisMonth}，<br/>
                ${mes2}${uploadedProducts}，<br/>
                电子化率：${rate}%
                `;
      }
    },
    xAxis: {
      type: 'category',
      data: displayMonths
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      name: '电子化率',
      type: 'line',
      data: monthlyData
    }]
  });
}

function updateCompleteChart(monthlyData, displayMonths, yData) {
  console.log(monthlyData)
  echartInstance.value.setOption({
    title: { text: '工艺完成率' },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function (params) {
        console.log(params)
        const data = monthlyData.find(e => e.month == params[0].axisValue)
        return `${params[0].axisValue}:<br/>
                本月工艺计划完成量${data.planNum}，<br/>
                本月工艺实际完成量${data.actualNum}，<br/>
                工艺完成率：${data.ratio}%`
      }
    },

    xAxis: {
      type: 'category',
      data: displayMonths
    },
    yAxis: {
      type: 'value'
    },
    dataset: {
      // 用 dimensions 指定了维度的顺序。直角坐标系中，如果 X 轴 type 为 category，
      // 默认把第一个维度映射到 X 轴上，后面维度映射到 Y 轴上。
      // 如果不指定 dimensions，也可以通过指定 series.encode
      // 完成映射，参见后文。
      dimensions: ['month', 'ratio'],
      source: monthlyData
    },
    series: [{
      name: '工艺完成率',
      type: 'line',
      data: yData
    }]
  });
}
function initChart() {
  echartInstance.value = markRaw(echarts.init(echartDom.value));
  updateChart([], months.value); // 使用空数据初始化图表
}

function handleQuery() {
  getList();
}

function handleYearChange(year) {
  const currentYear = new Date().getFullYear();
  if (parseInt(year) > currentYear) {
    queryParams.value.year = currentYear.toString();
  } else {
    queryParams.value.year = year;
  }
  getList();
}

function resetQuery() {
  queryParams.value.year = new Date().getFullYear().toString();
  getList();
}
function sortDataByDateDesc(rawData) {
  return rawData.slice().sort((a, b) => new Date(b.date) - new Date(a.date));
}
function getList() {
  // 解构 queryParams 和 currentMonthIndex 为局部变量
  // const { queryParams } = toRefs(data);
  // const currentMonthIndex = computed(() => new Date().getMonth());

  // // 获取当前选择的年份和当前年份
  // const selectedYear = parseInt(queryParams.value.year);
  // const currentYear = new Date().getFullYear();

  // listCompletion(selectedYear).then(res => {

  //   rawData.value = sortDataByDateDesc(res.data);
  //   console.log(rawData.value)
  //   number.value = rawData.value[0].number;
  //   getProcuctDrawing().then(res => {
  //     procuctDrawing.value = res.data;
  //     // 处理图表数据
  //     const monthlyData = processChartData(rawData.value, selectedYear);
  //     const displayMonths = selectedYear === currentYear ?
  //       months.value.slice(0, currentMonthIndex.value + 1) :
  //       months.value;

  //     // 将selectedYear和currentYear传递给updateChart
  //     updateChart(monthlyData, displayMonths, selectedYear, currentYear);
  //   });
  // });
  listCompletion({}).then(res => {
    if (res.code === 200) {
      completeList.value = res.rows.map(v => ({ ...v, editStatus: false, yearMonth: v.year + '-' + v.month + '-01' }))

      rawData.value = sortDataByDateDesc(res.rows);
      number.value = rawData.value[0].number;
      initGrophSize()
      initChartData();
      // updateCompleteChart(monthlyData, displayMonths, selectedYear, currentYear);
    }
  })
}

function handleTabClick(arg) {
  console.log(arg)
}


function handleAdd() {
  completeList.value.push({ editStatus: true })
}

function handleRowYearMonthChange(arg, row) {
  console.log(row, arg)
  row.year = proxy.moment(arg).format('YYYY')
  row.month = proxy.moment(arg).format('MM')
}

onMounted(() => {
  initChart();
  getList();
});
</script>
<style lang="scss">
.demo-tabs {
  height: 100%;
  display: flex;
  flex-direction: column;

  .el-tabs__content {
    height: 100%;

    #pane-first {
      height: 100%;
    }

    #pane-second {
      height: 100%;
      position: relative;
    }
  }
}
</style>