<template>
  <div class="app-container" v-loading="loading">
    <el-row>
      <el-form label-width="80px" inline>
        <el-form-item label="开始日期">
          <el-date-picker style="width: 200px;" v-model="queryParams.byCreateTimeStart" type="date"
            value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker style="width: 200px;" v-model="queryParams.byCreateTimeEnd" type="date"
            value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="班组">
          <el-select v-model="queryParams.team" placeholder="请选择班组" style="width: 200px;">
            <el-option label="甲" value="甲" />
            <el-option label="乙" value="乙" />
          </el-select>
        </el-form-item>
        <el-form-item label="入场钢卷号">
          <el-input style="width: 200px;" v-model="queryParams.enterCoilNo" placeholder="请输入入场钢卷号" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="当前钢卷号">
          <el-input style="width: 200px;" v-model="queryParams.currentCoilNo" placeholder="请输入当前钢卷号" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="逻辑库位">
          <el-select v-model="warehouseIds" collapse-tags multiple placeholder="请选择逻辑库位" style="width: 200px;">
            <el-option v-for="item in warehouseOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称">
          <el-input style="width: 200px;" v-model="queryParams.itemName" placeholder="请输入产品名称" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="规格">
          <memo-input style="width: 200px;" v-model="queryParams.itemSpecification" storageKey="coilSpec"
            placeholder="请选择规格" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="材质">
          <dict-select style="width: 200px;" v-model="queryParams.itemMaterial" dict-type="coil_material"
            placeholder="请选择材质" clearable @keyup.enter.native="handleQuery" multiple />
        </el-form-item>
        <el-form-item label="厂家">
          <dict-select style="width: 200px;" v-model="queryParams.itemManufacturer" dict-type="coil_manufacturer" 
            placeholder="请选择厂家" clearable @keyup.enter.native="handleQuery" multiple />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="primary" @click="exportData">导出产出钢卷</el-button>
          <el-button type="primary" @click="exportLossData">导出消耗钢卷</el-button>
          <el-button type="primary" @click="settingVisible = true">列设置</el-button>
          <el-button type="primary" @click="saveOutputReport">保存产出报表</el-button>
          <el-button type="primary" @click="saveLossReport">保存消耗报表</el-button>
        </el-form-item>
      </el-form>
    </el-row>

     <el-descriptions title="统计信息" :column="3" border>
      <el-descriptions-item label="产出数量">{{ summary.outCount }}</el-descriptions-item>
      <el-descriptions-item label="产出总重">{{ summary.outTotalWeight }}t</el-descriptions-item>
      <el-descriptions-item label="产出均重">{{ summary.outAvgWeight }}t</el-descriptions-item>

      <el-descriptions-item label="消耗数量">{{ summary.lossCount }}</el-descriptions-item>
      <el-descriptions-item label="消耗总重">{{ summary.lossTotalWeight }}t</el-descriptions-item>
      <el-descriptions-item label="消耗均重">{{ summary.lossAvgWeight }}t</el-descriptions-item>

      <el-descriptions-item label="数量差值">{{ summary.countDiff }}</el-descriptions-item>
      <el-descriptions-item label="总重差值">{{ summary.weightDiff }}</el-descriptions-item>
      <el-descriptions-item label="均重差值">{{ summary.avgWeightDiff }}t</el-descriptions-item>
      <!-- <el-descriptions-item label="合计均重">{{ summary.totalAvgWeight }}t</el-descriptions-item> -->

      <!-- 成品率 -->
      <el-descriptions-item label="成品率">{{ summary.passRate }}</el-descriptions-item>
      <el-descriptions-item label="损耗率">{{ summary.lossRate }}</el-descriptions-item>
      <!-- 异常率 -->
      <el-descriptions-item label="异常率">{{ summary.abRate }}</el-descriptions-item>
      <!-- 正品率 -->
      <el-descriptions-item label="正品率">{{ summary.passRate2 }}</el-descriptions-item>
    </el-descriptions>

   <!-- 已处理M统计信息 -->
    <el-descriptions title="已处理M统计信息" :column="3" border>
      <el-descriptions-item label="产出数量">{{ mSummary.outCount }}</el-descriptions-item>
      <el-descriptions-item label="产出总重">{{ mSummary.outTotalWeight }}t</el-descriptions-item>
      <el-descriptions-item label="产出均重">{{ mSummary.outAvgWeight }}t</el-descriptions-item>

      <el-descriptions-item label="消耗数量">{{ mSummary.lossCount }}</el-descriptions-item>
      <el-descriptions-item label="消耗总重">{{ mSummary.lossTotalWeight }}t</el-descriptions-item>
      <el-descriptions-item label="消耗均重">{{ mSummary.lossAvgWeight }}t</el-descriptions-item>

      <el-descriptions-item label="数量差值">{{ mSummary.countDiff }}</el-descriptions-item>
      <el-descriptions-item label="总重差值">{{ mSummary.weightDiff }}</el-descriptions-item>
      <el-descriptions-item label="均重差值">{{ mSummary.avgWeightDiff }}t</el-descriptions-item>
      <!-- 成品率 -->
      <el-descriptions-item label="成品率">{{ mSummary.passRate }}</el-descriptions-item>
      <el-descriptions-item label="损耗率">{{ mSummary.lossRate }}</el-descriptions-item>
      <!-- 异常率 -->
      <el-descriptions-item label="异常率">{{ mSummary.abRate }}</el-descriptions-item>
      <!-- 正品率 -->
      <el-descriptions-item label="正品率">{{ mSummary.passRate2 }}</el-descriptions-item>
    </el-descriptions>

    <el-descriptions title="异常统计" :column="4" border>
      <el-descriptions-item v-for="item in abSummary" :key="item.label" :label="item.label">{{ item.value
        }}</el-descriptions-item>
    </el-descriptions>

    <el-descriptions title="班组统计信息" :column="3" border>
    </el-descriptions>
    <el-table :data="teamSummary" border>
      <el-table-column label="班组" align="center" prop="team" />
      <el-table-column label="产出数量" align="center" prop="outCount" />
      <el-table-column label="产出总重" align="center" prop="outWeight" />
    </el-table>

    <el-descriptions title="明细信息" :column="3" border>
    </el-descriptions>
    <el-tabs v-model="activeTab">
      <el-tab-pane label="产出钢卷" name="output">
        <coil-table :columns="outputColumns" :data="list"></coil-table>
      </el-tab-pane>
      <el-tab-pane label="投入钢卷" name="loss">
        <coil-table :columns="lossColumns" :data="lossList"></coil-table>
      </el-tab-pane>
    </el-tabs>

    <el-dialog title="列设置" :visible.sync="settingVisible" width="50%">
      <el-radio-group v-model="activeColumnConfig">
        <el-radio-button label="coil-report-loss">投入明细配置</el-radio-button>
        <el-radio-button label="coil-report-output">产出明细配置</el-radio-button>
      </el-radio-group>
      <columns-setting :reportType="activeColumnConfig"></columns-setting>
    </el-dialog>
  </div>
