<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="partNumber">
        <el-input
          v-model="queryParams.partNumber"
          placeholder="请输入图号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

<!--      <el-form-item label="生产令号" prop="totalWeight">
        <el-input
          v-model="queryParams.totalWeight"
          placeholder="请输入生产令号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item label="父级图号" prop="fnumber">
        <el-input
          v-model="queryParams.fnumber"
          placeholder="请输入图号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数量" prop="quantity">
        <el-input
          v-model="queryParams.quantity"
          placeholder="请输入数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="材料" prop="material">
        <el-input
          v-model="queryParams.material"
          placeholder="请输入材料"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否存在" prop="unitWeight">
        <el-input
          v-model="queryParams.unitWeight"
          placeholder="是否存在"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产令号" prop="totalWeight">
        <el-input
          v-model="queryParams.totalWeight"
          placeholder="请输入生产令号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input
          v-model="queryParams.remarks"
          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-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"
          v-hasPermi="['system:details:add']"
        >新增
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:details:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:details:export']"
        >导出
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:details:import']"
        >导入
        </el-button>
      </el-col>
     <el-col :span="3">
        <el-input
          v-model="groupName"
          placeholder="请输入上传分组"
          size="mini"
          clearable
        />
      </el-col>
     

      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="updateFBMaterial"
          v-hasPermi="['system:details:updateFBMaterial']"
        >更新物料清单
        </el-button>

      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-view"
          size="mini"
          @click="getBomUploadStatus"
          v-hasPermi="['system:details:viewGetBomUploadStatus']"
        >查看BOM上传状态
        </el-button>

      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" row-key="id" :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
              :data="detailsList" border :header-cell-style ="{'text-align':'center'}" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
