<template>
  <div class="app-container">
    <el-form :model="queryParams" 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="计划开始时间段" label-width="130px" prop="scheduleStartDate">
            <el-date-picker
              v-model="queryParams.scheduleStartDate"
              type="datetimerange"
              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"
              range-separator="至"
              start-placeholder="开始日期"
              end-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-item label="单据状态" prop="maintenanceStatus">
        <el-select v-model="queryParams.maintenanceStatus" placeholder="请选择单据状态" clearable>
          <el-option
          v-for="dict in dict.TASK_STATUS"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value" />
        </el-select>
      </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"
          @click="handleSumbmitMakeProduction"
        >下达生产</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="任务单编码" 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="编排单号" width="120" prop="arrangeCode">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="taskWorkunitId= scope.row.taskWorkunitId, arrangCodeVisible = true"
            >{{ scope.row.arrangeCode }}</el-button
          >
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="任务单名称"
        width="200"
        align="center"
        prop="taskName"
        :show-overflow-tooltip="true"
      /> -->
      <el-table-column
        label="工作中心"
        align="center"
        prop="workstationName"
        width="140"
      />
      <el-table-column
        label="作业单元名称"
        align="center"
        prop="workunitName"
        width="140"
      />
      <!-- <el-table-column
        label="工艺名称"
        width="200"
        align="center"
        prop="routeName"
        show-overflow-tooltip
      /> -->
      <el-table-column
        label="工序名称"
        align="center"
        prop="processName"
        :show-overflow-tooltip="true"
      />
      <!-- <el-table-column
        label="产品名称"
        width="200"
        align="center"
        prop="itemName"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="单位" align="center" prop="unitOfMeasure" /> -->
      <el-table-column label="排产数量" align="center" prop="quantity" />
      <el-table-column
        label="计划开始时间"
        align="center"
        prop="scheduleStartDate"
        width="180"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.scheduleStartDate, "{y}-{m}-{d} {h}:{i}")
          }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="生产时长"
        align="center"
        prop="duration"
        width="120"
      >
      </el-table-column> -->
      <el-table-column
        label="计划结束时间"
        align="center"
        prop="scheduleEndDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.scheduleEndDate, "{y}-{m}-{d} {h}:{i}")
          }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="需求日期"
        align="center"
        prop="requestDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.requestDate, "{y}-{m}-{d}") }}</span>
        </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"
    />

    <!-- 添加或修改要维护刀模板对话框 -->
    <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"></order-list>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="handleSumbitScheduleList"
          >确 定</el-button>
        <el-button @click="scheduleVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 排程 -->
    <el-dialog
      title="详情"
      :visible.sync="arrangCodeVisible"
      width="1000px"
      append-to-body
    >
      <arrangCodeList v-if="arrangCodeVisible" ref="orderListRef" :taskWorkunitId="taskWorkunitId"></arrangCodeList>
      <div slot="footer" class="dialog-footer">
        <el-button @click="arrangCodeVisible = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {getListData, updateList, makeProduction, makeSchedule} from '@/api/mes/pro/scheduleList'
import BrandSelect from "@/components/TmTool/index.vue";
import OrderList from './orderList.vue'
import arrangCodeList from './arrangCodeList.vue'
export default {
  components: {BrandSelect, OrderList, arrangCodeList},
  dicts: ['TASK_STATUS'],
  name: "scheduleList",
  data() {
    return {
      taskWorkunitId: null,
      arrangCodeVisible: false,
      scheduleVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      maintenanceList: [],
      optType: null,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      selections: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskCode: null,
        processName: null,
        workunitName: null,
        statusArr: ['UN_ASSIGN'],
        scheduleStartDate: null,
        scheduleEndDate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询要维护刀模板列表 */
    getList() {
      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
      getListData(params).then(response => {
        this.maintenanceList = response.rows;
        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");
    },
    /** 搜索按钮操作 */
    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.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
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const {scheduleStartDate, scheduleEndDate, taskWorkunitId, remark} = this.form
          const params = {scheduleStartDate, scheduleEndDate, taskWorkunitId, remark}
          updateList(params).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            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
          }
        });
        makeSchedule(formData).then(response => {
          this.$modal.msgSuccess("排程成功");
          this.scheduleVisible = false
          this.getList();
        });
      } 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>