</template>

<script>
import ProductInfo from "@/components/KLPService/Renderer/ProductInfo";
import RawMaterialInfo from "@/components/KLPService/Renderer/RawMaterialInfo";
import CoilNo from "@/components/KLPService/Renderer/CoilNo.vue";
import MemoInput from "@/components/MemoInput";
import MutiSelect from "@/components/MutiSelect";
import WarehouseSelect from "@/components/KLPService/WarehouseSelect";
import { calcSummary, calcAbSummary, calcTeamSummary, calcMSummary } from "@/views/wms/report/js/calc";
import ColumnsSetting from "@/views/wms/report/components/setting/columns.vue";
import CoilTable from "@/views/wms/report/components/coilTable/index.vue";
import { fetchLossList, fetchOutputList } from "@/views/wms/report/js/fetch";
import { saveReportFile } from "@/views/wms/report/js/reportFile";

export default {
  name: 'TeamTemplate',
  components: {
    ProductInfo,
    RawMaterialInfo,
    CoilNo,
    MemoInput,
    MutiSelect,
    WarehouseSelect,
    ColumnsSetting,
    CoilTable,
  },
  props: {
    actionTypes: {
      type: Array,
      default: () => []
    },
    actionQueryParams: {
      type: Object,
      default: () => { }
    },
    baseQueryParams: {
      type: Object,
      default: () => { }
    },
    warehouseOptions: {
      type: Array,
      default: () => []
    },
    productionLine: {
      type: String,
      default: '',
    },
  },
  dicts: ['product_coil_status', 'coil_material', 'coil_itemname', 'coil_manufacturer'],
  data() {
    const addZero = (num) => num.toString().padStart(2, '0');
    const now = new Date();
    const currentDate = `${now.getFullYear()}-${addZero(now.getMonth() + 1)}-${addZero(now.getDate())}`;

    const getDayTimeRange = (dateStr) => {
      return {
        start: `${dateStr} 00:00:00`,
        end: `${dateStr} 23:59:59`
      };
    };

    const { start, end } = getDayTimeRange(currentDate);

    return {
      activeTab: 'output',
      activeColumnConfig: 'coil-report-loss',
      settingVisible: false,
      list: [],
      lossList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 9999,
        date: currentDate,
        byCreateTimeStart: start,
        byCreateTimeEnd: end,
        enterCoilNo: '',
        currentCoilNo: '',
        warehouseId: '',
        itemName: '',
        itemSpecification: '',
        itemMaterial: '',
        itemManufacturer: '',
        team: ''
      },
      loading: false,
      warehouseIds: [
        '1988150099140866050',
        '1988150263284953089',
        '1988150545175736322',
        '1988150150521090049',
        '2019583656787259393',
        '2019583325311414274',
        '2019583429955104769',
        '2019583137616310273'
      ],
      getDayTimeRange,

      lossColumns: [],
      outputColumns: [],

      actionIds: ''
    };
  },
  watch: {
    warehouseOptions: {
      handler(newVal) {
        if (newVal) {
          this.warehouseIds = newVal.map(item => item.value);
        }
      },
      immediate: true
    }
  },
  computed: {
    summary() {
      return calcSummary(this.list, this.lossList);
    },
    abSummary() {
      return calcAbSummary(this.list);
    },
    mSummary() {
      return calcMSummary(this.list, this.lossList);
    },
    teamSummary() {
      const teamOutSummary = calcTeamSummary(this.list);
      const allTeams = [...new Set(Object.keys(teamOutSummary))];

      return allTeams.map(team => {
        const outData = teamOutSummary[team] || { count: 0, weight: 0 };
        const formatWeight = function (weight) {
          return Number(weight || 0).toFixed(2);
        };

        return {
          team: team,
          outCount: outData.count,
          outWeight: formatWeight(outData.weight)
        };
      });
    }
  },
  methods: {
    // 加载列设置
    loadColumns() {
      this.lossColumns = JSON.parse(localStorage.getItem('preference-tableColumns-coil-report-loss') || '[]') || []
      this.outputColumns = JSON.parse(localStorage.getItem('preference-tableColumns-coil-report-output') || '[]') || []
    },
    // 统一查询入口（兼容回车和按钮点击）
    handleQuery() {
      this.loading = true
      Promise.all([
        fetchLossList(this.actionTypes, {
          ...this.queryParams,
          ...this.actionQueryParams
        }, (ids) => { this.actionIds = ids }),
        fetchOutputList({
          ...this.queryParams,
          ...this.baseQueryParams,
          warehouseIds: this.warehouseIds.join(','),
        }),
      ]).then(([lossList, outputList]) => {
        this.lossList = lossList
        this.list = outputList
        this.loading = false
      })
    },
    exportData() {
      if (this.list.length === 0) {
        this.$message.warning('暂无数据可导出');
        return;
      }
      this.download('wms/materialCoil/export', {
        coilIds: this.list.map(item => item.coilId).join(',')
      }, `materialCoil_${this.queryParams.date}_${new Date().getTime()}.xlsx`);
    },
    exportLossData() {
      if (this.lossList.length === 0) {
        this.$message.warning('暂无数据可导出');
        return;
      }
      this.download('wms/materialCoil/export', {
        // coilIds: this.lossList.map(item => item.coilId).join(',')
        actionIds: this.actionIds
      }, `materialCoil_${this.queryParams.date}_${new Date().getTime()}.xlsx`);
    },
    // 保存产出报表
    saveOutputReport() {
      this.loading = true
      saveReportFile(this.list.map(item => item.coilId).join(','), {
        reportParams: this.queryParams,
        reportType: '产出报表,班报表',
        productionLine: this.productionLine,
      }).then(res => {
        this.$message({
          message: '保存成功',
          type: 'success',
        })
      }).catch(err => {
        this.$message({
          message: '保存失败',
          type: 'error',
        })
      }).finally(() => {
        this.loading = false
      })
    },
    // 保存消耗报表
    saveLossReport() {
      this.loading = true
      saveReportFile(this.lossList.map(item => item.coilId).join(','), {
        reportParams: this.queryParams,
        reportType: '消耗报表,班报表',
        productionLine: this.productionLine,
      }).then(res => {
        this.$message({
          message: '保存成功',
          type: 'success',
        })
      }).catch(err => {
        this.$message({
          message: '保存失败',
          type: 'error',
        })
      }).finally(() => {
        this.loading = false
      })
    }
  },
  mounted() {
    this.handleQuery()
    this.loadColumns();
  }
};
</script>

<style scoped></style>