<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item prop="taskCode">
        <el-input
          v-model="queryParams.taskCode"
          placeholder="请输入任务单编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
        <template slot="label">
          <TipLabel title="编码" tip="任务单编码" />
        </template>
      </el-form-item>
      <el-form-item prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务单名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
        <template slot="label">
          <TipLabel title="名称" tip="任务单名称" />
        </template>
      </el-form-item>
      <el-form-item prop="workstationName">
        <el-input
          v-model="queryParams.workstationName"
          placeholder="请输入工作站名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
        <template slot="label">
          <TipLabel title="工作站" tip="工作站名称" />
        </template>
      </el-form-item>

      <el-form-item label="产品编号" prop="itemCode">
        <el-input
          v-model="queryParams.itemCode"
          placeholder="请输入产品编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!-- <el-form-item label="客户编码" prop="clientCode">
        <el-input
          v-model="queryParams.clientCode"
          placeholder="请输入客户编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="clientName">
        <el-input
          v-model="queryParams.clientName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="需求日期" prop="requestDate">
        <el-date-picker
          clearable
          v-model="queryParams.requestDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择需求日期"
        >
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-refresh"
          v-hasPermi="['mes:pro:protask:list']"
          circle=""
          @click="getList"
        ></el-button>
        <el-button
          type="primary"
          icon="el-icon-edit"
          v-hasPermi="['mes:pro:protask:edit']"
          circle=""
          @click="handleOpenGantt"
        ></el-button>
      </el-form-item>
    </el-form>
    <div class="wrapper">
      <div class="container">
        <GanttChar
          class="left-container"
          ref="ganttChar"
          :tasks="tasks"
        ></GanttChar>
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="taskList"
      row-key="taskId"
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <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="200"
        align="center"
        prop="taskName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="工作站名称"
        align="center"
        prop="workstationName"
        width="180"
      />
      <el-table-column
        label="工艺名称"
        width="140"
        align="center"
        prop="routeName"
      />
      <el-table-column
        label="工序名称"
        align="center"
        prop="processName"
        :show-overflow-tooltip="true"
      />
      <!-- <el-table-column
        label="产品编号"
        width="120"
        align="center"
        prop="itemCode"
      /> -->
      <el-table-column
        label="产品名称"
        width="180"
        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"
        width="100px"
        prop="quantityProduced"
      />
      <el-table-column
        label="合格品数量"
        align="center"
        prop="quantityQuanlify"
        width="100"
      />
      <el-table-column
        label="不良品数量"
        align="center"
        width="100px"
        prop="quantityUnquanlify"
      />
      <el-table-column label="调整数量" align="center" prop="quantityChanged" /> -->
      <el-table-column
        label="开始生产时间"
        align="center"
        prop="startTime"
        width="180"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.startTime, "{y}-{m}-{d}:{h}-{m}-{s}")
          }}</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="endTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.endTime, "{y}-{m}-{d}:{h}-{m}-{s}")
          }}</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="生产状态"
        align="center"
        prop="status"
        width="120"
      /> -->
      <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"
            v-if="scope.row.status == 'PREPARE'"
            @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="80px">
        <el-row>
          <el-col :lg="8" :md="8" :sm="12" :xs="12">
            <el-form-item label="编号" prop="taskCode">
              <el-input v-model="form.taskCode" readonly="readonly" disabled />
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="8" :sm="12" :xs="12">
            <el-form-item label="名称" prop="taskName">
              <el-input v-model="form.taskName" readonly="readonly" disabled />
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="8" :sm="12" :xs="12">
            <el-form-item label="产品名称" prop="itemName">
              <el-input v-model="form.itemName" readonly="readonly" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :lg="8" :md="8" :sm="12" :xs="12">
            <el-form-item label="工序名称" prop="processName">
              <el-input
                v-model="form.processName"
                readonly="readonly"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="8" :sm="12" :xs="12">
            <el-form-item label="工作站" prop="workstationName">
              <el-input
                v-model="form.workstationName"
                readonly="readonly"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="8" :sm="12" :xs="12">
            <el-form-item label="工作单元" prop="workunitId">
              <el-input v-model="form.workunitName">
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="$refs['WorkunitSelect'].showFlag = true"
                ></el-button>
              </el-input>
              <WorkuintSelect
                ref="WorkunitSelect"
                :workstationName="form.workstationName"
                @onSelected="onWorkunitSelect"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :lg="8" :md="8" :sm="12" :xs="12">
            <el-form-item label="排产数量" prop="quantity">
              <el-input-number
                :step="1"
                :min="0"
                v-model="form.quantity"
                placeholder="请输入排产数量"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="8" :sm="12" :xs="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                value-format="yyyy-MM-dd hh:mm:ss"
                placeholder="请选择开始时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :md="8" :sm="12" :xs="12">
            <el-form-item label="生产时长" prop="duration">
              <el-input-number
                :step="1"
                :min="0"
                v-model="form.duration"
                placeholder="请输入生产时长"
              />
            </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"
                readonly="readonly"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- <el-steps
        :active="activeProcess"
        v-if="form.taskId != null"
        align-center
        simple
      > -->
      <!-- <el-step
          v-for="(item, index) in processOptions"
          :title="item.itemName"
          :key="item.itemId"
          @click.native="handleStepClick(index)"
        >
        </el-step>
      </el-steps> -->
      <!-- <template v-if="activeProcess == index && form.taskId != null">
        <el-card v-for="(item, index) in processOptions" :key="index">
          <ProTask
            :workorderId="form.taskId"
            :routeId="item.routeId"
            :processId="item.itemId"
            :colorCode="item.colorCode"
            :optType="optType"
          ></ProTask>
        </el-card>
      </template> -->
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="cancel"
          v-if="optType == 'view' || form.status != 'PREPARE'"
          >返回</el-button
        >
        <el-button
          type="primary"
          @click="submitForm"
          v-if="form.status == 'PREPARE' && optType != 'view'"
          >确 定</el-button
        >
        <!-- <el-button
          type="success"
          @click="handleFinish"
          v-if="
            form.status == 'PREPARE' &&
            optType != 'view' &&
            form.workorderId != null
          "
          >完成</el-button
        > -->
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProtask,
  listGanttTaskList,
  getProtask,
  addProtask,
  updateProtask,
  delProtask,
  addProtaskList,
} from "@/api/mes/pro/protask";
import { listProductprocess } from "@/api/mes/pro/routeprocess";
import WorkuintSelect from "@/components/workunitSelect/single.vue";
import ProTask from "./proTask.vue";
import GanttChar from "./ganttx.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Workorder",
  dicts: ["mes_order_status", "mes_workorder_sourcetype"],
  components: {
    Treeselect,
    ProTask,
    GanttChar,
    WorkuintSelect,
  },
  data() {
    return {
      //自动生成编码
      autoGenFlag: false,
      optType: undefined,
      activeProcess: 0,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 任务单表格数据
      taskList: [],
      // 任务单工单树选项
      taskOptions: [],
      //当前生产工单中产品对应的工序列表
      processOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        workorderCode: null,
        workorderName: null,
        workorderType: "SELF", //这里的排产要排除自产之外的外协和外购
        taskCode: null,
        taskId: null,
        taskName: null,
        workstationCode: null,
        workstationName: null,
        workstationid: null,
        orderSource: null,
        sourceCode: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        routeId: null,
        routeName: null,
        routeCode: null,
        processId: null,
        processName: null,
        processCode: null,
        specification: null,
        unitOfMeasure: null,
        quantity: null,
        quantityProduced: null,
        quantityQuanlify: null,
        quantityUnquanlify: null,
        quantityChanged: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        requestDate: null,
        parentId: null,
        ancestors: null,
        startTime: null,
        duration: null,
        endTime: null,
        colorCode: null,
        requestDate: null,
        remark: null,
        status: "PREPARE",
        workunitName: null,
        workunitId: null,
      },
      tasks: {
        data: [],
        links: [],
      },
      // 表单参数
      form: {},
    };
  },
  created() {
    this.getList();
    this.getGanttTasks();
  },
  methods: {
    /** 查询任务单列表 */
    getList() {
      this.loading = true;
      listProtask(this.queryParams).then((response) => {
        this.taskList = this.handleTree(
          response.rows,
          "taskId"
          // "parentId"
        );
        this.total = response.total;
        this.loading = false;
      });
    },
    handleOpenGantt() {
      this.$router.push({ path: "/mes/pro/schedule/ganttedit" });
    },
    getGanttTasks() {
      listGanttTaskList(this.queryParams).then((response) => {
        this.tasks.data = response.data.data;
        this.tasks.links = response.data.links;
        this.$refs.ganttChar.reload();
      });
    },
    // 获取工作单元
    onWorkunitSelect(row) {
      console.log(45456, row);
      if (row != undefined && row != null) {
        this.form.workunitId = row.workunitId;
        this.form.workunitName = row.workunitName;
        console.log(111111, this.form);
      }
    },

    //获取当前产品对应的生产工序
    getProcess() {
      listProductprocess(this.form.itemId).then((response) => {
        this.processOptions = response.data;
      });
    },

    /** 转换任务单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.taskId,
        label: node.taskName,
        children: node.children,
      };
    },
    /** 查询生产工单下拉树结构 */
    getTreeselect() {
      listProtask().then((response) => {
        this.taskOptions = [];
        const data = {
          taskId: 0,
          taskName: "顶级节点",
          children: [],
        };
        data.children = this.handleTree(response.data, "taskId", "parentId");
        this.taskOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        workorderId: null,
        workorderCode: null,
        workorderName: null,
        orderSource: null,
        taskCode: null,
        taskId: null,
        taskName: null,
        workstationCode: null,
        workstationName: null,
        workstationid: null,
        sourceCode: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        routeId: null,
        routeName: null,
        routeCode: null,
        processId: null,
        processName: null,
        processCode: null,
        specification: null,
        unitOfMeasure: null,
        quantity: null,
        quantityProduced: null,
        quantityQuanlify: null,
        quantityUnquanlify: null,
        quantityChanged: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        requestDate: null,
        parentId: null,
        status: "NORMARL",
        startTime: null,
        duration: null,
        endTime: null,
        colorCode: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        workunitName: null,
        workunitId: null,
      };
      this.activeProcess = 0;
      this.autoGenFlag = false;
      this.resetForm("form");
    },
    //甘特图按钮点击
    openGanttChart() {
      this.$refs.ganttChar.showFlag = true;
    },
    //Step点击
    handleStepClick(index) {
      this.activeProcess = index;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //从BOM行中直接新增
    handleSubAdd(row) {
      this.open = false;
      this.reset();
      this.getTreeselect();
      if (row != null && row.taskId) {
        this.form = row;
        this.form.parentId = row.taskId;
        this.form.taskId = null;
        this.form.taskCode = null;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加任务单";
      this.optType = "add";
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.taskId) {
        this.form.parentId = row.workorderId;
        this.form.orderSource = row.orderSource;
        this.form.sourceCode = row.sourceCode;
        this.form.clientId = row.clientId;
        this.form.clientCode = row.clientCode;
        this.form.clientName = row.clientName;
        this.form.workunitName = row.workunitName;
        this.form.workunitId = row.workunitId;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加任务单";
      this.optType = "add";
    },
    // 查询明细按钮操作
    handleView(row) {
      this.reset();
      this.getTreeselect();
      const taskId = row.taskId || this.ids;
      getProtask(taskId).then((response) => {
        this.form = response.data;
        // this.getProcess();
        this.open = true;
        this.title = "查看任务单信息";
        this.optType = "view";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.taskId;
      }
      getProtask(row.taskId).then((response) => {
        this.form = response.data;
        // this.getProcess();
        this.open = true;
        this.title = "生产排产";
        this.optType = "edit";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.taskId != null) {
            updateProtask(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              // this.$refs["bomlist"].getList();
              this.getList();
              this.getGanttTasks();
            });
          } else {
            addProtask(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              //this.open = false;
              this.form.taskId = response.data;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除生产工单编号为"' + row.taskId + '"的数据项？')
        .then(function () {
          return delProtask(row.taskId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    handleSelectProduct() {
      this.$refs.itemSelect.showFlag = true;
    },
    handleSelectClient() {
      this.$refs.clientSelect.showFlag = true;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "mes/pro/protask/export",
        {
          ...this.queryParams,
        },
        `workorder_${new Date().getTime()}.xlsx`
      );
    },
    handleFinish() {
      let that = this;
      this.$modal
        .confirm("是否完成任务单编制？【完成后将不能更改】")
        .then(function () {
          that.form.status = "CONFIRMED";
          that.submitForm();
        });
    },
    //物料选择弹出框
    onItemSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.itemId = obj.itemId;
        this.form.itemCode = obj.itemCode;
        this.form.itemName = obj.itemName;
        this.form.specification = obj.specification;
        this.form.unitOfMeasure = obj.unitOfMeasure;
      }
    },
    //客户选择弹出框
    onClientSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.clientId = obj.clientId;
        this.form.clientCode = obj.clientCode;
        this.form.clientName = obj.clientName;
      }
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode("TASK_CODE").then((response) => {
          this.form.taskCode = response;
        });
      } else {
        this.form.taskCode = null;
      }
    },
  },
};
</script>
<style scoped>
.wrapper {
  height: 400px;
}
.container {
  height: 100%;
  width: 100%;
}
.left-container {
  overflow: hidden;
  position: relative;
  height: 100%;
}
</style>
