<template>
  <div class="newOperations">
    <!--    newOperations盒子开始-->
    <div class="left">
      <!-- 车间 -->
      <SopLeft
        v-if="this.activeName == 'first'"
        @product-line-selected="handleProductLineSelected"
        @work-shop-selected="handleWorkshopSelected"
        :sopProps="sopProps"
      />
      <!-- 隔离点 -->
      <IsolationLeftVue
        v-else
        :points="points"
        @selection-changed="handleSelectPoint"
      />
    </div>
    <div class="right">
      <div class="right_top">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span style="font-size: 18px">{{ this.getSopTitle }}</span>
            <span
              style="
                float: right;
                padding: 1px 0;
                font-size: 22px;
                cursor: pointer;
              "
              type="text"
              @click="goBack"
              >×</span
            >
          </div>
          <div class="text item">
            <el-tabs v-model="activeName" @tab-click="handleClick">
              <el-tab-pane :label="this.getSopTitle" name="first">
                <!-- 新增作业票信息-->
                <el-form ref="form" :model="form" label-width="70px">
                  <el-form-item label="SOP名称" prop="sopName">
                    <el-input
                      v-model="form.sopName"
                      placeholder="请输入SOP名称"
                      style="width: 100%"
                    />
                  </el-form-item>
                  <el-row>
                    <el-col :span="16">
                      <el-form-item label="SOP编号" prop="sopCode">
                        <el-input
                          v-model="form.sopCode"
                          placeholder="请输入SOP编号"
                          style="width: 100%"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label-width="80">
                        <el-switch
                          v-model="autoGenFlag"
                          active-color="#13ce66"
                          active-text="自动生成"
                          @change="handleAutoGenChange(autoGenFlag)"
                        >
                        </el-switch>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-form-item label="SOP类型" prop="sopType">
                    <el-select
                      v-model="form.sopType"
                      placeholder="请选择SOP类型"
                      clearable
                      style="width: 100%"
                    >
                      <el-option
                        v-for="dict in dict.type.sop_type"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="SOP内容" prop="sopContent">
                    <el-input
                      type="textarea"
                      v-model="form.sopContent"
                      :rows="5"
                    ></el-input>
                  </el-form-item>

                  <el-form-item label="" prop="" style="margin-top: 95%">
                    <el-button
                      style="float: right; height: 30px; line-height: 10px"
                      type="primary"
                      @click="nextStep"
                      >下一步</el-button
                    >
                  </el-form-item>
                </el-form>
              </el-tab-pane>
              <el-tab-pane label="选择隔离点" name="second">
                <!-- 隔离点信息-->
                <el-form ref="form" :model="form" label-width="90px">
                  <el-form-item label="车间名称" prop="workshopName">
                    <el-input
                      v-model="form.workshopName"
                      style="width: 100%"
                      disabled
                    />
                  </el-form-item>
                  <el-form-item label="生产线" prop="workline">
                    <el-input
                      v-model="form.workline"
                      style="width: 100%"
                      disabled
                    />
                  </el-form-item>

                  <div class="text item">
                    <p style="color:#606266;font-weight: 600;font-size: 16px">已选隔离点</p>
                    <el-table
                      :data="tableData"
                      stripe
                      height="480"
                      style="width: 100%"
                    >
                      <el-table-column prop="pointId" label="序号" width="60">
                      </el-table-column>
                      <el-table-column prop="pointName" label="已选隔离点">
                        <template slot-scope="scope">
                          <span style="color: #2a87ff">{{
                            scope.row.pointName
                          }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="pointType" label="隔离点类型">
                        <template slot-scope="scope">
                          <dict-tag
                            :options="dict.type.point_type"
                            :value="scope.row.pointType"
                          />
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="powerType"
                        label="危险能量类型"
                        width="100"
                      >
                        <template slot-scope="scope">
                          <dict-tag
                            :options="dict.type.power_type"
                            :value="scope.row.powerType"
                          />
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                  <el-form-item label="" prop="">
                    <el-button
                      style="float: right; height: 30px; line-height: 10px"
                      type="primary"
                      @click="submit"
                      >确 定</el-button
                    >
                    <el-button
                      style="
                        float: right;
                        height: 30px;
                        line-height: 10px;
                        margin-right: 19%;
                      "
                      type="primary"
                      @click="preStep"
                      >上一步</el-button
                    >
                  </el-form-item>
                </el-form>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-card>
      </div>
    </div>
    <!--    newOperations盒子结束-->
  </div>
</template>


<script>
import IsolationLeftVue from "@/components/separationPoint/index.vue";
import SopLeft from "@/components/separationPoint/workshop.vue";
import { genCode } from "@/api/system/autocode/rule";
import {
  addinsertIsSop,
  updateIsSop,
  selectIsSopById,
} from "@/api/mes/sop/sopindex";
import { mapActions, mapGetters } from "vuex";
export default {
  name: "addView",
  dicts: ["power_type", "point_type", "sop_type"],
  components: {
    SopLeft,
    IsolationLeftVue,
  },
  data() {
    return {
      //自动生成编码
      autoGenFlag: false,
      activeName: "first",
      form: {
        sopName: "",
        sopCode: "",
        SOPType: "",
        workshopName: "", //车间名称
        workline: "", //生产线
        workareaName: "",
        spoint: [], //已选隔离点
      },

      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      // 右侧底部已选隔离点
      tableData: [],
      points: null, //车间逆向传递拿到的隔离点数据
      emitWorkShop: null, //车间逆向传递拿到车间相关数据
      sopProps: [], //正传递
    };
  },
  mounted() {
    if (this.$route.query.sopId !== "null") {
      // console.log(this.$route.query.sopId, "接受路由参数");
      this.getSopInfo();
      this.setSopTitle("编辑SOP");
    } else {
      this.setSelectSopPoints([]);
      this.setPointTableData([]);
      this.setSopTitle("新增SOP");
    }
  },
  computed: {
    ...mapGetters("sopSelectPoints", ["getSopTitle"]),
  },
  
  methods: {
    ...mapActions("sopSelectPoints", [
      "setSelectSopPoints",
      "setPointTableData",
      "setSopEdit",
      "setSopTitle",
    ]),
    handleClick(tab, event) {
      // console.log(tab, event);
    },
    preStep() {
      this.activeName = "first";

      this.tableData = [];
      console.log(this.form, "sopform");
    },

    nextStep() {
      this.activeName = "second";
      // console.log("我点击了下一步");
      console.log(
        this.form.workshopName,
        this.form.workline,
        "点击下一步拿到下拉框的数据"
      );
    },

    // 详情数据
    getSopInfo() {
      const sopId = this.$route.query.sopId;
      console.log(this.$route.query.sopId, "接受路由参数");

      if (sopId !== null) {
        selectIsSopById(sopId).then((response) => {
          console.log(response, "详细内容");
          this.form = response.data;
          this.sopProps = [response.data];
          this.tableData = response.data.pointDetailVOList;
          this.title = "修改隔离点信息";
        });
      } else {
        this.title = "新增隔离点信息";
        this.setSopEdit(true);
        this.setSelectSopPoints([]);
        this.setPointTableData([]);
        this.tableData = null;
        this.form = {
          spoint: [],
          sopContent: "",
          sopCode: "",
          sopName: "",
          sopType: "",
          workareaId: "",
          workshopId: "",
        };
        this.autoGenFlag = false;
      }
    },
    submit() {
      // 确保 this.form.spoint 是一个数组，如果为空则默认空数组
      if (!Array.isArray(this.form.spoint)) {
        this.form.spoint = [];
      }

      // 如果没有选中点，逆向传递为空时，使用当前表格数据中的点
      if (this.form.spoint.length === 0 && Array.isArray(this.tableData)) {
        this.form.spoint = this.tableData.map((point) => point.pointId);
      }

      const selectedpointIds = this.form.spoint.join(",");

      const data = {
        pointIds: selectedpointIds,
        sopContent: this.form.sopContent,
        sopCode: this.form.sopCode,
        sopName: this.form.sopName,
        sopType: this.form.sopType,
        workareaId: this.points.value,
        workshopId: this.emitWorkShop.value,
      };

      // 编辑模式
      if (this.$route.query.sopId !== "null") {
        console.log(this.$route.query.sopId, "sopIdaaa");
        // 确保 sopId 存在
        if (!this.form.sopId) {
          console.error("隔离点id不可为空!");
          this.$message.error("隔离点id不可为空!"); // 使用消息提示
          return;
        }

        data.sopId = this.form.sopId;

        updateIsSop(data).then((res) => {
          console.log(res, "修改接口");
          if (res.code == 200) {
            this.$router.push("/sop/sopm");
            this.$message.success("SOP修改成功");
          }
        });
      } else {
        // 新增模式
        addinsertIsSop(data).then((res) => {
          console.log(res, "新增接口");
          if (res.code == 200) {
            this.$router.push("/sop/sopm");
            this.$message.success("SOP新建成功");
          }
        });
      }
    },

    // 子组件选中的隔离点逆传递拿到的数据
    handleSelectPoint(points) {
      // console.log(points, "父组件接收逆向传递选中的隔离点");

      // 使用 Set 来存储传递过来的点值
      const newValues = new Set(points.map((point) => point.pointId));

      // 1. 删除取消选中的点
      this.tableData = this.tableData.filter((item) =>
        newValues.has(item.pointId)
      );

      // 2. 确保新增点不会重复
      const existingValues = new Set(
        this.tableData.map((item) => item.pointId)
      );

      points.forEach((point) => {
        // 如果当前传递的点不在已有的点集中，则添加
        if (!existingValues.has(point.pointId)) {
          this.tableData.push({
            pointName: point.pointName, // 显示的名称
            pointId: point.pointId, // 对应的值
            pointType: point.pointType,
            powerType: point.powerType,
          });
          // 将新点值添加到 Set 中
          existingValues.add(point.value);
        }
      });

      // 更新 form.spoint 为最新选中的隔离点数组
      this.form.spoint = points.map((point) => point.pointId);
    },
    // 车间你逆向传递拿到的隔离点数据产线
    handleProductLineSelected(selectedOption) {
      // console.log(selectedOption, '父组件接收到的 selectedOption');
      this.points = selectedOption;
      this.form.workline = selectedOption.label;
    },
    // 车间子组件逆传递车间相关数据车间
    handleWorkshopSelected(selectedOption) {
      console.log(selectedOption, "handleWorkshopSelected");
      this.emitWorkShop = selectedOption;
      this.form.workshopName = selectedOption.label;
    },

    //自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode("SOP_CODE").then((response) => {
          this.form.sopCode = response;
        });
      } else {
        this.form.sopCode = null;
      }
    },
    // 侧边X关闭
    goBack() {
      this.$router.push("/sop/sopm");
    },
    //   methods结束
  },
};
</script>



<style scoped lang="scss">
.newOperations {
  width: 99%;
  height: 100%;
  // background: pink;
  margin: 10px;
  display: flex;
  .left {
    width: 75%;
    height: 830px;
    background: #eee;
    margin-right: 10px;
  }
  .right {
    flex: 1;
    .right_top {
      height: 540px;
    }
  }
}
//右侧卡片样式开始
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;

  p {
    font-size: 18px;
    font-weight: bolder;
    font-family: SourceHanSansSC-bold;
  }
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
  width: 320px;
}
.clearfix:after {
  clear: both;
}

.box-card {
  // width: 390px;
  width: 95%;
  height: 820px;
}

::v-deeep .el-tabs--top .el-tabs__item.is-top:nth-child(2),
.el-tabs--top .el-tabs__item.is-bottom:nth-child(2),
.el-tabs--bottom .el-tabs__item.is-top:nth-child(2),
.el-tabs--bottom .el-tabs__item.is-bottom:nth-child(2) {
  padding-left: 100px !important;
}
::v-deep .el-tabs .el-tabs__item {
  padding: 0 50px !important;
}

//右侧卡片样式结束
</style>
<style>
</style>