<!--   //   <el-table-column label="id" align="center" prop="id" v-if="true"/>-->
      <el-table-column label="生产令号" align="center" prop="totalWeight"/>
      <el-table-column label="父级图号" align="center" prop="fnumber" v-if="true">
        <template slot-scope="scope">
          <div style="font-family: '等线'; font-weight: bold; ">
            {{ scope.row.fnumber }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="父级名称" align="center" prop="fname" v-if="true">
        <template slot-scope="scope">
          <div style="font-family: '等线'; font-weight: bold; ">
            {{  scope.row.fname }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="子项图号" align="left" prop="partNumber"/>
      <el-table-column label="子项名称" align="center" prop="name"/>
      <el-table-column label="子项分子" align="center" prop="quantity"/>
      <el-table-column label="子项分母" align="center" prop="denominator"/>
      <el-table-column label="属性" align="center" prop="stats"/>
      <el-table-column label="子项材料" align="center" prop="material"/>
      <el-table-column label="是否存在" align="center" prop="unitWeight">
        <template slot-scope="scope">
          <div :style="{
      color: scope.row.unitWeight === '是' ? 'green' : 'red',
      fontFamily: '等线',
      fontWeight: 'bold'
    }">{{ scope.row.unitWeight }}</div>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remarks"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
        <el-button size="mini" type="text" @click="handAddSon(scope.row)" icon="el-icon-plus">添加子集</el-button>
        <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:material:edit']">修改</el-button>
<!--          <el-button
            size="mini"
            type="text"
            @click="updateFBMaterial(scope.row)"
            v-hasPermi="['system:details:edit']"
          >上传BOM
          </el-button>-->
         <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:details:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      :pageSizes="[50, 100, 1000, 5000]"
      @pagination="getList"
    />

    <!-- 添加或修改bom明细对话框 -->
    <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="totalWeight">
          <el-input v-model="form.totalWeight" placeholder="生产令号" :disabled="isDisabled"/>
        </el-form-item>
        <el-form-item label="父级图号" prop="fnumber">
          <el-input v-model="form.fnumber" placeholder="父级图号"  :disabled="isDisabled" />
        </el-form-item>
        <el-form-item label="父级名称" prop="fname ">
          <el-input v-model="form.fname " placeholder="父级名称"  :disabled="isDisabled" />
        </el-form-item>
        <el-form-item label="子项图号" prop="partNumber">
          <el-input v-model="form.partNumber" placeholder="请输入图号"/>
        </el-form-item>
        <el-form-item label="子项名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="属性" prop="stats">
          <el-select v-model="form.stats" placeholder="请选择属性">
            <el-option label="自制" value="自制"></el-option>
            <el-option label="委外" value="委外"></el-option>
            <el-option label="外购" value="外购"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="子项分子" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入数量"/>
        </el-form-item>
        <el-form-item label="子项分母" prop="denominator">
          <el-input v-model="form.denominator" placeholder="请输入数量"/>
        </el-form-item>
        <el-form-item label="材料" prop="material">
          <el-input v-model="form.material" placeholder="请输入材料"/>
        </el-form-item>
        <el-form-item label="单重" prop="unitWeight">
          <el-input v-model="form.unitWeight" placeholder="请输入单重"/>
        </el-form-item>
        <el-form-item label="总重" prop="totalWeight">
          <el-input v-model="form.totalWeight" placeholder="请输入总重"/>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" 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="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的物料数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
<!--          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>-->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {listDetails, getDetails, delDetails, addDetails, updateDetails, updateFBl, viewGetBomUploadStatus} from "@/api/system/details";
import upload from "svg-sprite-loader/examples/custom-runtime-generator/build/main";
import {getToken} from "@/utils/auth";
import axios from "axios";
import {align} from "quill/ui/icons";

export default {
  name: "Details",
  props: ['params'],
  computed: {
    align() {
      return align
    },
    // upload() {
    //   return upload
    // }
  },
  data() {
    return {
      // 是否父级图号和父级名称input框置灰不可编辑或填写
      isDisabled: false,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // bom明细表格数据
      detailsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 1000,
        partNumber: undefined,
        fname: undefined,
        fnumber: undefined,
        name: undefined,
        stats: undefined,
        quantity: undefined,
        denominator:undefined,
        material: undefined,
        unitWeight: undefined,
        totalWeight: undefined,
        remarks: undefined
      },
      // 表单参数
      form: {},
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/details/importData"
      },
      // 表单校验
      rules: {

      },
      groupName: ""
    };
  },
  created() {
    this.queryParams.totalWeight = "";
    if (this.params && this.params.productionOrderNo) {
      this.queryParams.totalWeight = this.params.productionOrderNo;
    }
    
    this.getList();
  },

  methods: {
    /** 查询bom明细列表 */
    getList() {
      this.loading = true;
      listDetails(this.queryParams).then(response => {
        this.detailsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },



  /** 导入按钮操作 */
  handleImport() {
    this.upload.title = "明细导入";
    this.upload.open = true;
  },
  /** 下载模板操作 */
  importTemplate() {
    this.download('system/details/importTemplate', {}, `details_template_${new Date().getTime()}.xlsx`)
  },
  // 文件上传中处理
  handleFileUploadProgress(event, file, fileList) {
    this.upload.isUploading = true;
  },
  // 文件上传成功处理
  handleFileSuccess(response, file, fileList) {
    this.upload.open = false;
    this.upload.isUploading = false;
    this.$refs.upload.clearFiles();
    this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>"
      + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
    this.getList();
  },
  // 提交上传文件
  submitFileForm() {
    this.$refs.upload.submit();
  },
  // 取消按钮
  cancel() {
    this.open = false;
    this.reset();
  },
  // 表单重置
  reset() {
    this.form = {
      id: undefined,
      partNumber: undefined,
      name: undefined,
      quantity: undefined,
      material: undefined,
      unitWeight: undefined,
      totalWeight: undefined,
      remarks: undefined
    };
    this.resetForm("form");
  },
  /** 搜索按钮操作 */
  handleQuery() {
    this.queryParams.pageNum = 1;
    this.getList();
  },
  /** 重置按钮操作 */
  resetQuery() {
    this.resetForm("queryForm");
    this.handleQuery();
  },
  // 多选框选中数据
  handleSelectionChange(selection) {
    this.ids = selection.map(item => item.id)
    this.fnumbers = selection.map(item => item.fnumber)
    this.single = selection.length !== 1
    this.multiple = !selection.length
  },
  /** 新增按钮操作 */
  handleAdd() {
    this.reset();
    this.open = true;
    this.title = "添加bom明细";
  },
  updateFBMaterial(row) {
  this.loading = true;
  this.reset();
  if (!this.ids || this.ids.length === 0) {
    this.$modal.msgError("请先选择要上传的行!");
    this.loading = false;
    return;
  }
  if (!this.groupName || !this.groupName.trim()) {
    this.$modal.msgError("请填写上传分组!");
    this.loading = false;
    return;
  }
  const selectedData = this.ids.map(id => {
    const item = this.detailsList.find(row => row.id === id);
    return {
      fnumber: item.fnumber,
      totalWeight: item.totalWeight,
      groupName: this.groupName.trim()
    };
  });
  updateFBl(selectedData).then(response => {
    this.form = response;
    const successCount = response.length;
    this.resNotice(successCount);
  }).catch(error => {
    console.error('更新BOM失败:', error);
    this.$modal.msgError("更新BOM失败，请重试!");
  }).finally(() => {
    this.loading = false;
  });
},
/** 查看BOM上传状态 */
getBomUploadStatus() {
  this.loading = true;
  this.reset();

  // 检查是否有选中行
  if (!this.ids || this.ids.length === 0) {
    this.$modal.msgError("请先选择要查询的行!");
    this.loading = false;
    return;
  }

  // 获取第一个选中行的生产令号
  const firstSelectedItem = this.detailsList.find(row => row.id === this.ids[0]);
  if (!firstSelectedItem) {
    this.$modal.msgError("未找到选中的数据项!");
    this.loading = false;
    return;
  }

  const rooteProdet = firstSelectedItem.totalWeight;
  console.log('选中的行ID:', this.ids);
  console.log('提取的生产令号:', rooteProdet);
  
  if (!rooteProdet) {
    this.$modal.msgError("未获取到生产令号，请检查选中行的数据!");
    this.loading = false;
    return;
  }

  // 调用获取BOM上传状态接口
  viewGetBomUploadStatus(rooteProdet).then(response => {
    // 处理后端返回的BOM上传状态数据
    const bomData = response.data;
    if (bomData && bomData.items) {
      // 显示BOM上传状态结果
      this.showBomUploadStatus(bomData.items);
    } else {
      this.$modal.msgWarning("未获取到BOM上传状态数据");
    }
  }).catch(error => {
    console.error('获取BOM上传状态失败:', error);
    this.$modal.msgError("获取BOM上传状态失败，请重试!");
  }).finally(() => {
    this.loading = false;
  });
},
/** 显示BOM上传状态 **/
showBomUploadStatus(items) {
  if (!items || items.length === 0) {
    this.$modal.msgWarning("暂无BOM上传状态数据");
    return;
  }
  
  // 统计各状态数量
  const successCount = items.filter(item => item.code === '200').length; // 成功上传
  const existCount = items.filter(item => item.code === '100').length;   // 已存在且一致
  const failedCount = items.filter(item => item.code === '300').length;  // 上传失败
  const totalCount = items.length;
  
  // 构建显示内容
  let content = `
    <div style="margin-bottom: 15px; padding: 10px; background-color: #f5f7fa; border-radius: 4px;">
      <div><strong>项目编码:</strong> ${items[0]?.projectCode || '未知'}</div>
      <div><strong>总计:</strong> ${totalCount} 条</div>
      <div><strong>成功上传:</strong> <span style="color: green;">${successCount}</span> 条</div>
      <div><strong>已存在:</strong> <span style="color: blue;">${existCount}</span> 条</div>
      <div><strong>上传失败:</strong> <span style="color: red;">${failedCount}</span> 条</div>
    </div>
    <div style="max-height: 400px; overflow-y: auto;">
  `;
  
  items.forEach((item, index) => {
    let statusColor, statusText, backgroundColor;
    
    switch(item.code) {
      case '100':
        statusColor = 'blue';
        statusText = '已存在';
        backgroundColor = '#f0f8ff';
        break;
      case '200':
        statusColor = 'green';
        statusText = '成功上传';
        backgroundColor = '#f0f9ff';
        break;
      case '300':
        statusColor = 'red';
        statusText = '上传失败';
        backgroundColor = '#fef2f2';
        break;
      default:
        statusColor = 'gray';
        statusText = '未知状态';
        backgroundColor = '#f5f5f5';
    }
    
    content += `
      <div style="margin-bottom: 10px; padding: 8px; border: 1px solid #e4e7ed; border-radius: 4px; background-color: ${backgroundColor};">
        <div><strong>序号:</strong> ${index + 1}</div>
        <div><strong>物料编码:</strong> ${item.materialCode || '无'}</div>
        <div><strong>状态码:</strong> <span style="color: ${statusColor}; font-weight: bold;">${item.code}</span></div>
        <div><strong>上传状态:</strong> <span style="color: ${statusColor}; font-weight: bold;">${statusText}</span></div>
        <div><strong>说明:</strong> ${item.reason || '无'}</div>
      </div>
    `;
  });
  content += '</div>';
  
  this.$alert(content, 'BOM上传状态', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确定',
    customClass: 'bom-upload-status-dialog'
  });
},
/** 弹窗 **/
resNotice(successCount) {
      this.$alert(`成功上传的条数：${successCount}`, '成功信息', {
        confirmButtonText: '确定',
        callback: action => {
          this.$message({
            type: 'info',
            message: `action: ${action}`
          });
        }
      });
    },
  /** 添加子集操作 */
  handAddSon(row){
    // 表单重置
    this.reset();
    // 禁用
    this.isDisabled = true;
    // 打开弹框
    this.open = true;
    // 弹框标题
    this.title = "添加子集";

    // 如果自己图号和子集名称为空
    if(row.partNumber == null && row.name == null){
    // 表单图号赋值父级
    this.form.fnumber = row.fnumber;
    // 表单名称赋值父级
    this.form.fname = row.fname;
    }else{
    // 表单图号赋值子集
    this.form.fnumber = row.partNumber;
    // 表单名称赋值子集
    this.form.fname = row.name;
    }

  },
  /** 修改按钮操作 */
  handleUpdate(row) {
    this.loading = true;
    this.reset();
    const id = row.id || this.ids
    getDetails(id).then(response => {
      this.loading = false;
      this.form = response.data;
      this.open = true;
      this.title = "修改bom明细";
    });
  },
  /** 提交按钮 */
  submitForm() {
    this.$refs["form"].validate(valid => {
      if (valid) {
        this.buttonLoading = true;
        if (this.form.id != null) {
          updateDetails(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          }).finally(() => {
            this.buttonLoading = false;
          });
        } else {
          addDetails(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          }).finally(() => {
            this.buttonLoading = false;
          });
        }
      }
    });
  },
  /** 删除按钮操作 */
  handleDelete(row) {
    const ids = row.id || this.ids;
    this.$modal.confirm('是否确认删除bom明细编号为"' + ids + '"的数据项？').then(() => {
      this.loading = true;
      return delDetails(ids);
    }).then(() => {
      this.loading = false;
      this.getList();
      this.$modal.msgSuccess("删除成功");
    }).catch(() => {
    }).finally(() => {
      this.loading = false;
    });
  },
  /** 导出按钮操作 */
  handleExport() {
    this.download('system/details/export', {
      ...this.queryParams
    }, `details_${new Date().getTime()}.xlsx`)
  }
}
}
;
</script>
