<template>
  <div class="app-container" style="display: flex;">
    <div style="width: 100%;">
       <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="workorderCode">
          <el-input
            v-model="queryParams.workorderCode"
           
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>  
        <el-form-item :label="$t('是否已委外')" prop="outsourced">
          <el-select v-model="queryParams.outsourced" clearable>
            <el-option
                v-for="dict in dict.type.sys_yes_non"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('物料编码')" prop="itemCode">
          <el-input
            v-model="queryParams.itemCode"
           
            clearable
            @keyup.enter.native="handleQuery"
          />
        </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"
          :disabled='multiple'
          @click="handleOpenTask('split')"
        >{{$t('拆分')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          :disabled='multiple'
          @click="handleOpenTask('myself')"
        >{{$t('转自制')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          :disabled='multiple'
          @click="handleOutsource"
        >{{$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('生产工单')" align="center" prop="workorderCode" />
       <el-table-column :label="$t('外协单号')" align="center" prop="taskCode" />
       <el-table-column :label="$t('是否已委外')" align="center" prop="outsourced" >
        <template slot-scope="scope">
          {{scope.row.outsourced ? $t('是') : $t('否')}}
        </template>
       </el-table-column>
       <el-table-column
        :label="$t('物料编码')"
        align="center"
        prop="itemCode"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="$t('物料名称')"
        align="center"
        prop="itemName"
        :show-overflow-tooltip="true"
      />
      <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="outsourceUnitPrice"
          width="180"
      >   <template slot-scope="scope">
              <el-input-number
                  style="width: 150px"
                  :step="1"
                  :min="0"
                  :disabled="scope.row.outsourced"
                  @change="changeoutsourceUnitPrice(scope.row)"
                  v-model="scope.row.outsourceUnitPrice"
              />
          </template>
      </el-table-column>
      <el-table-column
        :label="$t('委外加工商')"
        align="center"
        prop="vendorName"
        width="200"
      >
        <template slot-scope="scope">
          <el-input v-model="scope.row.vendorName"  v-if="!scope.row.outsourced">
              <el-button slot="append" @click="handleSelectVendor(scope.row)" icon="el-icon-search"></el-button>
          </el-input>
          <span v-else>{{
            scope.row.vendorName
          }}</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.outsourced"
            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.outsourced"
            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('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="isVisibleTASK"
      width="1000px"
      append-to-body
    >
      <taskList v-if="isVisibleTASK" ref="taskListRef" :selections="selections" :title="title"></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>
    <VendorSelect ref="vendorSelect" @onSelected="onVendorSelected" />
  </div>
</template>

<script>


import {
  getListData,
  updateList,
  outsourceConfirm} from '@/api/mes/pro/scheduleList'
import VendorSelect from "@/components/vendorSelect/single.vue";
import taskList from './taskList.vue'
import dayjs from 'dayjs'
export default {
  components: {taskList,  VendorSelect},
  dicts: ['sys_yes_non'],
  name: "OutSourceSchedule",
  data() {
    return {
      currentData: {},
      currentTask: null,
      isVisibleTASK: false,
      taskWorkunitList: [],
      queryWorkunitParams: {
        workshopId: null,
        workstationId: null
      },
      taskId: null,
      Assignform: {
        quantity: 1,
        workunitName: ''
      },
      scheduleBtnDis: false,
      taskWorkunitId: null,
      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,
        outsourced: null,
        statusArr: [],
        itemCode: null,
        workorderCode: null,
        scheduleStartDate: null,
        scheduleEndDate: null,
      },
      editTimeLast: null,
      arrangeCode: null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleSelectVendor(row) {
        this.currentData = row
        this.$refs.vendorSelect.showFlag = true;
    },
    toOutsource() {
      this.$refs['taskListRef'].toOutsource().then(res => {
        this.isVisibleTASK = false
        this.getList();
      })
    },
    handleOpenTask(type){
      this.title = type === 'split' ? '拆分' : this.$t('转自制')
      for(let i=0;i<this.selections.length;i++){
        const v = this.selections[i]
        if (v.outsourced) return this.$modal.msgWarning(this.$t('已委外的数据不允许') + this.title);
      }
      this.isVisibleTASK = true
    },
    // 获取工作单元
    async onVendorSelected(row) {
      this.currentData['vendorName'] = row.vendorName
      await this.submitForm({...this.currentData, vendorId: row.vendorId, vendorName: row.vendorName})
      this.$refs['vendorSelect'].showFlag = false
    },
    changeoutsourceUnitPrice(row) {
      this.submitForm(row)
    },
    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, workunitId: 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]
      }
      if (params.outsourced) params.outsourced = Number(params.outsourced)
      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;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.statusArr = []
      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
    },
    /** 提交按钮 */
    async submitForm(row) {
      const {scheduleStartDate, scheduleEndDate, taskWorkunitId, vendorId, vendorName, outsourceUnitPrice } = row
      const params = {scheduleStartDate, scheduleEndDate, taskWorkunitId, vendorId, vendorName, outsourceUnitPrice }
      await updateList(params)
      this.$modal.msgSuccess(this.$t('common.edit_success'));
      this.getList();
    },
    handleOutsource(){
      const arr = this.selections.filter(v => !v.vendorId)
      if (arr && arr.length > 0) return this.$modal.msgWarning(this.$t('委外加工商必选'))
      this.$modal
        .confirm(this.$t('是否确认委外？'))
        .then( ()=> {
          outsourceConfirm(this.ids).then(res => {
            if(res.code === 200) {
              this.$modal.msgSuccess(this.$t('确认委外成功'));
              this.getList();
            }
          })
        })
    }
  }
};
</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>
