<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="调拨单号" prop="transferNo">
        <el-input
          v-model="queryParams.transferNo"
          placeholder="请输入调拨单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="调拨单名称" prop="transferName">
        <el-input
          v-model="queryParams.transferName"
          placeholder="请输入调拨单名称，用于帮助记忆与沟通"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="调拨时间" prop="transferTime">
        <el-date-picker clearable
          v-model="queryParams.transferTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择实际调拨时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="调拨类型" prop="transferType">
        <dict-select v-model="queryParams.transferType" dict-type="coil_move_type" placeholder="请选择调拨类型" clearable>
        </dict-select>
      </el-form-item>
      <el-form-item label="审批状态" prop="approveStatus">
        <el-select v-model="queryParams.approveStatus" placeholder="请选择审批状态" clearable>
          <el-option label="未申请" :value="'0'" />
          <el-option label="待审批" :value="'1'" />
          <el-option label="已通过" :value="'2'" />
          <el-option label="已驳回" :value="'3'" />
        </el-select>
      </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-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="transferOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="调拨单号" align="center" prop="transferNo" />
      <el-table-column label="调拨单名称" align="center" prop="transferName" />
      <!-- <el-table-column label="调拨状态" align="center" prop="transferStatus" /> -->
      <el-table-column label="调拨时间" align="center" prop="transferTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.transferTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调拨类型" align="center" prop="transferType" width="120"></el-table-column>
       <el-table-column label="审批状态" align="center" prop="approveStatus" width="120">
        <template slot-scope="scope">
          <el-tag :type="getapproveStatusType(scope.row.approveStatus)">
            {{ getapproveStatusText(scope.row.approveStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审批人" align="center" prop="approver" />
     
      <el-table-column label="审批时间" align="center" prop="approveTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.approveTime ? parseTime(scope.row.approveTime, '{y}-{m}-{d} {h}:{i}') : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <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-view"
            @click="handleView(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            :disabled="!canEdit(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            :disabled="!canDelete(scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            plain
            type="text"
            @click="handleSubmitapprove(scope.row)"
            v-if="(scope.row.approveStatus || '0') == '0'"
            icon="el-icon-check"
          >提交</el-button>
          <el-button
            size="mini"
            plain
            type="text"
            @click="handleWithdrawapprove(scope.row)"
            v-if="scope.row.approveStatus == '1'"
            icon="el-icon-refresh"
          >撤回</el-button>
          <el-button
            size="mini"
            type="text"
            plain
            @click="handleReSubmit(scope.row)"
            v-if="scope.row.approveStatus == '3' || scope.row.approveStatus == '2'"
            icon="el-icon-refresh"
          >重新提交</el-button>
          <el-button
            size="mini"
            type="text"
            v-hasPermi="['coil:move:approval']"
            @click="handleResolve(scope.row)"
            icon="el-icon-check"
            v-if="scope.row.approveStatus == '1'"
          >通过</el-button>
          <el-button
            size="mini"
            type="text"
            v-hasPermi="['coil:move:approval']"
            @click="handleReject(scope.row)"
            v-if="scope.row.approveStatus == '1'"
            icon="el-icon-close"
          >驳回</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-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="调拨单号" prop="transferNo">
          <el-input v-model="form.transferNo" placeholder="请输入调拨单号" />
        </el-form-item>
        <el-form-item label="调拨单名称" prop="transferName">
          <el-input v-model="form.transferName" placeholder="请输入调拨单名称，用于帮助记忆与沟通" />
        </el-form-item>
        <el-form-item label="调拨时间" prop="transferTime">
          <el-date-picker clearable
            v-model="form.transferTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择调拨时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="调拨类型" prop="transferType">
          <dict-select v-model="form.transferType" dict-type="coil_move_type" placeholder="请选择调拨类型" clearable>
          </dict-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="调拨单明细" v-loading="detailLoading" :visible.sync="detailOpen" fullscreen>
      <div style="margin-bottom: 10px; display: flex; align-items: center;">
        <el-button icon="el-icon-download" type="warning" plain @click="handleExportDetail">导出</el-button>
        <el-button style="margin-right: 10px;" icon="el-icon-refresh" type="success" plain @click="handleRefreshDetailList">刷新</el-button>
        <el-button :loading="buttonLoading" style="margin-right: 10px;" icon="el-icon-check" type="primary" plain @click="handleConfirmAll" v-if="currentOrderStatus == '2'">执行全部</el-button>
        <coil-selector v-loading="buttonLoading" ref="coilSelector" multiple @confirm="handleCoilChange" v-if="canAddCoils"></coil-selector>
      </div>
      <transfer-item-table ref="transferItemTable" :data="transferOrderItems" @refreshData="getDetailList" :orderStatus="currentOrderStatus" :canEdit="canAddCoils" />
    </el-dialog>
  </div>
</template>

<script>
import { listTransferOrder, getTransferOrder, delTransferOrder, addTransferOrder, updateTransferOrder, approveTransferOrder } from "@/api/wms/transferOrder";
import { listTransferOrderItem, batchAddTransferOrderItem } from "@/api/wms/transferOrderItem";
import CoilSelector from "@/components/CoilSelector";
import TransferItemTable from "@/views/wms/move/components/tranferItemTable.vue";

export default {
  name: "TransferOrder",
  components: {
    CoilSelector,
    TransferItemTable,
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 调拨单主表格数据
      transferOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        transferNo: undefined,
        transferName: undefined,
        transferStatus: undefined,
        transferTime: undefined,
        approveStatus: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderId: [
          { required: true, message: "调拨单主键ID不能为空", trigger: "blur" }
        ],
        transferNo: [
          { required: true, message: "调拨单号不能为空", trigger: "blur" }
        ],
        transferTime: [
          { required: true, message: "实际调拨时间不能为空", trigger: "blur" }
        ],
        // remark: [
        //   { required: true, message: "备注不能为空", trigger: "blur" }
        // ],
      },
      // 详情弹窗loading
      detailLoading: false,
      detailOpen: false,
      // 调拨单明细表格数据
      transferOrderItems: [],
      currentOrderId: undefined,
      // 是否可以添加钢卷
      canAddCoils: false,
      // 当前审批状态
      currentOrderStatus: undefined,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询调拨单主列表 */
    getList() {
      this.loading = true;
      listTransferOrder(this.queryParams).then(response => {
        this.transferOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleResolve(row) {
      approveTransferOrder(row.orderId, '2').then(response => {
        this.$modal.msgSuccess('审批成功');
        this.getList();
      }).finally(() => {
        this.loading = false;
      });
    },
    handleReject(row) {
      approveTransferOrder(row.orderId, '3').then(response => {
        this.$modal.msgSuccess('审批成功');
        this.getList();
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 获取审批状态文本 */
    getapproveStatusText(status) {
      // 如果没有状态字段，则视为未提交
      if (!status) {
        return '未申请';
      }
      const statusMap = {
        '0': '未申请',
        '1': '待审批',
        '2': '已通过',
        '3': '已驳回'
      };
      return statusMap[status] || '未申请';
    },
    /** 获取审批状态标签类型 */
    getapproveStatusType(status) {
      // 如果没有状态字段，则视为未提交
      if (!status) {
        return 'info';
      }
      const typeMap = {
        '0': 'info',
        '1': 'warning',
        '2': 'success',
        '3': 'danger'
      };
      return typeMap[status] || 'info';
    },
    /** 判断是否可以编辑 */
    canEdit(row) {
      // 如果没有状态字段，则视为未提交
      const status = row.approveStatus || '0';
      return status === '0' || status === '1' || status === '3';
    },
    /** 判断是否可以删除 */
    canDelete(row) {
      // 如果没有状态字段，则视为未提交
      const status = row.approveStatus || '0';
      return status === '0';
    },
    /** 提交审批 */
    handleSubmitapprove(row) {
      this.$confirm('确定要提交审批吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        updateTransferOrder({
          ...row,
          approveStatus: '1',
        }).then(response => {
          this.$modal.msgSuccess('提交审批成功');
          this.getList();
        }).finally(() => {
          this.loading = false;
        });
      });
    },
    /** 撤回审批 */
    handleWithdrawapprove(row) {
      this.$confirm('确定要撤回审批吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        updateTransferOrder({
          ...row,
          approveStatus: '0',
        }).then(response => {
          this.$modal.msgSuccess('撤回审批成功');
          this.getList();
        }).finally(() => {
          this.loading = false;
        });
      });
    },
    /** 重新提交 */
    handleReSubmit(row) {
      this.$confirm('确定要重新提交审批吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        this.loading = true;
        // 这里需要调用重新提交的API
        // 假设API为reSubmitapprove
        // reSubmitapprove(row.orderId).then(response => {
        //   this.$modal.msgSuccess('重新提交成功');
        //   this.getList();
        // }).finally(() => {
        //   this.loading = false;
        // });
        // 模拟API调用
        setTimeout(() => {
          this.loading = false;
          this.$modal.msgSuccess('重新提交成功');
          this.getList();
        }, 1000);
      });
    },
    /** 刷新调拨单明细列表 */
    handleRefreshDetailList() {
      this.getDetailList();
    },
    /** 导出调拨单明细 */
    handleExportDetail() {
      if (this.transferOrderItems.length === 0) {
        this.$message({ message: '没有数据可导出', type: 'warning' });
        return;
      }

      // 定义字段映射，英文字段名对应中文表头
      const fieldMap = {
        // Before相关字段
        'materialTypeBeforeName': '物料类型(调拨前)',
        'materialNameBefore': '物料名称(调拨前)',
        'specificationBefore': '规格(调拨前)',
        'materialBefore': '材质(调拨前)',
        'surfaceTreatmentBefore': '表面处理(调拨前)',
        'manufacturerBefore': '厂家(调拨前)',
        'zincLayerBefore': '镀层质量(调拨前)',
        'warehouseNameBefore': '逻辑库区(调拨前)',
        // After相关字段
        'materialTypeAfterName': '物料类型(调拨后)',
        'materialNameAfter': '物料名称(调拨后)',
        'specificationAfter': '规格(调拨后)',
        'materialAfter': '材质(调拨后)',
        'surfaceTreatmentAfter': '表面处理(调拨后)',
        'manufacturerAfter': '厂家(调拨后)',
        'zincLayerAfter': '镀层质量(调拨后)',
        'warehouseNameAfter': '逻辑库区(调拨后)',
        // Coil相关字段
        'coil_enterCoilNo': '入库卷号',
        'coil_currentCoilNo': '当前卷号',
        'coil_supplierCoilNo': '厂家卷号',
        // 'coil_warehouseName': '逻辑库区',
        'coil_netWeight': '净重',
        
        // 'coil_itemName': '物品名称',
        // 'coil_materialType': '物料类型',
        'coil_qualityStatus': '质量状态',
        'coil_trimmingRequirement': '切边要求',
        'coil_packingStatus': '原料材质',
        'coil_packagingRequirement': '包装要求',
        'coil_remark': '备注',
      };

      // 提取所有字段名
      const exportFields = Object.keys(fieldMap);

      // 准备导出数据
      const exportData = this.transferOrderItems.map(item => {
        const flatItem = {};
        
        // 处理Before和After字段
        exportFields.forEach(field => {
          if (field.startsWith('coil_')) {
            const coilField = field.replace('coil_', '');
            flatItem[field] = item.coil ? item.coil[coilField] : '';
          } else {
            flatItem[field] = item[field] !== null && item[field] !== undefined ? item[field] : '';
          }
        });
        
        return flatItem;
      });

      // 生成CSV头部（使用中文）
      const chineseHeaders = Object.values(fieldMap);
      const csvContent = [
        chineseHeaders.join(','), // 中文头部
        ...exportData.map(row => {
          return exportFields.map(field => {
            const value = row[field];
            // 处理包含逗号或引号的值
            if (typeof value === 'string' && (value.includes(',') || value.includes('"'))) {
              return `"${value.replace(/"/g, '""')}"`;
            }
            return value !== null && value !== undefined ? value : '';
          }).join(',');
        })
      ].join('\n');

      // 创建Blob对象
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      // 创建下载链接
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      link.setAttribute('href', url);
      link.setAttribute('download', `transferOrderDetail_${new Date().getTime()}.csv`);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }, 
    /** 钢卷选择器改变 */
    handleCoilChange(coils) {
      console.log(coils);
      this.buttonLoading = true;
      batchAddTransferOrderItem({
        transferId: this.currentOrderId,
        coilIds: coils.map(item => item.coilId)
      }).then(response => {
        this.$message({
          message: "添加成功",
          type: "success"
        });
        this.buttonLoading = false;
        this.handleView({ orderId: this.currentOrderId });
      }).catch(() => {
        this.buttonLoading = false;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
      reset() {
        this.form = {
          orderId: undefined,
          transferNo: undefined,
          transferName: undefined,
          transferStatus: undefined,
          transferTime: undefined,
          remark: undefined,
          delFlag: undefined,
          createBy: undefined,
          updateBy: undefined,
          createTime: undefined,
          updateTime: undefined,
          approveStatus: '0',
          approver: undefined,
          approveTime: undefined
        };
        this.resetForm("form");
      },
    getDetailList() {
      this.handleView({ orderId: this.currentOrderId, approveStatus: this.currentOrderStatus });
    },
    /** 查看按钮操作 */
    handleView(row) {
      // 查看调拨单明细
      this.detailLoading = true;
      this.detailOpen = true;
      this.currentOrderId = row.orderId;
      // 根据审批状态设置是否可以添加钢卷，如果没有状态字段，则视为未提交
      const status = row.approveStatus || '0';
      this.currentOrderStatus = status;
      this.canAddCoils = status === '0';
      listTransferOrderItem({ transferId: row.orderId }).then(response => {
        console.log(response.rows);
        this.transferOrderItems = response.rows;
        this.detailLoading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 生成当前时间
      const currentDate = new Date();
      // 生成调拨单号：TR + 年月日时分秒
      const transferNo = 'TR' + currentDate.getFullYear() + 
        String(currentDate.getMonth() + 1).padStart(2, '0') + 
        String(currentDate.getDate()).padStart(2, '0') + 
        String(currentDate.getHours()).padStart(2, '0') + 
        String(currentDate.getMinutes()).padStart(2, '0') + 
        String(currentDate.getSeconds()).padStart(2, '0');
      // 生成调拨时间：YYYY-MM-DD HH:mm:ss
      const transferTime = currentDate.getFullYear() + '-' + 
        String(currentDate.getMonth() + 1).padStart(2, '0') + '-' + 
        String(currentDate.getDate()).padStart(2, '0') + ' ' + 
        String(currentDate.getHours()).padStart(2, '0') + ':' + 
        String(currentDate.getMinutes()).padStart(2, '0') + ':' + 
        String(currentDate.getSeconds()).padStart(2, '0');
      // 填充表单
      this.form.transferNo = transferNo;
      this.form.transferTime = transferTime;
      this.open = true;
      this.title = "添加调拨单主";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const orderId = row.orderId || this.ids
      getTransferOrder(orderId).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.orderId != null) {
            updateTransferOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addTransferOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除调拨单主编号为"' + orderIds + '"的数据项？').then(() => {
        this.loading = true;
        return delTransferOrder(orderIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wms/transferOrder/export', {
        ...this.queryParams
      }, `transferOrder_${new Date().getTime()}.xlsx`)
    },
    /** 执行全部调拨 */
    handleConfirmAll() {
      if (this.$refs.transferItemTable) {
        this.buttonLoading = true;
        this.$refs.transferItemTable.handleConfirmAll().finally(() => {
          this.buttonLoading = false;
        });
      }
    }
  }
};
</script>
