<template>
  <div class="JNPF-common-layout pro-order-data">
    <div class="JNPF-common-layout-center">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="6">
            <el-form-item label="订单日期">
              <el-date-picker
                v-model="query.proDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品名称">
              <el-input v-model="query.materialName" placeholder="请输入产品名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="规格型号">
              <el-input v-model="query.spec" placeholder="请输入规格型号" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">  
            <el-form-item label="订单状态">
              <JnpfSelect v-model="query.planStatus" placeholder="请选择订单状态" clearable :options="planStatusOptions"
                          :props="planStatusProps">
              </JnpfSelect>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item class="btn">
              <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
              <el-button type="primary"  @click="completeHandle()" width="90px">订单完成</el-button>
              <el-button type="primary"  @click="closeHandle()" width="90px">订单关闭</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="JNPF-common-layout-main" style="flex: 1; overflow: visible;">
        <!-- <div class="JNPF-common-head">
          <div>
            <el-button type="primary" icon="icon-ym icon-ym-btn-add" @click="generateHandle()">生成生产订单</el-button>
          </div>
          <div class="JNPF-common-head-right"></div>
        </div> -->
        <div style="overflow-x: auto; min-height: 400px;">
          <JNPF-table
            v-loading="listLoading"
            :data="list"
            :hasNO="false"
            border
            ref="table"
            :row-key="row => row.id"
            @selection-change="handleSelectionChange"
            :index="false"
            @row-click="handleRowClick"
            :highlight-current-row="true">
          <el-table-column type="index" label="序号" align="center" width="60" fixed="left"/>
          <el-table-column type="selection" align="center" :reserve-selection="true" fixed="left"/>
          <el-table-column prop="proNo" label="生产订单号" align="center" min-width="140" fixed="left"/>
          <el-table-column prop="materialName" label="产品名称" align="center" min-width="150"/>
          <el-table-column prop="spec" label="规格型号" align="center" min-width="120"/>
          <el-table-column prop="unit" label="单位" align="center" min-width="80">
             <template slot-scope="scope">
              {{ scope.row.unit == '1' ? 'kg' : scope.row.unit == '2' ? 'T' : scope.row.unit }}
            </template>
          </el-table-column>
          <el-table-column prop="planQty" label="订单数量" align="center" min-width="100">
            <template slot-scope="scope">
              {{ scope.row.planQty || 0 }}
            </template>
          </el-table-column>
          <el-table-column prop="completeQty" label="完成数量" align="center" min-width="100">
            <template slot-scope="scope">
              {{ scope.row.completeQty || 0 }}
            </template>
          </el-table-column>
          <el-table-column prop="storeInQty" label="入库数量" align="center" min-width="100">
            <template slot-scope="scope">
              {{ scope.row.storeInQty || 0 }}
            </template>
          </el-table-column>
          <el-table-column prop="planBgDate" label="计划开始日期" align="center" min-width="110" :formatter="jnpf.tableDateFormat1"/>
          <el-table-column prop="planEndDate" label="计划完成日期" align="center" min-width="110" :formatter="jnpf.tableDateFormat1"/>
          <el-table-column prop="processFlow" label="工艺流程" align="center" min-width="100"/>
          <el-table-column prop="planEmpName" label="编制人员" align="center" min-width="100"/>
          <el-table-column prop="planStatus" label="订单状态" align="center" min-width="100" fixed="right">
            <template slot-scope="scope">
              <el-tag :type="getPlanStatusType(scope.row.planStatus)" size="small">
                {{ getPlanStatusLabel(scope.row.planStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" align="center" width="180">
            <template slot-scope="scope">
              <el-button type="text" @click="detailHandle(scope.row)">详情</el-button>
              <el-button type="text" @click="deleteHandle(scope.row)">删除</el-button>
              <!-- <el-button type="text" @click="closeHandle(scope.row)" v-if="canClose(scope.row)">关闭</el-button> -->
            </template>
          </el-table-column>
        </JNPF-table>
        </div>
        <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize"
                    @pagination="initData"/>
        
        <div style="margin-top: 20px;">
          <el-row :gutter="20">
            <el-col :span="12">
              <div style="border: 1px solid #ebeef5; border-radius: 4px; padding: 10px;">
                <div style="margin-bottom: 10px; font-weight: bold;">关联销售订单</div>
                <JNPF-table
                  :data="orderList"
                  border>
                  <el-table-column prop="saleOrdNo" label="销售订单编号" align="center" min-width="120"/>
                  <el-table-column prop="custName" label="客户名称" align="center" min-width="120"/>
                  <el-table-column prop="materialName" label="产品名称" align="center" min-width="120"/>
                  <el-table-column prop="spec" label="规格型号" align="center" min-width="100"/>
                  <el-table-column prop="changProQty" label="转生产数量" align="center" min-width="100">
                    <template slot-scope="scope">
                      {{ scope.row.changProQty || 0 }}
                    </template>
                  </el-table-column>
                </JNPF-table>
              </div>
            </el-col>
            <el-col :span="12">
              <div style="border: 1px solid #ebeef5; border-radius: 4px; padding: 10px;">
                <div style="margin-bottom: 10px; font-weight: bold;">产线订单信息</div>
                <JNPF-table
                  :data="lineList"
                  border>
                  <el-table-column prop="lineCd" label="产线编码" align="center" min-width="100"/>
                  <!-- <el-table-column prop="lineName" label="产线名称" align="center" min-width="120"/> -->
                  <el-table-column prop="proBgDate" label="开工时间" align="center" min-width="110" :formatter="jnpf.tableDateFormat1"/>
                  <el-table-column prop="proEndDate" label="完工时间" align="center" min-width="110" :formatter="jnpf.tableDateFormat1"/>
                  <el-table-column prop="planQty" label="计划数量" align="center" min-width="100"/>
                  <el-table-column prop="completeQty" label="完成数量" align="center" min-width="100">
                    <template slot-scope="scope">
                      {{ scope.row.completeQty || 0 }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="planStatus" label="计划状态" align="center" min-width="100">
                    <template slot-scope="scope">
                      <el-tag :type="getPlanStatusType(scope.row.planStatus)" size="small">
                        {{ getPlanStatusLabel(scope.row.planStatus) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" fixed="right" align="center" width="180">
                    <template slot-scope="scope">
                      <el-button type="text" @click="detailHandle(scope.row)">详情</el-button>
                    </template>
                  </el-table-column>
                </JNPF-table>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
    <GenerateForm v-if="generateVisible" ref="GenerateForm" @refresh="refresh"/>
    <Detail v-if="detailVisible" ref="Detail" @close="detailVisible = false"/>
  </div>
</template>

<script>
import {getProOrderList, deleteProOrder, getProOrderInfo} from "./api";
import GenerateForm from "./generateForm";
import Detail from "./detail";
import jnpf from "@/utils/jnpf";

export default {
  name: "proorder",
  components: {
    GenerateForm,
    Detail
  },
  data() {
    return {
      query: {
        proNo: undefined,
        materialCode: undefined,
        materialName: undefined,
        planStatus: undefined,
        planBgDateRange: undefined,
        planEndDateRange: undefined
      },
      list: [],
      listLoading: false,
      total: 0,
      hasSelected: false,
      selectedRowId: null,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: "",
        sidx: ""
      },
      generateVisible: false,
      detailVisible: false,
      planStatusOptions: [
        { fullName: "未下发", id: "0" },
        { fullName: "已下发", id: "1" },
        { fullName: "执行中", id: "2" },
        { fullName: "已完成", id: "3" },
        { fullName: "暂停", id: "4" },
        { fullName: "关闭", id: "5" }
      ],
      planStatusProps: { label: "fullName", value: "id" },
      // 关联销售订单列表
      orderList: [],
      // 产线订单列表
      lineList: []
    };
  },
  computed: {
    jnpf() {
      return jnpf;
    }
  },
  created() {
    this.initDefaultDate();
    this.initData();
  },
  methods: {
    initDefaultDate() {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth();
      const day = now.getDate();
      const firstDayStr = `${year}-${String(month + 1).padStart(2, '0')}-01`;
      const lastDayStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
      this.query.proDateRange = [firstDayStr, lastDayStr];
    },
    handleSelectionChange(val) {
      this.hasSelected = val.length > 0;
    },
    handleRowClick(row) {
      this.selectedRowId = row.id;
      this.loadDetailData(row.id);
    },
    initData() {
      this.listLoading = true;
      let _query = {
        ...this.listQuery,
        ...this.query,
        dataType: 0
      };

      if (this.query.planBgDateRange && this.query.planBgDateRange.length === 2) {
        _query.planBgDateStart = this.query.planBgDateRange[0];
        _query.planBgDateEnd = this.query.planBgDateRange[1];
      }

      if (this.query.planEndDateRange && this.query.planEndDateRange.length === 2) {
        _query.planEndDateStart = this.query.planEndDateRange[0];
        _query.planEndDateEnd = this.query.planEndDateRange[1];
      }

      Object.keys(_query).forEach(key => {
        if (_query[key] === undefined || _query[key] === null || _query[key] === '') {
          if (key !== 'dataType') {
            delete _query[key];
          }
        }
      });

      getProOrderList(_query).then((res) => {
        this.list = res.data.list || [];
        this.total = res.data.pagination.total;
        this.listLoading = false;
        // 查询后默认选中第一条数据并加载详情
        if (this.list.length > 0) {
          this.selectedRowId = this.list[0].id;
          this.loadDetailData(this.list[0].id);
        } else {
          this.selectedRowId = null;
          this.orderList = [];
          this.lineList = [];
        }
      }).catch(() => {
        this.listLoading = false;
      });
    },
    loadDetailData(proOrderId) {
      // 加载销售订单和产线订单信息
      getProOrderInfo(proOrderId).then((res) => {
        const data = res.data || {};
        this.orderList = data.orderList || [];
        this.lineList = data.lineList || [];
      }).catch(() => {
        this.orderList = [];
        this.lineList = [];
      });
    },

    search() {
      this.listQuery.currentPage = 1;
      this.initData();
    },
    reset() {
      this.query = {
        proNo: undefined,
        materialCode: undefined,
        materialName: undefined,
        planStatus: undefined,
        planBgDateRange: undefined,
        planEndDateRange: undefined
      };
      this.initDefaultDate();
      this.search();
    },
    generateHandle() {
      this.generateVisible = true;
      this.$nextTick(() => {
        this.$refs.GenerateForm.init();
      });
    },
    detailHandle(row) {
      this.detailVisible = true;
      this.$nextTick(() => {
        this.$refs.Detail.init(row.id);
      });
    },
    closeHandle(row) {
      this.$confirm('此操作将关闭该生产订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用关闭接口
        this.$message.success('关闭成功');
        this.initData();
      }).catch(() => {
      });
    },
    deleteHandle(row) {
      this.$confirm('此操作将永久删除该生产订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteProOrder(row.id).then(() => {
          this.$message.success('删除成功');
          this.initData();
        }).catch((err) => {
          const msg = err?.response?.data?.message || err?.message || '删除失败';
          this.$message.error(msg);
        });
      }).catch(() => {
      });
    },
    refresh() {
      this.initData();
    },
    lineDetailHandle(row) {
      this.detailVisible = true;
      this.$nextTick(() => {
        this.$refs.Detail.init(row.proId || row.id);
      });
    },
    getPlanStatusLabel(value) {
      const statusMap = {
        '0': '未下发',
        '1': '已下发',
        '2': '执行中',
        '3': '已完成',
        '4': '暂停',
        '5': '关闭'
      };
      return statusMap[value] || value;
    },
    getPlanStatusType(value) {
      const typeMap = {
        '0': 'info',
        '1': '',
        '2': 'primary',
        '3': 'success',
        '4': 'warning',
        '5': 'danger'
      };
      return typeMap[value] || '';
    },
    canClose(row) {
      return row.planStatus !== '3' && row.planStatus !== '5';
    }
  }
};
</script>

<style scoped>
</style>
