<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="productionCode">
        <el-input v-model="queryParams.productionCode" placeholder="请输入生产令号" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="项目进度" prop="productionName">
        <el-input v-model="queryParams.productionName" placeholder="请输入项目进度" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="图纸计划时间" prop="drawingPlanTime">
        <el-date-picker clearable v-model="queryParams.drawingPlanTime" type="date" value-format="yyyy-MM-dd"
                        placeholder="请选择图纸计划时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="上传图纸" prop="uploadDrawing">
        <el-input v-model="queryParams.uploadDrawing" placeholder="请输入上传图纸" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="图纸预览" prop="drawingPreview">
        <el-input v-model="queryParams.drawingPreview" placeholder="请输入图纸预览" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>

      <el-form-item label="任务完成时间" prop="taskCompletionTime">
        <el-date-picker clearable v-model="queryParams.taskCompletionTime" type="date" value-format="yyyy-MM-dd"
                        placeholder="请选择任务完成时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="生产配料时间" prop="productionMaterialTime">
        <el-date-picker clearable v-model="queryParams.productionMaterialTime" type="date" value-format="yyyy-MM-dd"
                        placeholder="请选择生产配料时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="生产装配时间" prop="productionAssemblyTime">
        <el-date-picker clearable v-model="queryParams.productionAssemblyTime" type="date" value-format="yyyy-MM-dd"
                        placeholder="请选择生产装配时间">
        </el-date-picker>
      </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:plan:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['system:plan:edit']">修改
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleImage"
                v-hasPermi="['system:plan:upload']">上传图片</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:plan: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:plan:export']">导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload" size="mini" @click="handleImport"
                   v-hasPermi="['system:plan:import']">导入
        </el-button>
      </el-col>


      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">

      <el-table-column type="selection" width="55" align="center"/>

      <el-table-column label="生产令号" width="200" align="center" prop="productionCode" width:100>
        <template slot-scope="scope">
          <el-button @click="openProductionInfo(scope.row)" type="primary">
            {{ scope.row.productionCode }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="项目进度" width="300" align="center" prop="productionName">
        <template slot-scope="scope">
          <el-progress :stroke-width="25" :text-inside="true" :percentage="scope.row.productionName"/>
        </template>
      </el-table-column>
      <el-table-column label="成品图号" align="center" prop="figureNumber" width="100"/>
      <el-table-column label="物料名称" align="center" prop="figureName" width="100"/>
      <el-table-column label="成品数量" align="center" prop="figureNum" width="100"/>

      <el-table-column label="计划状态" align="center" prop="planStatus"/>
      <el-table-column label="任务状态" align="center" prop="taskStatus"/>

      <el-table-column label="上传图纸" align="center" prop="uploadDrawing"/>

      <el-table-column label="图纸预览" align="center" prop="drawingPreview" width="200">
        <template slot-scope="scope">
          <ImagePreview v-if="previewListResource && checkFileSuffix(scope.row.drawingPreview)" :width=100 :height=100
                        :src="scope.row.drawingPreview" :preview-src-list="[scope.row.drawingPreview]"/>
          <span v-text="scope.row.drawingPreview"
                v-if="!checkFileSuffix(scope.row.drawingPreview) || !previewListResource"/>
        </template>
      </el-table-column>
      <el-table-column label="图纸计划时间" align="center" prop="drawingPlanTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.drawingPlanTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图纸完成时间" align="center" prop="taskCompletionTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.taskCompletionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生产配料时间" align="center" prop="productionMaterialTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.productionMaterialTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生产装配时间" align="center" prop="productionAssemblyTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.productionAssemblyTime, '{y}-{m}-{d}') }}</span>
        </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="handleUpdate(scope.row)"
                     v-hasPermi="['system:plan:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:plan:remove']">删除
          </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-drawer title="计划详情" :visible.sync="drawer" :with-header="false" direction="rtl" size="50%">

      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span class="card-title">设计</span>
        </div>
        <div class="content">
          <el-row class="required-time">
            <el-col :span="24">
              <div style="margin: 10px 0;">
                <span>设计图纸所需时间：</span>
                <el-date-picker size="mini" :value="needTime" type="daterange" align="right" unlink-panels
                                value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                :picker-options="pickerOptions" @input="changeNeedTime">
                </el-date-picker>
              </div>
            </el-col>
          </el-row>
          <el-row class="content-title">
            <el-col :span="12">操作</el-col>
            <el-col :span="12">进度</el-col>
          </el-row>
          <el-row v-for="(item, key) in tableData" :key="key">
            <el-col :span="12">
              <el-upload class="upload-demo" ref="upload" :on-error="handleUploadError"
                         :on-success="handleUploadSuccess" :on-remove="handleRemove" :action="action + planInfo.id"
                         :file-list="fileList" :headers="headers">
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <!-- <el-button style="margin-left: 10px;" size="small" type="success"
                  @click="submitUpload">上传到服务器</el-button> -->
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-col>

            <!-- 进度列 -->
            <el-col :span="12" class="progress">
              <el-progress type="circle" :percentage="designProgress"
                           :status="designProgress >= 100 ? 'success' : 'exception'"></el-progress>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span class="card-title">生产</span>
        </div>

        <div class="content">
          <el-row class="content-title">
            <el-col :span="12">操作</el-col>
            <el-col :span="12">进度</el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-row class="btn">
                <el-col :span="8">
                  <span>装配领料</span>
                </el-col>
                <el-col :span="8">
                  <span>{{ this.planInfo.assemblellStatus ? '已完成' : '未完成' }}</span>
                </el-col>
                <el-col :span="8">
                  <el-button type="primary" @click="handleIsZPLL">切换进度</el-button>
                </el-col>
              </el-row>

              <el-row class="btn">
                <el-col :span="8">
                  <span>装配制造</span>
                </el-col>
                <el-col :span="8">
                  <span>{{ this.planInfo.assemblezzStatus ? '已完成' : '未完成' }}</span>
                </el-col>
                <el-col :span="8">
                  <el-button type="primary" @click="handleIsZPZZ">切换进度</el-button>
                </el-col>
              </el-row>
            </el-col>

            <el-col :span="12" class="progress">
              <el-progress type="circle" :percentage="productionProgress"
                           :status="productionProgress >= 100 ? 'success' : 'exception'"></el-progress>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span class="card-title">采购</span>
        </div>

        <el-table style="width: 100%;" max-height="300" v-loading="figureSaveLoading" :data="figureSaveList">
          <el-table-column prop="productionCode" label="生产令号"></el-table-column>
          <el-table-column prop="figureNumber" label="图号"></el-table-column>
          <el-table-column prop="figureName" label="名称"></el-table-column>
          <el-table-column prop="figureNum" label="数量" header-align="left" align="center"></el-table-column>
          <el-table-column prop="jdInventory" label="库存"></el-table-column>
          <!-- 操作列 -->
          <!-- <el-table-column prop="operation" label="操作" width="200px"> </el-table-column> -->
          <!-- 进度列 -->
          <!-- <el-table-column prop="operation" label="进度" width="300px"> </el-table-column> -->
        </el-table>
      </el-card>
    </el-drawer>

    <!-- 导入导入对话框 -->
    <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>
    <!-- 添加或修改排产计划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生产令号" prop="productionCode">
              <el-input v-model="form.productionCode" placeholder="请输入生产令号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图号" prop="figureNumber">
              <el-input v-model="form.figureNumber" placeholder="请输入图号"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="名称" prop="figureName">
              <el-input v-model="form.figureName" placeholder="请输入名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行单路径" prop="drawingPreview">
              <el-input v-model="form.drawingPreview" placeholder="请输入执行单路径"/>
            </el-form-item>
          </el-col>
          <el-form-item label="开始日期" prop="startDate">
            <el-date-picker clearable
                            v-model="form.startDate"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="请选择开始日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker clearable
                            v-model="form.endTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="请选择结束时间">
            </el-date-picker>
          </el-form-item>
          <!-- 图片上传控件 -->
          <el-form-item label="图片" prop="pictureUrl">
            <el-upload
              :action="imgUpload.url"
              :headers="imgUpload.headers"
              :on-success="handlePictureSuccess"
              :before-upload="beforePictureUpload"
              list-type="picture-card"
              :file-list="fileListShow"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemovePicture"
              multiple>
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" />
            </el-dialog>
          </el-form-item>
        </el-row>
      </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="title" :visible.sync="uploadOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件名">
          <fileUpload v-model="form.file" v-if="type === 0"/>
          <imageUpload v-model="form.file" v-if="type === 1"/>
        </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>

  </div>
</template>

<script>
import {getToken} from "@/utils/auth";
import {listPlan, getPlan, delPlan, addPlan, updatePlan, updateTimeRange, updateZPStatus} from "@/api/system/plan";
import {listSave} from '@/api/system/save'
import upload from "svg-sprite-loader/examples/custom-runtime-generator/build/main";

export default {
  name: "Plan",
  computed: {
    upload() {
      return upload
    }
  },
  data() {
    return {
      lookdialogVisible: false,
      previewListResource: true,
      previewpic: "",
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/plan/importData"
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      fileList: [],
      // 绑定设计图纸所需时间
      needTime: ['', ''],
      // 项目总进度
      Progress: 0,
      // 绑定设计进度
      designProgress: 0,
      // 绑定生产进度
      productionProgress: 0,
      // 上传文件地址
      action: process.env.VUE_APP_BASE_API + '/system/plan/importDWG/',
      // 请求头，token认证
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 排产计划详情
      planInfo: {},
      // 按钮loading
      buttonLoading: false,
      // 外购件临时列表
      figureSaveList: [],
      // 外购件临时列表加载层
      figureSaveLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //抽屉
      drawer: false,
      tableData: [
        {operation: '设计部分', progress: 75},
        /* { operation: '生产部分', progress: 50 },
         { operation: '销售部分', progress: 30 }*/
      ],
      tableData1: [
        {operation: '生产部分', progress: 75},
        /* { operation: '生产部分', progress: 50 },
         { operation: '销售部分', progress: 30 }*/
      ],
      // 总条数
      total: 0,
      // 排产计划表格数据
      planList: [],
      // 排产计划详情表格数据(采购)
      purchaseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      uploadOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productionCode: undefined,
        productionName: undefined,
        planStatus: undefined,
        taskStatus: undefined,
        drawingPlanTime: undefined,
        uploadDrawing: undefined,
        drawingPreview: undefined,
        taskCompletionTime: undefined,
        productionMaterialTime: undefined,
        productionAssemblyTime: undefined,
      },
      // 表单参数
      form: {
        productionCode: '',
        figureNumber: '',
        figureName: '',
        drawingPreview: '',
        subItems: [
          {text: '铆   焊', startDate: '', duration: '',type:"2"},
          {text: '热 处 理', startDate: '', duration: '',type:"3"},
          {text: '普车普铣', startDate: '', duration: '',type:"4"},
          {text: '走 心 机', startDate: '', duration: '',type:"5"},
          {text: '龙门立加', startDate: '', duration: '',type:"6"},
          {text: '表面处理', startDate: '', duration: '',type:"7"},
          {text: '外 购 件', startDate: '', duration: '',type:"8"}
        ],
        createdTime: ''

      },
      // 表单校验
      rules: {
        /*id: [
          { required: true, message: "ID不能为空", trigger: "blur" }
        ],
        productionCode: [
          { required: true, message: "生产令号不能为空", trigger: "blur" }
        ],
        productionName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        planStatus: [
          { required: true, message: "计划状态不能为空", trigger: "change" }
        ],
        taskStatus: [
          { required: true, message: "任务状态不能为空", trigger: "change" }
        ],
        drawingPlanTime: [
          { required: true, message: "图纸计划时间不能为空", trigger: "blur" }
        ],
        uploadDrawing: [
          { required: true, message: "上传图纸不能为空", trigger: "blur" }
        ],
        drawingPreview: [
          { required: true, message: "图纸预览不能为空", trigger: "blur" }
        ],
        taskCompletionTime: [
          { required: true, message: "任务完成时间不能为空", trigger: "blur" }
        ],
        productionMaterialTime: [
          { required: true, message: "生产配料时间不能为空", trigger: "blur" }
        ],
        productionAssemblyTime: [
          { required: true, message: "生产装配时间不能为空", trigger: "blur" }
        ],*/
      },
      imgUpload: {
        url: process.env.VUE_APP_BASE_API + "/system/plan/uploadPicture",
        headers: {Authorization: "Bearer " + getToken()}
      },
      dialogVisible: false,
      dialogImageUrl: '',
      fileListShow: [],
      fileListPut: [],
      type: 0
    };
  },
  created() {
    this.getList();
  },
  // watch: {
  //   needTime(newValue, oldValue) {
  //     if (newValue !== null) {
  //       if (this.fileList.length > 0) {
  //         this.designProgress = Math.min(this.designProgress + 50, 100);
  //         this.calculate(25, true)
  //       } else {
  //         this.designProgress = 50;
  //         this.calculate(25, false)
  //       }
  //     } else {
  //       this.designProgress = Math.max(this.designProgress - 50, 0);
  //       this.calculate(-25, true)
  //     }
  //     console.log( oldValue.length)
  //     if (oldValue !== null || oldValue.length > 0) {
  //       this.planInfo.drawingPlanTime = newValue[0]
  //       this.planInfo.taskCompletionTime = newValue[1]
  //       // 监听设计图纸所需时间,进行更新
  //       updateTimeRange(this.planInfo).then(response => {
  //         this.$modal.msgSuccess("更新成功");
  //       }).finally(() => {

  //       });
  //     }
  //   }
  // },
  methods: {
    changeNeedTime(value) {
      if (value) {
        // 设置时间
        this.$set(this.needTime, 0, value[0]);
        this.$set(this.needTime, 1, value[1]);

        // 增加进度
        if (this.fileList.length > 0) {
          this.designProgress = Math.min(this.designProgress + 50, 100);
          this.calculate(25, true)
        } else {
          this.designProgress = 50;
          this.calculate(25, false)
        }
      } else {
        // 清空时间
        this.$set(this.needTime, 0, '');
        this.$set(this.needTime, 1, '');

        // 减少进度
        this.designProgress = Math.max(this.designProgress - 50, 0);
        this.calculate(-25, true)
      }

      // 对象赋值
      this.planInfo.drawingPlanTime = this.needTime[0]
      this.planInfo.taskCompletionTime = this.needTime[1]
      // 监听设计图纸所需时间,进行更新
      updateTimeRange(this.planInfo).then(response => {
        this.$modal.msgSuccess("更新成功");
      }).finally(() => {

      });
    },

    /** 导入按钮操作 */
    handleImport() {
      const data = this.ids.join(",")
      this.upload.title = "明细导入";
      this.upload.open = true;
      const url = process.env.VUE_APP_BASE_API + "/system/plan/importData" + "/" + data
      this.upload.url = url
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/plan/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();
    },

    /** 图片按钮操作 */
    handleImage() {
      this.reset();
      this.uploadOpen = true;
      this.title = "上传图片";
      this.type = 1;
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        if (this.needTime !== null) {
          if (this.fileList.length <= 0) {
            this.designProgress = Math.min(this.designProgress + 50, 100);
            this.calculate(25, true)
          }
        } else {
          this.designProgress = 50;
          this.calculate(25, false)
        }

        this.fileList.push({name: file.name});
      }
    },
    // 删除文件
    handleRemove(file) {
      this.fileList.splice(file, 1);
      if (this.fileList.length == 0) {
        this.designProgress = Math.max(this.designProgress - 50, 0);
        this.calculate(-25, true)
      }
    },
    // 打开项目详情
    openProductionInfo(item) {
      // 是否打开,设置为打开
      this.drawer = true
      this.designProgress = 0
      this.productionProgress = 0
      this.fileList = []

      // 如果设计图纸所需开始时间和结束时间不为空
      if (item.drawingPlanTime !== null && item.taskCompletionTime !== null) {
        // 赋值显示到界面
        this.needTime = [item.drawingPlanTime, item.taskCompletionTime]
        // 三元表达式判断进度是否等于0,两种情况,50或者100
        this.designProgress = this.designProgress === 0 ? 50 : 100
      }

      // 逗号截取字符串，如果不存在值截取时会报错，需要进行判断后截取
      const idList = item.fileName == null ? [] : item.fileName.split(',')
      // 循环遍历集合
      for (let i = 0; i < idList.length; i++) {
        //  通过文件名进行检索
        const list = this.fileList.filter(item => {
          return item.name.includes(idList[i])
        })
        // 是否存在相同文件,为空则不存在
        if (list.length === 0) {
          // 集合追加
          this.fileList.push({name: idList[i]});
        }
      }

      // 如果存在文件
      if (this.fileList.length > 0) {
        // 三元表达式判断进度是否等于0,两种情况,50或者100
        this.designProgress = this.designProgress === 0 ? 50 : 100
      }

      if (item.assemblezzStatus) {
        this.productionProgress = this.productionProgress === 0 ? 50 : 100
      }

      if (item.assemblellStatus) {
        this.productionProgress = this.productionProgress == 0 ? 50 : 100
      }

      this.Progress = item.productionName

      // 将点击后的排产计划详情对象赋值
      this.planInfo = item

      this.figureSaveLoading = true;
      const data = {
        productionCode: this.planInfo.productionCode
      }
      listSave(data).then(response => {
        this.figureSaveList = response.rows;
        this.total = response.total;
        this.figureSaveLoading = false;
      });
    },
    // 计算项目进度
    calculate(val, isCalculate) {
      const plan = this.planList.filter(item => {
        return item.productionCode.includes(this.planInfo.productionCode)
      })

      // 是否计算
      if (isCalculate) {
        this.Progress += val;
      } else {
        this.Progress = val
      }

      this.$set(this.planList, plan)
      this.planInfo.productionName = this.Progress
    },
    // 是否完成装配领料
    handleIsZPLL() {
      this.planInfo.assemblellStatus = this.planInfo.assemblellStatus == null ? false : !this.planInfo.assemblellStatus

      if (this.planInfo.assemblellStatus) {
        this.productionProgress += 50
        this.calculate(25, true)
      } else {
        this.productionProgress -= 50
        this.calculate(-25, true)
      }

      this.updateZPStatus(this.planInfo)
    },
    // 是否完成装配制造
    handleIsZPZZ() {
      this.planInfo.assemblezzStatus = this.planInfo.assemblezzStatus == null ? false : !this.planInfo.assemblezzStatus

      if (this.planInfo.assemblezzStatus) {
        this.productionProgress += 50
        this.calculate(25, true)
      } else {
        this.productionProgress -= 50
        this.calculate(-25, true)
      }

      this.updateZPStatus(this.planInfo)
    },
    // 更新装配状态(领料,制造)
    updateZPStatus(data) {
      updateZPStatus(data).then(response => {
        this.$modal.msgSuccess("更新成功");
      }).finally(() => {

      });
    },
    handleRemove2(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview2(file) {
      console.log(file);
    },
    /** 查询排产计划列表 */
    getList() {
      this.loading = true;
      listPlan(this.queryParams).then(response => {
        for (let i = 0; i < response.rows.length; i++) {
          // 进度需要重置
          this.Progress = 0

          // 存在文件进度加25%
          if (response.rows[i].fileName !== null) {
            this.Progress += 25
          }

          // 设计图纸所需时间进度加25%
          if (response.rows[i].drawingPlanTime !== null && response.rows[i].taskCompletionTime !== null) {
            this.Progress += 25
          }

          // 装配领料已完成进度加25%
          if (response.rows[i].assemblellStatus) {
            this.Progress += 25
          }

          // 装配制造已完成进度加25%
          if (response.rows[i].assemblezzStatus) {
            this.Progress += 25
          }

          response.rows[i].productionName = this.Progress
        }
        this.planList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        productionCode: undefined,
        productionName: undefined,
        planStatus: undefined,
        taskStatus: undefined,
        drawingPlanTime: undefined,
        uploadDrawing: undefined,
        drawingPreview: undefined,
        taskCompletionTime: undefined,
        productionMaterialTime: undefined,
        productionAssemblyTime: undefined,
        createBy: undefined,
        updateBy: undefined,
        subItems: [
          {text: '下   料', startDate: '', duration: ''},
          {text: '铆   焊', startDate: '', duration: ''},
          {text: '热 处 理', startDate: '', duration: ''},
          {text: '普车钻床', startDate: '', duration: ''},
          {text: '走心 机', startDate: '', duration: ''},
          {text: '龙门立加', startDate: '', duration: ''},
          {text: '表面处理', startDate: '', duration: ''},
          {text: '外购  件', startDate: '', duration: ''}
        ],
        createTime: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    checkFileSuffix(fileSuffix) {
      let arr = ["png", "jpg", "jpeg"];
      return arr.some(type => {
        return fileSuffix.indexOf(type) > -1;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加排产计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids;
      getPlan(id).then(response => {
        this.loading = false;
        this.form = response.data;
        // 图片回显
        if (this.form.pictureUrl) {
          try {
            this.fileListShow = JSON.parse(this.form.pictureUrl);
            this.fileListPut = JSON.parse(this.form.pictureUrl);
          } catch (e) {
            this.fileListShow = [];
            this.fileListPut = [];
          }
        } else {
          this.fileListShow = [];
          this.fileListPut = [];
        }
        this.open = true;
        this.title = "修改排产计划";
      });
    },
    /** 提交按钮 */
    submitForm() {
      // 提交前将图片列表转为JSON
      this.form.pictureUrl = JSON.stringify(this.fileListPut);
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updatePlan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addPlan(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('是否确认删除排产计划编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delPlan(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/plan/export', {
        ...this.queryParams
      }, `plan_${new Date().getTime()}.xlsx`)
    },
    handlePictureSuccess(response, file) {
      const imgObj = { name: file.name, url: response.data.url };
      this.fileListShow.push(imgObj);
      this.fileListPut.push(imgObj);
    },
    beforePictureUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
      }
      return isJPG || isPNG;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemovePicture(file) {
      this.fileListShow = this.fileListShow.filter(f => f.name !== file.name);
      this.fileListPut = this.fileListPut.filter(f => f.name !== file.name);
    }
  }
};

</script>
<style>
.drawer-sections {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  height: 100%;
}

.drawer-section {
  text-align: center;
  margin: 10px 0;
}

.design-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.upload-container {
  flex: 1;
  text-align: left;
  /* Aligns the upload button to the left */
}

.progress-container {
  flex: 1;
  text-align: right;
  /* Aligns the progress circle to the right */
}

.btn {
  margin: 10px;
}

.content-title {
  height: 30px;
  line-height: 30px;
  font-weight: 600;
  font-size: 13px;
  color: #515a6e;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 96%;
  margin: 20px auto;
}

.card-title {
  font-size: 22px;
  font-weight: 600;
}

.progress {
  text-align: center;
}

.el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: #82a3d4 !important;
}
</style>
