<template>
  <div class="page-wrapper">
    <a-row class="page-box">
      <a-col
        class="gutter-row"
        :span="16"
        style="border-right: solid 10px #eef1f4"
      >
        <a-form-model ref="ruleForm" :model="form" :rules="rules">
          <a-collapse
            v-model="activeKey"
            expand-icon-position="right"
            class="collapse-header-divide"
          >
            <a-collapse-panel
              key="a"
              :header="$t('PERSONNEL_ATTEND')"
              :show-arrow="false"
              disabled
            >
              <a-row :gutter="24" type="flex">
                <a-col :span="12">
                  <a-form-model-item :label="$t('SHIFT')" prop="shiftId">
                    <a-select
                      v-model="form.shiftId"
                      :placeholder="$t('PLACESELECT')"
                      @change="onShiftChange"
                    >
                      <a-select-option
                        v-for="(item, index) in classesList"
                        :key="index"
                        :value="item.shiftId"
                      >
                        {{ item.desc_text }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item :label="$t('FAC_SHOP')" prop="fabId">
                    <a-select
                      v-model="form.fabId"
                      :placeholder="$t('PLACESELECT')"
                      @change="onFabChange"
                    >
                      <a-select-option
                        v-for="(item, index) in fabList"
                        :key="index"
                        :value="item.id"
                      >
                        {{ item.fabName }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item :label="$t('FAC_AREA')" prop="areaId">
                    <a-select
                      v-model="form.areaId"
                      :placeholder="$t('PLACESELECT')"
                      @change="onAreaChange"
                    >
                      <a-select-option
                        v-for="(item, index) in areaList"
                        :key="index"
                        :value="item.id"
                      >
                        {{ item.areaName }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    :label="$t('PRODUCTION_LINE')"
                    prop="lineId"
                  >
                    <a-select
                      v-model="form.lineId"
                      :placeholder="$t('PLACESELECT')"
                      @change="onLineChange"
                    >
                      <a-select-option
                        v-for="(item, index) in lineList"
                        :key="index"
                        :value="item.id"
                      >
                        {{ item.lineName }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col v-if="showStation" :span="12">
                  <a-form-model-item
                    v-if="showStation"
                    :label="$t('STATION')"
                    prop="stationId"
                  >
                    <a-select
                      v-model="form.stationId"
                      :placeholder="$t('PLACESELECT')"
                      @change="onLineStation"
                    >
                      <a-select-option
                        v-for="(item, index) in stationList"
                        :key="index"
                        :value="item.id"
                      >
                        {{ item.stationName }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col v-if="showStation" :span="12">
                  <a-form-model-item
                    v-if="showStation"
                    :label="$t('EQP')"
                    prop="eqpId"
                  >
                    <a-input
                      v-model="eqpName"
                      disabled
                      :placeholder="$t('PLACEENTER')"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col v-if="showStation" :span="12">
                  <a-form-model-item
                    v-if="showStation"
                    :label="$t('PRODUCTION_PROCESS')"
                    prop="processId"
                  >
                    <a-input
                      v-model="opName"
                      disabled
                      :placeholder="$t('PLACEENTER')"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    :label="$t('JOB_NUMBER')"
                    prop="attendEmployeeNo"
                  >
                    <a-input
                      v-model="form.attendEmployeeNo"
                      :placeholder="$t('PLACEENTER')"
                      @pressEnter="onChangeInput"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-collapse-panel>
          </a-collapse>
        </a-form-model>
      </a-col>
      <a-col class="gutter-row" :span="8">
        <a-collapse
          v-model="activeKey"
          disabled
          expand-icon-position="right"
          class="collapse-header-divide"
        >
          <a-collapse-panel
            key="a"
            :header="$t('ATTEND_RECORD')"
            :show-arrow="false"
            disabled
          >
            <div class="scroll-box">
              <a-list :data-source="data">
                <a-list-item
                  slot="renderItem"
                  slot-scope="item"
                  style="padding: 24px"
                >
                  <div class="flex justify-between" style="width: 100%">
                    <div class="flex">
                      {{ `${item.no} ${item.name}` }}
                      <p
                        :style="{
                          color: item.type === 'ATTEND' ? '#07B985' : '#FF2727',
                          margin: 0,
                          marginLeft: '5px',
                        }"
                      >
                        {{ ` ${item.status}成功 ` }}
                      </p>
                    </div>
                    <div>{{ `${item.time}` }}</div>
                  </div>
                </a-list-item>
              </a-list>
            </div>
          </a-collapse-panel>
        </a-collapse>
      </a-col>
    </a-row>
  </div>
</template>
<script>
import { mapState } from "vuex";
import moment from "moment";
import ApiConstant from "@/api/ApiConstant";

export default {
  data() {
    return {
      activeKey: "a",
      data: [],
      form: {
        shiftId: "", // 班别 SHIFT
        fabId: "", // 车间 FAC_SHOP
        areaId: "", // 生产区域 FAC_AREA
        lineId: "", // 生产线 PRODUCTION_LINE
        stationId: "", // 工位 STATION
        attendEmployeeNo: "", // 工号 JOB_NUMBER
      },
      isDuty: "",
      showStation: false,
      timer: null,
      shiftDay: "",
      stationList: [],
      classesList: [], // 班别
      fabList: [],
      areaList: [],
      lineList: [],
      fabIdList: [],
      areaIdList: [],
      userInfo: null,
      eqpName: "",
      opName: "",
    };
  },
  computed: {
    ...mapState({
      systemConfig: (state) => state.app.systemConfig,
    }),
    rules() {
      return {
        shiftId: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        fabId: [
          {
            required: false,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        areaId: [
          {
            required: false,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        lineId: [
          {
            required: !this.showStation,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        stationId: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        attendEmployeeNo: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      };
    },
  },
  mounted() {
    const objStr = localStorage.getItem("onDutyObj") || "";
    if (objStr) {
      const onDutyObj = JSON.parse(objStr) || null;
      if (onDutyObj && onDutyObj.timer === new Date().getDate()) {
        this.data = onDutyObj.list;
      } else {
        localStorage.setItem("onDutyObj", "");
      }
    }
    this.init();
    this.getFab();
    this.getClasses();
    this.getStation();
  },
  methods: {
    // 初始化数据
    init() {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/epm/ebs/switch-config/get-config/ENABLE_STATION_ATTEND`
        )
        .then(({ data }) => {
          this.showStation = data.data;
        });
    },
    // 获取车间
    getFab() {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/mdm/fac-fab/list-by-factory-code`,
          { params: { isCancelApiLoad: true } }
        )
        .then((facRes) => {
          const { data } = facRes.data;
          this.fabList = facRes.data.data || [];
          if (data && data.length > 0) {
            data.forEach((item) => {
              this.fabIdList.push(item.id);
            });
            this.getAreaByFab();
          }
        });
    },
    // 获取区域
    getAreaByFab() {
      const params = {
        fabIdList: this.form.fabId || this.fabIdList.join(","),
        isCancelApiLoad: true,
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/mdm/fac-area/list`, { params })
        .then((res) => {
          const { data } = res.data;
          if (data && data.length > 0) {
            this.areaList = res.data.data || [];
            data.forEach((item) => {
              this.areaIdList.push(item.id);
            });
            this.getLineByArea();
          } else {
            this.areaList = [];
            this.lineList = [];
            this.stationList = [];
          }
        });
    },
    // 获取产线
    getLineByArea() {
      const params = {
        areaIdList: this.form.areaId || this.areaIdList.join(","),
        isCancelApiLoad: true,
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/mdm/fac-line/list-by-area-code`, {
          params,
        })
        .then((res) => {
          this.lineList = res.data.data || [];
          if (!this.lineList || this.lineList.length === 0) {
            this.stationList = [];
          }
        });
    },
    // 获取班别
    getClasses() {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/mdm/shift/get-current-and-next`, {
          params: { isCancelApiLoad: true },
        })
        .then(({ data }) => {
          data.data.forEach((item) => {
            const element = item;
            element.desc_text = `${item.shiftDay} / ${item.shiftName}`;
          });
          this.form.shiftId = data.data.length > 0 ? data.data[0].shiftId : "";
          this.shiftDay = data.data.length > 0 ? data.data[0].shiftDay : "";
          this.classesList = data.data;
        });
    },
    getStation() {
      const params = {
        lineId: this.form.lineId || "",
        isCancelApiLoad: true,
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/mdm/fac-station/list`, {
          params,
        })
        .then((res) => {
          this.stationList = res.data.data || [];
        });
    },
    // 獲取设备和工序
    getEqpAndOp(code) {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/epm/ebs/attend/get-attend-base-info/${code}`,
          { params: { isCancelApiLoad: true } }
        )
        .then(({ data }) => {
          if (data.code === 200) {
            this.eqpName = data.data.eqpInfo;
            this.opName = data.data.opInfo;
          }
        });
    },
    // 上岗 离岗
    onDuty() {
      const params = {
        lineId: this.form.lineId,
        shiftId: this.form.shiftId,
        shiftDay: this.shiftDay,
        operateType: "ATTEND",
        attendEmployeeNo: this.form.attendEmployeeNo,
        stationId: this.form.stationId,
      };
      this.$axios
        .post(`${ApiConstant.PREFIX_CORE}/api/epm/ebs/attend`, {
          ...params,
        })
        .then(({ data }) => {
          const obj = {
            name: data.data,
            no: this.form.attendEmployeeNo,
            time: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
            type: "ATTEND",
            status: this.$t("ON_DUTY"),
          };
          this.data.unshift(obj);
          const onDutyObj = {
            timer: new Date().getDate(),
            list: this.data,
          };
          localStorage.setItem("onDutyObj", JSON.stringify(onDutyObj));
          this.form.attendEmployeeNo = "";
          this.$message.success(`${this.$t("ON_DUTY")}${this.$t("SUCCEEDED")}`);
        })
        .catch((res) => {
          if (res.response.data.errorCode === "E0150034") {
            this.getClasses();
          }
        });
    },
    onShiftChange(e) {
      const index = this.classesList.findIndex((item) => item.shiftId === e);
      this.shiftDay = this.classesList[index].shiftDay;
    },
    onFabChange(e) {
      this.getAreaByFab();
      this.form.areaId = "";
      this.form.lineId = "";
      this.form.stationId = "";
      this.eqpName = "";
      this.opName = "";
    },
    onAreaChange(e) {
      this.getLineByArea();
      this.form.lineId = "";
      this.form.stationId = "";
      this.eqpName = "";
      this.opName = "";
    },
    onLineChange(e) {
      this.form.stationId = "";
      this.eqpName = "";
      this.opName = "";
      this.getStation();
      // this.getBtnStatus();
    },
    onLineStation(e) {
      const index = this.stationList.findIndex((item) => item.id === e);
      const code = this.stationList[index].stationCode;
      this.getEqpAndOp(code);
    },
    async onChangeInput() {
      const valid = await this.$refs.ruleForm.validate();
      if (!valid) {
        this.$message.error(this.$t("REQUIRED_INFO"));
      } else {
        this.onDuty();
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.collapse-header-divide {
  /deep/ .ant-collapse-header {
    border-bottom: solid 1px #eef1f4 !important;
    border-radius: 0 !important;
  }
}
/deep/.ant-collapse .ant-collapse-item-disabled > .ant-collapse-header,
.ant-collapse .ant-collapse-item-disabled > .ant-collapse-header > .arrow {
  color: rgba(0, 0, 0, 0.85);
}
.gutter-row {
  position: relative;
  height: 100%;
}
.page-wrapper,
.page-box {
  position: absolute;
  height: 100%;
  width: 100%;
}
.scroll-box {
  overflow-y: scroll;
  overflow-x: hidden;
  height: calc(100vh - 165px);
}
.page-bottom-op {
  bottom: 30px;
  z-index: 10;
  position: absolute;
  text-align: center;
  width: 100%;
}
</style>
