  <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="ticketName">
        <el-input
          v-model="queryParams.ticketName"
          placeholder="请输入作业票名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备/工艺" prop="machineryId">
        <treeselect
          style="width: 218px"
          v-model="queryParams.machineryId"
          :options="TechnologyOptions"
          :normalizer="Technologynormalizer"
          placeholder="选择设备工艺"
        />
      </el-form-item>
      <el-form-item label="岗位" prop="workstationId">
        <treeselect
          style="width: 218px"
          v-model="queryParams.workstationId"
          :options="marsOptions"
          :normalizer="normalizer"
          placeholder="选择岗位"
        />
      </el-form-item>
      <el-form-item label="状态" prop="ticketStatus">
        <el-select v-model="queryParams.ticketStatus" placeholder="状态">
          <el-option
            v-for="dict in dict.type.ticket_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          style="width: 218px"
          v-model="createTime"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="作业类型" prop="ticketType">
        <el-select
          v-model="queryParams.ticketType"
          placeholder="请选择作业类型"
        >
          <el-option
            v-for="dict in dict.type.ticket_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button v-no-more-click
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button v-no-more-click 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 v-no-more-click
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd('hasSop')"
          v-hasPermi="['mes:job:jobm:add']"
          >新增sop作业票
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-no-more-click
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd('noSop')"
          v-hasPermi="['mes:job:jobm:add']"
          >新增自定义作业票
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-no-more-click
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mes:sop:sopm:batchremove']"
          >批量删除
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="jobList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="作业票名称" align="center" prop="ticketName" width="270"/>
      <el-table-column label="所属岗位" align="center" prop="workstationName">
      </el-table-column>
      <el-table-column label="设备工艺" align="center" prop="machineryName"></el-table-column>
      <el-table-column label="状态" align="center" prop="ticketStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.ticket_status"
            :value="scope.row.ticketStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="作业类型" align="center" prop="ticketType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.ticket_type"
            :value="scope.row.ticketType"
          />
        </template>
      </el-table-column>
      <el-table-column label="隔离点总数" align="center" prop="pointCount">
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button v-no-more-click
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:job:jobm:edit']"
            >编辑
          </el-button>
          <el-button v-no-more-click
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleLook(scope.row)"
            v-hasPermi="['mes:job:jobm:progress']"
            >查看
          </el-button>
          <el-button v-no-more-click
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mes:job:jobm:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  getJobTicketInfo,
  listJobTicket,
  deleteIsJobTicket,
} from "@/api/mes/job/job";

import { genCode } from "@/api/system/autocode/rule";
import { mapActions } from "vuex";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import { listMarsDept } from '@/api/system/marsdept'
import { listTechnology } from '@/api/system/machinery'
export default {
  name: "Team",
  components: { Treeselect },
  dicts: ["ticket_type", "ticket_status"],
  data() {
    return {
      //自动生成编码
      autoGenFlag: false,
      optType: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      codes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班组表格数据
      jobList: [],
      //mars岗位树选项
      marsOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 车间数据
      workshopList: [],
      // 作业区域数据
      workareaList: [],
      // 查询参数
      createTime: "",
      queryParams: {
        current: 1,
        size: 10,
        ticketCode: null,
        ticketName: null,
        ticketStatus: null,
        workshopId: null,
        workareaId: null,
        ticketType: null,
        startTime: "",
        endTime: "",
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      // 表单参数
      form: {},
      TechnologyOptions:[],//设备工艺查询下拉
    //
    };
  },
  created() {
    this.getList();
    this.getOtherList()
  },

  methods: {
    ...mapActions("sopSelectPoints", [
      "setSopEdit",
      "setSopLook",
      "setJobLook",
      "selectSopPoints",
      "PointTableData",
      "PointTableData",
      "setMapData",
      'setVisibleSopSelect'
    ]),
    // 格式化日期查询数据
    formatDate(date) {
      if (date && date instanceof Date && !isNaN(date)) {
        // 使用本地时间
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
          2,
          "0"
        )}-${String(date.getDate()).padStart(2, "0")}`;
      }
      return null;
    },
    /** 查询班组列表 */
    getList() {
      this.loading = true;
      // 格式化日期并更新queryParams
      if (Array.isArray(this.createTime) && this.createTime.length === 2) {
        this.queryParams.startTime = this.formatDate(this.createTime[0]);
        this.queryParams.endTime = this.formatDate(this.createTime[1]);
      }
      listJobTicket(this.queryParams).then((response) => {
        console.log(response, "response--作业票列表");
        this.jobList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });


    },
    getOtherList(){
      const data={
        pasge:1,
        size:-1
      }
      listMarsDept(data).then(response => {
        this.marsOptions = this.handleTree(response.data.records,"workstationId","parentId")
      })
      listTechnology(data).then((response) => {
        this.TechnologyOptions = this.handleTree(response.data.records,"machineryId","parentId")
      })
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.workstationId,
        label: node.workstationName,
        children: node.children,
      };
    },
    Technologynormalizer(node) {
      if (node.children &&!node.children.length) {
        delete node.children;
      }
      return {
        id: node.machineryId,
        label: node.machineryName,
        children: node.children,
      };
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ticketCode: null,
        ticketName: null,
        ticketStatus: null,
        workstationId: null,
        workstationName: null,
        ticketType: null,
        pointCount: null,
        createTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.createTime = "";
      (this.queryParams.startTime = ""),
        (this.queryParams.endTime = ""),

        this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.ticketId);
      this.codes = selection.map((item) => item.ticketCode);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd(val) {
      if(val=='hasSop'){
        this.setVisibleSopSelect(true)
      }else {
        this.setVisibleSopSelect(false)
      }
      this.reset();
      this.open = true;
      this.selectSopPoints(null);
      this.PointTableData(null);
      // this.$router.push(`/mes/job/jobm/NewOperations?ticketId=null`);//黄总原来的作业票新增
      this.$router.push({
        name:'NewMarsJob'
      });
      this.title = "添加隔离点";
      this.optType = "add";
      this.setSopLook(false);
      this.setMapData(null);
    },
    // 查看
    handleLook(row) {
      // 设置为true表示作业票里查看不可以点击隔离点
      this.setSopLook(true);
      this.$router.push(`/mes/job/jobm/lookWork?ticketId=${row.ticketId}`);
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row,'作业票编辑拿到的row');
      this.reset();
      const teamId = row.ticketId || this.ids;
      this.setSopLook(false);
      // 如果编辑的是带有sop模板的 就不允许点击 新增或者删除隔离点

      this.$router.push(
        `/mes/job/jobm/NewOperationsEdit?ticketId=${row.ticketId}`
      );
      getJobTicketInfo(teamId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改隔离点信息";
        this.optType = "edit";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.teamId != null) {
            updateTeam(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTeam(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const teamIds = row.ticketId || this.ids;
      const titcketCodes = row.ticketCode || this.codes;
      this.$modal
        .confirm('是否确认删除作业票编号为"' + titcketCodes + '"的数据项？')
        .then(function () {
          return deleteIsJobTicket(teamIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "cal/team/export",
        {
          ...this.queryParams,
        },
        `team_${new Date().getTime()}.xlsx`
      );
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode("CAL_TEAM_CODE").then((response) => {
          this.form.teamCode = response;
        });
      } else {
        this.form.teamCode = null;
      }
    },
  },
};
</script>
<style lang="scss" src="@/assets/styles/dialog-title.scss" scoped>
.el-input-width {
  width: 380px !important;
}
</style>
