<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="6">
        <el-card>
          <el-input v-model="planQueryParams.planName" placeholder="计划名称" clearable @change="handlePlanQuery"
            style="width: 100%;" />

          <el-tree v-loading="planLoading" :data="planTreeData" :props="planTreeProps" @node-click="handlePlanSelect"
            default-expand-all style="margin-top: 10px; height: 550px; overflow: auto;">
            <template slot-scope="{ node, data }">
              <span class="plan-node">
                <span class="plan-name">{{ data.planName }}</span>
              </span>
            </template>
          </el-tree>
          <pagination v-show="planTotal > 0" :total="planTotal" :page.sync="planQueryParams.pageNum"
            :limit.sync="planQueryParams.pageSize" @pagination="getPlanList" style="margin-top: 10px;"
            layout="total, prev, jumper, next" />
        </el-card>
      </el-col>

      <el-col :span="18">
        <el-card>
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="68px">
            <el-form-item label="收货单名称" prop="waybillName">
              <el-input v-model="queryParams.waybillName" placeholder="请输入收货单名称" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="收货单位" prop="consigneeUnit">
              <el-input v-model="queryParams.consigneeUnit" placeholder="请输入收货单位" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              <el-button type="success" plain icon="el-icon-refresh" size="mini" @click="handleQuery">刷新</el-button>
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                :disabled="!selectedPlan" title="导入收货计划">导入</el-button>
              <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
            </el-form-item>
          </el-form>

          <el-table v-loading="loading" border :data="deliveryWaybillList" highlight-current-row>
            <el-table-column label="钢卷号" align="center" prop="currentCoilNo" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-tag type="info" size="small">{{ scope.row.currentCoilNo }}</el-tag>
              </template>
            </el-table-column>

            <el-table-column label="优先级" align="center" prop="priority">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.priority === 0" type="info" size="mini">普通</el-tag>
                <el-tag v-else-if="scope.row.priority === 1" type="warning" size="mini">重要</el-tag>
                <el-tag v-else-if="scope.row.priority === 2" type="danger" size="mini">紧急</el-tag>
              </template>
            </el-table-column>

            <el-table-column label="来源" align="center" prop="sourceType">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.sourceType === 'scan'" type="success" size="mini">
                  <i class="el-icon-mobile"></i> 扫码
                </el-tag>
                <el-tag v-else type="info" size="mini">
                  <i class="el-icon-edit-outline"></i> 手动
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column label="新增时间" align="center" prop="createTime" width="155" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
              </template>
            </el-table-column>

            <el-table-column label="创建人" align="center" prop="createBy" width="100" />
            <el-table-column label="操作状态" align="center" prop="actionStatus" width="120">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.actionStatus === 2" type="success">已收货</el-tag>
                <el-tag v-else type="primary">未收货</el-tag>
              </template>
            </el-table-column>
            <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit"
                  @click.stop="handleUpdate(scope.row)">修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete"
                  @click.stop="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column> -->
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-card>
      </el-col>
    </el-row>
    

    <!-- 先做导入功能，通过一个钢卷的excel文件导入, 全屏弹窗 -->
    <el-dialog title="导入收货计划" :visible.sync="importDialogVisible" width="80%" >
      <ImportGuide />
    </el-dialog>
  </div>
</template>

<script>
import { listDeliveryPlan } from "@/api/wms/deliveryPlan"; // 导入收货计划API
import { listPendingAction } from '@/api/wms/pendingAction';
import MemoInput from "@/components/MemoInput";
import ImportGuide from "@/views/wms/receive/components/ImportGuide.vue";

export default {
  name: "DeliveryWaybill",
  components: {
    MemoInput,
    ImportGuide
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 收货单表格数据
      deliveryWaybillList: [],
      waybillId: null,
      // 打印相关数据
      printDialogVisible: false,
      currentWaybill: {},
      currentWaybillDetails: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        waybillNo: undefined,
        waybillName: undefined,
        licensePlate: undefined,
        consigneeUnit: undefined,
        senderUnit: undefined,
        deliveryTime: undefined,
        weighbridge: undefined,
        salesPerson: undefined,
        principal: undefined,
        principalPhone: undefined,
        status: undefined,
        planId: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 收货计划相关数据
      planList: [],
      planTreeData: [],
      planTreeProps: {
        label: 'planName',
        children: 'children'
      },
      planTotal: 0,
      planLoading: false,
      selectedPlan: null,
      planQueryParams: {
        pageNum: 1,
        pageSize: 100, // 增大分页大小以确保树形结构显示足够数据
        planName: undefined,
        planType: 1,
      },

      // 导入弹窗
      importDialogVisible: false,
    };
  },
  created() {
    this.getList();
    this.getPlanList();
  },
  methods: {
    /** 查询收货单列表 */
    getList() {
      this.loading = true;
      // 确保查询参数包含planId
      const params = {
        ...this.queryParams,
        actionType: 401, // 401表示钢卷入库
        // 如果选中了计划，将计划作为查询条件，虽然字段名交warehouseId，但实际存储的是计划Id
        warehouseId: this.selectedPlan ? this.selectedPlan.planId : undefined
      };
      listPendingAction(params).then(response => {
        this.deliveryWaybillList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        waybillId: undefined,
        waybillNo: new Date().getTime(),
        waybillName: undefined,
        planId: undefined,
        licensePlate: undefined,
        consigneeUnit: undefined,
        senderUnit: '科伦普',
        deliveryTime: undefined,
        weighbridge: undefined,
        salesPerson: undefined,
        principal: undefined,
        principalPhone: undefined,
        status: undefined,
        remark: undefined,
        delFlag: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 重置查询时保留planId
      if (this.selectedPlan) {
        this.queryParams.planId = this.selectedPlan.planId;
      }
      this.handleQuery();
    },
    // 获取收货计划列表
    getPlanList() {
      this.planLoading = true;
      listDeliveryPlan(this.planQueryParams).then(response => {
        this.planList = response.rows;
        this.planTotal = response.total;
        // 转换为树形数据格式
        this.planTreeData = response.rows;
        this.planLoading = false;
      });
    },

    // 收货计划搜索
    handlePlanQuery() {
      this.planQueryParams.pageNum = 1;
      this.getPlanList();
    },
    // 收货计划重置
    resetPlanQuery() {
      this.planQueryParams.planName = undefined;
      this.handlePlanQuery();
    },
    handlePlanSelect(row) {
      this.selectedPlan = row;
      // 更新查询参数，根据选中的planId筛选收货单
      this.queryParams.planId = row.planId;
      this.waybillId = null;
      this.getList();
    },
    handleRowClick(row) {
      this.waybillId = row.waybillId;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.importDialogVisible = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const waybillId = row.waybillId || this.ids
      getDeliveryWaybill(waybillId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改收货单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.waybillId != null) {
            updateDeliveryWaybill(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addDeliveryWaybill(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const waybillIds = row.waybillId || this.ids;
      this.$modal.confirm('是否确认删除收货单编号为"' + waybillIds + '"的数据项？').then(() => {
        this.loading = true;
        return delDeliveryWaybill(waybillIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wms/deliveryWaybill/export', {
        ...this.queryParams
      }, `deliveryWaybill_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>

<style scoped>
.plan-container {
  padding: 10px;
  height: 100%;
  border-right: 1px solid #ebeef5;
}

.plan-container h3 {
  margin: 0 0 10px 0;
  padding: 0;
  font-size: 16px;
  font-weight: 500;
}
</style>
