<template>
  <div class="app-container" style="display: flex;">
    <div style="width: 400px; margin-right:10px;">
      <el-form :model="queryWorkunitParams" ref="queryWorkunitForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="车间" prop="workshopId">
            <el-select filterable v-model="queryWorkunitParams.workshopId" placeholder="请选择车间" clearable @change="handleChangeWorkshopId">
              <el-option
                v-for="dict in workshopList"
                :key="dict.workshopId"
                :label="dict.workshopName"
                :value="dict.workshopId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="工作中心" prop="workstationId">
            <el-select filterable v-model="queryWorkunitParams.workstationId" placeholder="请选择工作中心" clearable @change="handleChangeWorkStationId">
              <el-option
                v-for="dict in workstationList"
                :key="dict.workstationId"
                :label="dict.workstationName"
                :value="dict.workstationId"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleWorkunitQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetWorkunitQuery">重置</el-button>
          </el-form-item> -->
        </el-form>
        <div  class="cardBox">
          <div v-if="taskWorkunitList.length" class="list">
            <div @click.stop="handleClick(item,index)" class="list-item" :class="{'active': currentTask === index}" v-for="(item,index) in taskWorkunitList" :key="index">
               <div class="item-top">{{ item.workunitCode }}</div>
               <div>{{ item.workunitName }}</div>
            </div>
          </div>
          <div v-else style="text-align: center;margin-top:30px;color:#ccc;">暂无数据</div>
        </div>
    </div>
    <div style="width: calc(100% - 400px);">
       <el-form :model="queryParams" @submit.native.prevent ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
          <el-form-item label="任务号" prop="taskCode">
            <el-input
              v-model="queryParams.taskCode"
              placeholder="请输入任务号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="工序名称" prop="processName">
            <el-input
              v-model="queryParams.processName"
              placeholder="请输入工序名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <!-- <el-form-item label="工作单元名称" prop="workunitName">
            <el-input
              v-model="queryParams.workunitName"
              placeholder="请输入工作单元名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item> -->
          <el-form-item label="状态" prop="statusArr">
            <el-select v-model="queryParams.statusArr" multiple placeholder="请选择单据状态" clearable>
              <el-option
                v-for="dict in dict.type.TASK_STATUS"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="编排单号" prop="arrangeCode">
            <el-input
              v-model="queryParams.arrangeCode"
              placeholder="请输入编排单号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="编排人员" prop="arrangeUsername">
            <el-input
              v-model="queryParams.arrangeUsername"
              placeholder="请输入编排人员"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="工单编码" prop="workorderCode">
            <el-input
              v-model="queryParams.workorderCode"
              placeholder="请输入工单编码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="计划开始时间段" label-width="130px" prop="scheduleStartDate">
            <el-date-picker
              v-model="queryParams.scheduleStartDate"
              type="datetimerange"
              :clearable="false"
              range-separator="至"
              start-placeholder="开始日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="计划结束时间段" label-width="130px" prop="scheduleEndDate">
            <el-date-picker
              v-model="queryParams.scheduleEndDate"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              :clearable="false"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="工单类型" prop="workorderTypes">
            <el-select v-model="queryParams.workorderTypes" multiple clearable placeholder="请选择状态" >
              <el-option v-for="dict in dict.type.mes_workorder_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value">
              </el-option>
            </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
          size="mini"
          @click="handleSchedule"
        >排程</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          :disabled='single'
          @click="handleJobAssignment"
        >作业分派</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="handleOpenTask"
        >取消完工</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          :disabled='single'
          @click="handleSplitWorkstation"
        >工序新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          :disabled='single'
          @click="handleDeleteTask"
        >工序删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          :disabled='single'
          @click="handleVirtualReporting"
        >虚拟报工</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="maintenanceList" @selection-change="handleSelectionChange" ref="tableRef">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编排单号" width="120" prop="arrangeCode">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="taskWorkunitId= scope.row.taskWorkunitId, isOrder = false, arrangCodeVisible = true"
            >{{ scope.row.arrangeCode }}</el-button
          >
        </template>
      </el-table-column>
       <el-table-column label="任务单编码" width="120" prop="taskCode">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['mes:pro:protask:query']"
            >{{ scope.row.taskCode }}</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="任务状态" align="center" prop="quantity">
        <template slot-scope="{ row }">
          {{ dict.type.TASK_STATUS.find(item => item.value == row.status).label }}
        </template>
      </el-table-column>
      <el-table-column label="虚拟报工" align="center" prop="virtualFlag">
        <template slot-scope="{ row }">
          {{ row.virtualFlag ? '是'  : '否' }}
        </template>
      </el-table-column>
       <el-table-column
        label="工序名称"
        align="center"
        prop="processName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="任务顺序"
        align="center"
        prop="ordinalStr"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="排产数量" align="center" prop="quantity" />
      <el-table-column label="可加工数量" align="center" prop="quantityWait"/>
      <el-table-column label="已完成数量" align="center" prop="quantityQualify" />
      <el-table-column label="委外待收货数量" align="center" prop="quantityAssist" />
      <el-table-column label="编排人员" align="center" prop="arrangeUsername" />
      <!-- <el-table-column label="工单编码" align="center" prop="workorderCode" /> -->
      <el-table-column
        label="工作中心"
        align="center"
        prop="workstationName"
        width="140"
      />
      <el-table-column
        label="作业单元名称"
        align="center"
        prop="workunitName"
        width="200"
      >
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.workunitName" key="1" v-if="scope.row.status === 'UN_ASSIGN'|| scope.row.status === 'PREPARE'">
            <el-input v-model="scope.row.workunitName">
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="currentData = scope.row, $refs['WorkunitSelect'].showFlag = true"
              ></el-button>
            </el-input>
          </el-tooltip>
          <el-tooltip :content="scope.row.workunitName" key="2" v-else>
            <span>{{
                scope.row.workunitName
              }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
        label="计划开始时间"
        align="center"
        prop="scheduleStartDate"
        width="230"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <el-date-picker
            v-if="scope.row.status === 'UN_ASSIGN'|| scope.row.status === 'PREPARE'"
            v-model="scope.row.scheduleStartDate"
            type="datetime"
            :clearable="false"
            style="width: 100%;"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择计划开始时间"
            @focus="writeRow(scope.row)"
            @change="editTime(scope.row, 'start')"
          >
          </el-date-picker>
          <span v-else>{{
            parseTime(scope.row.scheduleStartDate)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="计划结束时间"
        align="center"
        prop="scheduleEndDate"
        width="230"
      >
        <template slot-scope="scope">
          <el-date-picker
             v-if="scope.row.status === 'UN_ASSIGN'|| scope.row.status === 'PREPARE'"
            v-model="scope.row.scheduleEndDate"
            type="datetime"
            :clearable="false"
            style="width: 100%;"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择计划结束时间"
            @focus="writeRow(scope.row)"
            @change="editTime(scope.row, 'end')"
          >
          </el-date-picker>
          <span v-else>{{
            parseTime(scope.row.scheduleEndDate)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工单类型" align="center" prop="workorderType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_workorder_type" :value="scope.row.workorderType" />
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="操作"
        width="150px"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:pro:protask:edit']"
            >编辑</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"
    />
    </div>

    <!-- 添加或修改要维护刀模版对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-form ref="form" :model="form" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="编号" prop="taskCode">
              <el-input v-model="form.taskCode" readonly="readonly" disabled />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="名称" prop="taskName">
              <el-input v-model="form.taskName" readonly="readonly" disabled />
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="12">
            <el-form-item label="产品名称" prop="itemName">
              <el-input v-model="form.itemName" readonly="readonly" disabled />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="工序名称" prop="processName">
              <el-input
                v-model="form.processName"
                readonly="readonly"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作中心" prop="workstationName">
              <el-input
                v-model="form.workstationName"
                readonly="readonly"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作业单元名称" prop="workunitName">
              <el-input
                v-model="form.workunitName"
                readonly="readonly"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作单元" prop="workunitId">
              <el-input disabled v-model="form.workunitName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排产数量" prop="quantity">
              <el-input-number
                :step="1"
                :min="0"
                disabled
                v-model="form.quantity"
                placeholder="请输入排产数量"
              />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="12">
            <el-form-item label="生产时长" prop="duration">
              <el-input-number
                :step="1"
                :min="0"
                disabled
                v-model="form.duration"
                placeholder="请输入生产时长"
              />
            </el-form-item>
          </el-col> -->
          <el-col :lg="12" :md="12" :sm="12" :xs="12">
            <el-form-item label-width="130px" label="计划开始时间" prop="scheduleStartDate">
              <el-date-picker
                v-model="form.scheduleStartDate"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择计划开始时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :lg="12" :md="12" :sm="12" :xs="12">
            <el-form-item label-width="130px" label="计划结束时间" prop="scheduleEndDate">
              <el-date-picker
                v-model="form.scheduleEndDate"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择计划结束时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitForm"
          v-if="optType === 'edit'"
          >确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 排程 -->
    <el-dialog
      title="选择编排单"
      :visible.sync="scheduleVisible"
      width="1000px"
      append-to-body
    >
      <order-list v-if="scheduleVisible" ref="orderListRef" @clickTask="clickTask"></order-list>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          :disabled="scheduleBtnDis"
          @click="handleSumbitScheduleList"
          >确 定</el-button>
        <el-button @click="scheduleVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 作业分派 -->
    <el-dialog
      title="作业分派"
      :visible.sync="jobAssignmentVisible"
      width="700px"
      append-to-body
    >
      <el-form :model="Assignform" ref="Assignform" size="small" :inline="true">
        <el-row>
          <el-col :span="24">
            <el-form-item label="排产数量" prop="quantity">
              <el-input-number
                :step="1"
                :min="0"
                v-model="Assignform.quantity"
                placeholder="请输入排产数量"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="工作单元" prop="workunitCode">
              <el-input v-model="Assignform.workunitName" placeholder="工作单元" >
                <el-button slot="append" icon="el-icon-search" @click="$refs.jobAssign.showFlag = true"></el-button>
                </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="AssignList" >
        <el-table-column type="index" label="任务号" width="80" align="center" />
        <el-table-column label="排产数量" width="130" prop="quantity" align="center">
          <template slot-scope="scope">
            <el-input-number
              style="width: 120px"
              :step="1"
              :min="0"
              v-model="scope.row.quantity"
              placeholder="请输入排产数量"
            />
          </template>
        </el-table-column>
        <el-table-column label="工序名称" width="150" prop="processName" />
        <el-table-column label="工作中心" width="150" prop="workstationName" />
        <el-table-column label="工作单元" width="150" prop="workunitName" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="handleCheckJobAssignment"
          >检 查</el-button>
        <el-button
          type="primary"
          @click="handleSubmitJobAssignment"
          >确 定</el-button>
        <el-button @click="jobAssignmentVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 工序新增 -->
    <el-dialog
      title="工序新增"
      :visible.sync="splitVisible"
      width="600px"
      append-to-body
    >
      <el-form :model="splitform" ref="splitform" size="small" :inline="true">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工序名称" prop="processName">
              <el-input v-model="splitform.processName" placeholder="请选择工序" disabled>
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="$refs.brSelectpro.showFlag = true"
                ></el-button>
              </el-input>

            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作单元" prop="workunitCode">
              <el-input v-model="splitform.workunitName" placeholder="请选择工作单元" disabled>
                <el-button slot="append" icon="el-icon-search" @click="showWorkunit"></el-button>
                </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="handleSubmitSplit"
          >确 定</el-button>
        <el-button @click="splitVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 工作单元选择 -->
    <jobAssign ref="jobAssign" :taskId="taskId"  @onSelected="val => onWorkstationSelect(val)"></jobAssign>
    <!-- 工作单元选择 -->
    <splitProcess ref="splitProcess" :processId="splitform.processId"  @onSelected="val => onWorkstationSelect(val)"></splitProcess>
    <!-- 排程 -->
    <el-dialog
      title="详情"
      :visible.sync="arrangCodeVisible"
      width="1000px"
      append-to-body
    >
      <arrangCodeList v-if="arrangCodeVisible" ref="orderListRef" :taskWorkunitId="taskWorkunitId" :arrangeCode="arrangeCode" :isOrder="isOrder"></arrangCodeList>
      <div slot="footer" class="dialog-footer">
        <el-button @click="arrangCodeVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="取消完工"
      :visible.sync="isVisibleTASK"
      width="1000px"
      append-to-body
    >
      <taskList v-if="isVisibleTASK" ref="taskListRef" ></taskList>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isVisibleTASK = false">取 消</el-button>
      </div>
    </el-dialog>
    <ProcessSelect
      ref="brSelectpro"
      @onSelected="onBrandProcess"
    ></ProcessSelect>
    <WorkuintSelect
      ref="WorkunitSelect"
      :workstationId="currentData.workstationId"
      @onSelected="onWorkunitSelect"
    />

  </div>
</template>

<script>
import {
  getListData,
  updateList,
  makeProduction,
  makeSchedule,
  getworkshopList,
  getworkstationList,
  gettaskWorkunitList,
  getdefaultWorkCenterList} from '@/api/mes/pro/scheduleList'
import {putProtaskSplit, splitWorkstation, deleteTask, updateProTaskWorkunitApi} from '@/api/mes/pro/protask'
import BrandSelect from "@/components/TmTool/index.vue";
import shiftSelectMixin from '@/utils/shiftSelectMixin'
import OrderList from './orderList.vue'
import jobAssign from './jobAssign.vue'
import splitProcess from './splitProcess.vue'
import arrangCodeList from './arrangCodeList.vue'
import taskList from './taskList.vue'
import WorkuintSelect from "./workunitSelectSche.vue";
import dayjs from 'dayjs'
import ProcessSelect from "@/components/process/taskSelectSingle.vue";

export default {
  components: {BrandSelect,ProcessSelect, OrderList, arrangCodeList, WorkuintSelect, jobAssign, taskList, splitProcess},
  dicts: ['TASK_STATUS', 'mes_workorder_type'],
  name: "scheduleList",
  mixins: [shiftSelectMixin],
  data() {
    return {
      currentData: {},
      keyValue: 'taskWorkunitId',
      currentTask: null,
      workshopList: [],
      workstationList: [],
      taskWorkunitList: [],
      queryWorkunitParams: {
        workshopId: null,
        workstationId: null
      },
      AssignList: [],
      taskId: null,
      Assignform: {
        quantity: 0,
        workunitName: ''
      },
      scheduleBtnDis: false,
      taskWorkunitId: null,
      arrangCodeVisible: false,
      scheduleVisible: false,
      splitVisible: false,
      splitform: {},
      isOrder: true,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      maintenanceList: [],
      optType: null,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      selectedRows: [],
      workstationId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskCode: null,
        arrangeCode: null,
        arrangeUsername: null,
        workorderCode: null,
        processName: null,
        statusArr: ['PREPARE'],
        scheduleStartDate: null,
        scheduleEndDate: null,
      },
      isVisibleTASK: false,
      editTimeLast: null,
      jobAssignmentVisible: false,
      arrangeCode: null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      timestamp: 0
    };
  },
  created() {
    // this.getList();
    this.hanldeGetdefaultWorkCenterList()
  },
  methods: {
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.taskId);
      this.selectedRows = selection;
      this.multiple = !selection.length;
      if(selection.length !== 1) {
        this.single = true;
      } else {
        this.single = false;
        if(selection[0].status == "CLOSE" || selection[0].status == "FINISHED") {
          this.single = true;
        }
      }
    },
    showWorkunit () {
      if(!this.splitform.processName) return this.$modal.msgError("需要选择工序")
      this.$refs.splitProcess.showFlag = true
    },
    onBrandProcess(row){
     if (Object.values(row).length > 0) {
         this.splitform.processId = row.processId;
          this.splitform.processName = row.processName;
          this.splitform.workunitId = null
          this.splitform.workunitName = null
      }
    },
    handleOpenTask(){
      this.isVisibleTASK = true
    },
    clickTask(arrangeCode){
      this.arrangeCode= arrangeCode
      this.isOrder = true
      this.arrangCodeVisible = true
    },
    handleSubmitJobAssignment() {
      if(!this.Assignform.quantity || this.Assignform.quantity === 0) return this.$modal.msgError("分派任务数量不可为0")
      if(!this.AssignList || this.AssignList.length === 0) return this.$modal.msgError("请先点击检查按钮，检查数据")
      let datas = Object.assign({}, this.selectedRows[0]);
      datas.taskWorkunit = this.AssignList[0];
      delete datas.proWorkorderList;
      delete datas.taskWorkunit.workstationName;
      delete datas.taskWorkunit.processName;
      putProtaskSplit(datas).then((res) => {
        // console.log(res, 'res333')
        if (res.code === 200) {
          this.jobAssignmentVisible = false;
          this.getList();
        }
      });
    },
    handleCheckJobAssignment() {
      if(!this.Assignform.quantity || this.Assignform.quantity === 0) return this.$modal.msgError("分派任务数量不可为0")
      this.AssignList = [{workstationName: this.selectedRows[0].workstationName, processName: this.selectedRows[0].processName, ...JSON.parse(JSON.stringify(this.Assignform))}]
    },
    handleSubmitSplit() {
      let datas = Object.assign({}, this.splitform);
      datas['taskId'] = this.selectedRows[0].taskId
      datas['scheduleStartDate'] = this.selectedRows[0].scheduleStartDate
      datas['scheduleEndDate'] = this.selectedRows[0].scheduleEndDate
      splitWorkstation(datas).then((res) => {
        // console.log(res, 'res333')
        if (res.code === 200) {
          this.splitVisible = false;
          this.getList();
        }
      });
    },
    hanldeGetdefaultWorkCenterList() {
      getdefaultWorkCenterList().then(async (res) => {
        console.log(res, 5566)
        this.hanldeGetworkshopList()
        if (res&&res.length) {
          this.queryWorkunitParams.workshopId = res[0].workshopId
        }
        await this.hanldeGetworkstationList()
        if (this.queryWorkunitParams.workshopId) {
          this.queryWorkunitParams.workstationId = res[0].workstationId? res[0].workstationId: this.workstationList[0].workstationId
          this.hanldeGettaskWorkunitList()
        }
        if(!this.queryWorkunitParams.workshopId) {
          this.queryWorkunitParams.workshopId = this.workshopList[0].workshopId;
          this.queryWorkunitParams.workstationId = this.workstationList[0].workstationId;
          this.hanldeGettaskWorkunitList();
        }
        this.getList();
      });
    },
    async hanldeGetworkshopList() {
      const response = await getworkshopList()
      this.workshopList = response.rows
    },
    handleDeleteTask(){
      this.$modal
        .confirm('是否删除工序')
        .then( ()=> {
          deleteTask(this.selectedRows[0].taskId).then(response => {
            this.$modal.msgSuccess("删除成功");
            this.getList();
          });
        })
    },
    handleVirtualReporting() {
      const params =  {
        taskWorkunitId: this.selectedRows[0].taskWorkunitId,
        virtualFlag: !this.selectedRows[0].virtualFlag,
      }
      updateProTaskWorkunitApi(params).then(response => {
        this.$modal.msgSuccess("更改成功");
        this.getList();
      })
    },
    async handleChangeWorkshopId() {
      // this.workstationList = []
      this.queryWorkunitParams.workstationId = null
      await this.hanldeGetworkstationList()
      this.taskWorkunitList = []
      this.currentTask = null
      this.queryParams.workunitId = ''
      this.getList()
    },
    async hanldeGetworkstationList() {
      let workshopId= this.queryWorkunitParams.workshopId
      const response = await getworkstationList({workshopId: workshopId})
      this.workstationList = response.rows
    },
    handleJobAssignment() {
      this.AssignList = []
      this.Assignform = {
        quantity: 0,
        workunitName: null,
        workunitId: null
      };
      this.workstationId = this.selectedRows[0].workstationId
      this.taskId = this.selectedRows[0].taskId
      console.log('this.selectedRows[0]', this.selectedRows[0])
      this.jobAssignmentVisible = true;
    },
    handleSplitWorkstation() {
      this.splitform = {
        workunitName: null,
        processId: null,
        workunitId: null
      };
      this.workstationId = this.selectedRows[0].workstationId
      this.taskId = this.selectedRows[0].taskId
      this.splitVisible = true;
    },
    handleChangeWorkStationId(item) {
      this.hanldeGettaskWorkunitList()
      const finditem = this.workstationList.find(v => v.workstationId === item)
      if(finditem) {
        this.queryWorkunitParams.workshopId = finditem.workshopId
      }
      this.queryParams.pageNum = 1
      this.queryParams.workunitId = ''
      this.getList()
    },
    // 获取工作单元
    async onWorkunitSelect(row) {
      await this.submitForm({...this.currentData, workunitId: row.workunitId})
      this.$refs['WorkunitSelect'].showFlag = false
    },
    async hanldeGettaskWorkunitList() {
      this.taskWorkunitList = []
      this.currentTask = null
      if (!this.queryWorkunitParams.workstationId) {
        return
      }
      console.log(this.queryWorkunitParams.workstationId, 'this.queryWorkunitParams.workstationId')
      const response = await gettaskWorkunitList({workstationId: this.queryWorkunitParams.workstationId})
      this.taskWorkunitList = response.rows
    },
    onWorkstationSelect(row) {
      if (row != undefined && row != null) {
        if (!this.splitVisible) {
          this.Assignform.workunitId = row.workunitId
          this.Assignform.workunitName = row.workunitName
        } else {
          this.splitform.workunitId = row.workunitId
          this.splitform.workunitName = row.workunitName
        }
      }
    },
    handleClick(row,index) {
      this.currentTask = index
      this.queryParams.workunitId = row.workunitId
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 查询要维护刀模版列表 */
    async getList() {
      // if(this.loading) {
      //   return this.$modal.msgWarning("正在查询中，待查询结果返回后再查询！");
      // }
      this.queryParams.workCenterId = this.queryWorkunitParams.workstationId
      this.queryParams.workshopId = this.queryWorkunitParams.workshopId
      this.loading = true;
      const params = {...this.queryParams}
      if (params.scheduleEndDate&&params.scheduleEndDate.length > 0) {
        params.scheduleEndDateFrom = params.scheduleEndDate[0]
        params.scheduleEndDateTo = params.scheduleEndDate[1]
      }
      if (params.scheduleStartDate&&params.scheduleStartDate.length > 0) {
        params.scheduleStartDateFrom = params.scheduleStartDate[0]
        params.scheduleStartDateTo = params.scheduleStartDate[1]
      }
      delete params.scheduleStartDate
      delete params.scheduleEndDate
      const response = await getListData(params)
      this.maintenanceList = response.rows;
      // this.maintenanceList.forEach(s=>{
      //   s.quantityWait = (s.quantity-s.quantityQualify)|0;
      // })
      this.total = response.total;
      this.loading = false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.opena = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        toolMaintenanceId: null,
        toolMaintenanceCode: null,
        toolId: null,
        maintenanceStatus: null,
        maintenanceType: null,
        itemCode: null,
        toolName: null,
        toolCode: null,
        location: null,
        processId: null,
        processPerson: null,
        lifeTime: null,
        processTime: null,
        startTime: null,
        endTime: null,   };
      this.resetForm("form");
    },
    writeRow(row) {
      this.editTimeLast = JSON.parse(JSON.stringify(row))
    },
    editTime(row, type){
      const scheduleStartDate = dayjs(this.editTimeLast.scheduleStartDate)
      const scheduleEndDate = dayjs(this.editTimeLast.scheduleEndDate)
      if (type === 'start') {
        const duration = scheduleEndDate.diff(scheduleStartDate)
        row.scheduleEndDate = dayjs(row.scheduleStartDate).add(duration).format('YYYY-MM-DD HH:mm:ss')
      } else {
        const duration = scheduleStartDate.diff(scheduleEndDate)
        console.log('duration', duration)
        row.scheduleStartDate = dayjs(row.scheduleEndDate).add(duration).format('YYYY-MM-DD HH:mm:ss')
      }
      this.submitForm(row)
    },
    /** 搜索按钮操作 */
    handleWorkunitQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetWorkunitQuery() {
      this.resetForm("queryWorkunitForm");
      this.handleWorkunitQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if(new Date().getTime() - this.timestamp > 1000) {
        this.timestamp = new Date().getTime();
        this.getList();
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.statusArr = ['UN_ASSIGN']
      this.handleQuery();
    },

    handleBrandSelect(){
      this.$refs.brSelect.showFlag = true;
    },
    /** 新增按钮操作 */
    handleSchedule() {
      this.scheduleVisible = true
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.title = "修改任务单";
      this.form = Object.assign({}, row)
      this.optType = "edit";
      this.open = true;
    },
    //  查询明细按钮操作
    handleView(row){
      this.reset();
      this.title = "查看任务单"
      this.form = Object.assign({}, row)
      this.optType = "view"
      this.open = true
    },
    /** 提交按钮 */
    async submitForm(row) {
      const {scheduleStartDate, scheduleEndDate, taskWorkunitId, workunitId } = row
      const params = {scheduleStartDate, scheduleEndDate, taskWorkunitId, workunitId}
      await updateList(params)
      this.$modal.msgSuccess("修改成功");
      this.getList();
    },
    handleSumbitScheduleList() {
      if (this.$refs.orderListRef.selectedRows&&this.$refs.orderListRef.selectedRows.length > 0) {
        let formData = this.$refs.orderListRef.selectedRows.map(item => {
          return {
            // workorderId: item.workorderId,
            arrangeCode: item.arrangeCode
          }
        });
        this.scheduleBtnDis = true
        const m = this.$message({
          message: '执行中...',
          duration: 0,
          showClose: true,
          type: 'info'
        });
        makeSchedule(formData).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.scheduleVisible = false
          this.scheduleBtnDis = false
          this.getList();
          m.close()
        }).catch(()=>{
          this.scheduleBtnDis = false
          m.close()
        });
      } else {
        this.$modal.msgError("请至少选择一条生产工单")
      }

    },
    handleSumbmitMakeProduction() {
      this.$modal
        .confirm('是否确认下达生产？')
        .then( ()=> {
          if(!(this.ids&&this.ids.length > 0)){
            this.$modal.msgError("请至少选择一条数据")
            return
          }
          let formData = new FormData()
          this.ids.forEach(item => {
            formData.append('taskWorkunitIds', item)
          });
          console.log(this.ids, 'ids')
          makeProduction(formData).then(response => {
            this.$modal.msgSuccess("下达成功");
            this.getList();
          });
        })
        .catch(() => {});
    }
  }
};
</script>

<style lang="scss" scoped>
.cardBox{
  padding: 10px;
  margin-right:30px;
  max-height:600px;
  overflow-y:auto;
  .list{
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    .list-item{
      width: 100%;
      padding: 10px;
      border: 1px solid #eee;
      border-radius: 6px;
      margin-bottom:10px;
      cursor: pointer;
      .item-top{
        font-size:16px;
        font-weight: 600;
      }
      &:nth-child(2n) {
        background:#dfdfdf;
      }
      &:nth-child(2n+1) {
        background:#efefef;
      }
      &:hover{
        background: #85ce61;
        color:#fff;
      }
      &.active{
        background: #85ce61;
        color:#fff;
      }
    }
  }
}
</style>
