<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="$t('车间')" prop="workshopId">
            <el-select filterable v-model="queryWorkunitParams.workshopId" 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="$t('common.workstation')" prop="workstationId">
            <el-select filterable v-model="queryWorkunitParams.workstationId" 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">{{ $t('common.search') }}</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetWorkunitQuery">{{ $t('common.reset') }}</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;">{{$t('暂无数据')}}</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="$t('任务号')" prop="taskCode">
            <el-input
              v-model="queryParams.taskCode"

              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item :label="$t('工序名称')" prop="processName">
            <el-input
              v-model="queryParams.processName"

              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <!-- <el-form-item :label="$t('common.workunit_name')" prop="workunitName">
            <el-input
              v-model="queryParams.workunitName"

              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item> -->
          <el-form-item :label="$t('common.status')" prop="statusArr">
            <el-select v-model="queryParams.statusArr" multiple 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="$t('工单编码')" prop="workorderCode">
            <el-input
              v-model="queryParams.workorderCode"

              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item :label="$t('项目号')" prop="customerProjectNo">
            <el-input
              v-model="queryParams.customerProjectNo"

              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item :label="$t('订单号')" prop="orderCode">
            <el-input
              v-model="queryParams.orderCode"

              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item :label="$t('计划开始时间段')" label-width="130px" prop="scheduleStartDate">
            <el-date-picker
              v-model="queryParams.scheduleStartDate"
              type="datetimerange"
              :range-separator="$t('至')"
              :start-placeholder="$t('common.start_date')"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
              :end-placeholder="$t('common.end_date')">
            </el-date-picker>
          </el-form-item>
          <el-form-item :label="$t('计划结束时间段')" 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"
              :range-separator="$t('至')"
              :start-placeholder="$t('common.start_date')"
              :end-placeholder="$t('common.end_date')">
            </el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('common.search') }}</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('common.reset') }}</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"
        >{{$t('排程')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          :disabled='single'
          @click="handleJobAssignment"
        >{{$t('作业分派')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          :disabled='multiple'
          @click="handleOpenTask"
        >{{$t('转委外')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          :disabled='multiple'
          @click="handlePrint"
        >{{$t('打印')}}</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">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="$t('任务单编码')" 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="$t('工序名称')"
        align="center"
        prop="processName"
        :show-overflow-tooltip="true"
      />
      <el-table-column :label="$t('排产数量')" align="center" prop="quantity" />
      <el-table-column :label="$t('可加工数量')" align="center" prop="quantityWait"/>
      <el-table-column :label="$t('已完成数量')" align="center" prop="quantityQualify" />
      <el-table-column :label="$t('工单编码')" align="center" prop="workorderCode" />
      <el-table-column
        :label="$t('common.workstation')"
        align="center"
        prop="workstationName"
        width="140"
      />
      <el-table-column
        :label="$t('作业单元名称')"
        align="center"
        prop="workunitName"
        width="200"
      >
        <template slot-scope="scope">
          <el-input v-if="scope.row.status === 'UN_ASSIGN'|| scope.row.status === 'PREPARE'" 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>
          <span v-else>{{
            scope.row.workunitName
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('计划开始时间')"
        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"
            style="width: 100%;"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"

            @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="$t('计划结束时间')"
        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"
            style="width: 100%;"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"

            @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="$t('项目号')" align="center" prop="customerProjectNo"/>
      <el-table-column :label="$t('订单号')" align="center" prop="orderCode"/>
      <!-- <el-table-column
        :label="$t('common.option')"
        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="$t('编号')" 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="$t('工序名称')" prop="processName">
              <el-input
                v-model="form.processName"
                readonly="readonly"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('common.workstation')" prop="workstationName">
              <el-input
                v-model="form.workstationName"
                readonly="readonly"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('作业单元名称')" prop="workunitName">
              <el-input
                v-model="form.workunitName"
                readonly="readonly"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('common.workunit')" prop="workunitId">
              <el-input disabled v-model="form.workunitName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('排产数量')" prop="quantity">
              <el-input-number
                :step="1"
                :min="0"
                disabled
                v-model="form.quantity"

              />
            </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"

              />
            </el-form-item>
          </el-col> -->
          <el-col :lg="12" :md="12" :sm="12" :xs="12">
            <el-form-item label-width="130px" :label="$t('计划开始时间')" 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"

              >
              </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="$t('计划结束时间')" 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"

              >
              </el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('common.remark')" 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'"
          >{{ $t('common.confirm') }}</el-button>
        <el-button @click="cancel">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>

    <!-- 排程 -->
    <el-dialog
      :title="$t('选择生产工单')"
      :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"
          >{{ $t('common.confirm') }}</el-button>
        <el-button @click="scheduleVisible = false">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
    <!-- 作业分派 -->
    <el-dialog
      :title="$t('作业分派')"
      :visible.sync="jobAssignmentVisible"
      width="600px"
      append-to-body
    >
      <el-form :model="Assignform" ref="Assignform" size="small" :inline="true">
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('排产数量')" prop="quantity">
              <el-input-number
                :step="1"
                :min="0"
                v-model="Assignform.quantity"

              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('common.workunit')" prop="workunitCode">
              <el-input v-model="Assignform.workunitName" >
                <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>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="handleSubmitJobAssignment"
          >{{ $t('common.confirm') }}</el-button>
        <el-button @click="jobAssignmentVisible = false">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
    <!-- 工作单元选择 -->
    <jobAssign ref="jobAssign" :taskId="taskId" :workstationId="workstationId" @onSelected="val => onWorkstationSelect(val)"></jobAssign>
    <!-- 排程 -->
    <el-dialog
      :title="$t('详情')"
      :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">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="$t('转委外')"
      :visible.sync="isVisibleTASK"
      width="1000px"
      append-to-body
    >
      <taskList v-if="isVisibleTASK" ref="taskListRef" :selections="selections" ></taskList>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isVisibleTASK = false">{{ $t('common.cancel') }}</el-button>
        <el-button @click="toOutsource">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>
    <WorkuintSelect
      ref="WorkunitSelect"
      :workstationId="currentData.workstationId"
      @onSelected="onWorkunitSelect"
    />

  </div>
</template>

<script>


import {
  getListData,
  updateList,
  makeProduction,
  makeSchedule,
  getworkshopList,
  getworkstationList,
  gettaskWorkunitList,
  getdefaultWorkCenterList,
  printData} from '@/api/mes/pro/scheduleList'
import {putProtaskSplit} from '@/api/mes/pro/protask'
import taskList from './taskList.vue'
import BrandSelect from "@/components/TmTool/index.vue";
import OrderList from './orderList.vue'
import jobAssign from './jobAssign.vue'
import arrangCodeList from './arrangCodeList.vue'
import WorkuintSelect from "./workunitSelectSche.vue";
import dayjs from 'dayjs'
import { postBatchPrintPdf }  from '@/utils/ruoyi'

export default {
  components: {BrandSelect, taskList, OrderList, arrangCodeList, WorkuintSelect, jobAssign},
  dicts: ['TASK_STATUS'],
  name: "scheduleList",
  data() {
    return {
      currentData: {},
      currentTask: null,
      workshopList: [],
      isVisibleTASK: false,
      workstationList: [],
      taskWorkunitList: [],
      queryWorkunitParams: {
        workshopId: null,
        workstationId: null
      },
      taskId: null,
      Assignform: {
        quantity: 1,
        workunitName: ''
      },
      scheduleBtnDis: false,
      taskWorkunitId: null,
      arrangCodeVisible: false,
      scheduleVisible: false,
      isOrder: true,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      maintenanceList: [],
      optType: null,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      selections: [],
      workstationId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskCode: null,
        arrangeCode: null,
        arrangeUsername: null,
        workorderCode: null,
        processName: null,
        customerProjectNo: null,
        orderCode: null,
        statusArr: ['PREPARE'],
        scheduleStartDate: null,
        scheduleEndDate: null,
      },
      editTimeLast: null,
      jobAssignmentVisible: false,
      arrangeCode: null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    // this.getList();
    this.hanldeGetdefaultWorkCenterList()
  },
  methods: {
    toOutsource() {
      this.$refs['taskListRef'].toOutsource().then(res => {
        this.isVisibleTASK = false
        this.getList();
      })
    },
    handleOpenTask(){
      this.isVisibleTASK = true
    },
    clickTask(arrangeCode){
      this.arrangeCode= arrangeCode
      this.isOrder = true
      this.arrangCodeVisible = true
    },
    handleSubmitJobAssignment() {
      let datas = Object.assign({}, this.selections[0]);
      datas.taskWorkunit = this.Assignform;
      delete datas.proWorkorderList;
      putProtaskSplit(datas).then((res) => {
        // console.log(res, 'res333')
        if (res.code === 200) {
          this.jobAssignmentVisible = false;
          this.getList();
        }
      });
    },
    hanldeGetdefaultWorkCenterList() {
      getdefaultWorkCenterList().then(async (res) => {
        res = res.filter(v => v.workstationId !== 1)
        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()
        }
        this.getList()
      });
    },
    async hanldeGetworkshopList() {
      const response = await getworkshopList()
      console.log('response.rows', response.rows)
      this.workshopList = response.rows
    },
    async handleChangeWorkshopId() {
      // this.workstationList = []
      this.queryWorkunitParams.workstationId = null
      // await this.hanldeGetworkstationList()
      this.taskWorkunitList = []
      this.currentTask = null
      this.queryParams.workunitId = ''
      this.getList()
    },
    async hanldeGetworkstationList() {
      const response = await getworkstationList({workshopId: null})
      this.workstationList = response.rows.filter(v => v.workstationId !== 1)
    },
    handleJobAssignment() {
      this.Assignform = {
        quantity: 1,
        workunitName: null,
        workunitId: null
      };
      this.workstationId = this.selections[0].workstationId
      this.taskId = this.selections[0].taskId
      console.log('this.selections[0]', this.selections[0])
      this.jobAssignmentVisible = 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) {
        this.Assignform.workunitId = row.workunitId
        this.Assignform.workunitName = row.workunitName
      }
    },
    handleClick(row,index) {
      this.currentTask = index
      this.queryParams.workunitId = row.workunitId
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 查询要维护刀模版列表 */
    async getList() {
      this.queryParams.workCenterId = this.queryWorkunitParams.workstationId
      this.queryParams.workshopId = this.queryWorkunitParams.workshopId
      this.loading = true;
      const params = {...this.queryParams, neWorkunitId: 1}
      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.total = response.total;
      this.loading = false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.opena = false;
      this.reset();
    },
    handlePrint(){
      const ids = this.selections.map(v => v.taskId)
      printData(ids).then(res => {
        if (res.data) {
          postBatchPrintPdf(
            res.data.reportName,
            res.data.valueList
          ).then(()=> {

          })
        }
      })

    },
    // 表单重置
    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;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.statusArr = ['UN_ASSIGN']
      this.handleQuery();
    },

    handleBrandSelect(){
      this.$refs.brSelect.showFlag = true;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.taskWorkunitId)
      this.selections = selection

      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleSchedule() {
      this.scheduleVisible = true
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.title = this.$t('修改任务单');
      this.form = Object.assign({}, row)
      this.optType = "edit";
      this.open = true;
    },
    //  查询明细按钮操作
    handleView(row){
      this.reset();
      this.title = this.$t('查看任务单')
      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.$t('common.edit_success'));
      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,
            scheduleDate: dayjs(item.scheduleDate).format('YYYY-MM-DD HH:mm'),
            scheduleQuantity: item.scheduleQuantity
          }
        });
        this.scheduleBtnDis = true
        const m = this.$message({
          message: this.$t('执行中...'),
          duration: 0,
          showClose: true,
          type: 'info'
        });
        makeSchedule(formData).then(response => {
          this.$modal.msgSuccess(this.$t('排程成功'));
          this.scheduleVisible = false
          this.scheduleBtnDis = false
          this.getList();
          m.close()
        }).catch(()=>{
          this.scheduleBtnDis = false
          m.close()
        });
      } else {
        this.$modal.msgError(this.$t('请至少选择一条生产工单'))
      }

    },
    handleSumbmitMakeProduction() {
      this.$modal
        .confirm(this.$t('是否确认下达生产？'))
        .then( ()=> {
          if(!(this.ids&&this.ids.length > 0)){
            this.$modal.msgError(this.$t('请至少选择一条数据'))
            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.$t('下达成功'));
            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>
