<template>
  <a-config-provider :locale="locale">
    <div id="app">
      <a-layout>
        <!-- 顶部信息栏 -->
        <a-layout-header class="border-b" v-if="viewHeader">
          <fe-header
              v-if="headerFlag === 1"
              ref="headerMenu"
              :headerFlag="headerFlag"
              :projectNo="projectNo"
              :performanceModule="performanceModule"
              :versionNO="versionNO"
          />
          <fe-header
            v-if="headerFlag === 2"
            ref="headerMenu"
            :headerFlag="headerFlag"
            :projectNo="projectNo"
            :systemName="systemName"
            :versionNO="versionNO"
          />
          <fe-header
            v-if="headerFlag === 3"
            ref="headerMenu"
            :headerFlag="headerFlag"
            :projectNo="projectNo"
            :componentsName="componentsName"
            :versionNO="versionNO"
          />
        </a-layout-header>
        <a-layout-content class="content">
          <!-- 步骤条 -->
          <div class="step-bar" v-if="viewHeader">
            <a-steps size="small" type="default" v-model="currentStep" @change="onChange">
              <a-step
                  v-for="item in stepsList"
                  :key="item.path"
                  :status="item.status"
              >
                <template slot="title">
                  <div
                    class="titleStyle"
                    :style="{ 'border-color': item.background }"
                  >
                    {{ $t(item.name) }}
                  </div>
                </template>
              </a-step>
            </a-steps>
          </div>
          <!-- 详细内容 -->
          <div class="step-detail">
            <router-view @footerButtonChange="footerButtonChange" v-if="isRouterAlive"/>
          </div>
        </a-layout-content>
        <!-- 步骤条按钮组 -->
        <footer-tool-bar v-if="viewHeader">
          <!-- 提交 -->
          <a-button type="primary" :disabled="!$api.btnPms" :loading="loading" style="margin-right:-12px;" v-if="this.libStep !== 3 && this.libStep !== 0 && !this.footerButtonFlag" @click="toSubmit">
            {{ $t('header.submit') }}
          </a-button>
          <!-- 下一步 -->
          <a-button type="primary" :disabled="!$api.btnPms" :loading="loading" style="margin-right:-12px;" v-if="this.libStep === 0" @click="toSubmit">
            {{ $t('header.next-step') }}
          </a-button>
          <!-- 返回 -->
          <a-button type="danger" :loading="loading" v-if="footerButtonFlag" style="margin-right:-12px; margin-left: 24px" @click="returnToUpper">
            {{ $t('global-btn.return') }}
          </a-button>
        </footer-tool-bar>
      </a-layout>
      <!-- 提交审批 -->
      <submit-approval
          ref='submitApproval'
          :title='submitApprovalTitle'
          :visible='submitApprovalVisible'
          :rfmeaType="'D'"
          @close='submitApprovalVisible = false'
      />
      <!-- 变更内容查看 -->
      <change-content-modal ref="changeContentModal" />
    </div>
  </a-config-provider>
</template>

<script>

import feHeader from "@/layout/header";
import FooterToolBar from '@/components/FooterToolbar';
import { getUrlParam } from "@/common/common";
import utils from '@/utils/urlParamUtil';
import SubmitApproval from '@/components/SubmitApprovalModal';
import ChangeContentModal from "@/components/ChangeManagement/changeManagement";

export default {
  name: 'App',
  components: {
    feHeader,
    FooterToolBar,
    SubmitApproval,
    ChangeContentModal
  },
  data() {
    return {
      isRouterAlive: true,
      currentStep: 0,
      libStep: 0,
      loading: false,
      stepsList: [],
      projectNo: '',
      performanceModule: '',
      systemName: '',
      componentsName: '',
      headerFlag: undefined,
      versionNO: undefined,
      /** 提交审批：标题 */
      submitApprovalTitle: '',
      /** 提交审批：开关 */
      submitApprovalVisible: false,
      // dvp类型 0:整车性能DVP 1:系统DVP 2:零部件DVP"
      dvpType: "",
      // 真实状态
      realLifeState: '',
      // 部门id
      departmentId: undefined,
      // 原始版本id
      mainDvpId: undefined,
      // 数据填写完整标识
      checkDataFlag: false,
      /** 用户权限列表 */
      menuList: [],
      /** 控制header和footer显示隐藏 跳转到403页面需要 */
      viewHeader: true,
      footerButtonFlag: false
    }
  },
  mounted() {
    // 储存mainDvpId
    this.$store.dispatch("dvp/set", {
      key: "mainDvpId",
      value: getUrlParam("mainDvpId")
    });
    // 储存dvpId
    this.$store.dispatch("dvp/set", {
      key: "dvpId",
      value: getUrlParam("dvpId")
    });
    // 储存cpacId
    this.$store.dispatch("dvp/set", {
      key: "cpacId",
      value: getUrlParam("cpacId")
    });

    /**
     * 先初始化步骤条，再获取dvp当前步骤，然后判断用户权限和跳转页面。
     * 以下三个方法顺序不要变：1-initStep，2-getDvpCurrentStep，3-getUserDvpRole
     * 其他的方法随意
     */
    this.initStep();
    this.getDvpCurrentStep();
    this.getUserDvpRole();
    this.initBaseInfo();
    // 查询dvp信息
    this.getDvpInfo();
  },
  computed: {
    locale() {
      return this.$i18n.getLocaleMessage(this.$store.getters.lang).antLocale;
    }
  },
  watch: {
    libStep(val) {
      this.changeStepsStatus(this.$store.getters.dvpId,val);
    },
  },
  methods: {
    /**
     * 获取用户权限并判断是否有权限，有权限，则正常跳转页面，无权限，则跳转到403页面
     * 阻止无权限用户，地址栏输入地址跳转
     */
    getUserDvpRole() {
      this.$api.getUserDvpRole().then(res => {
        if (res.flag) {
         this.menuList = res.data || [];
          // 判断是否拥有整车、系统、零部件DVP的编制权限
          const hasVehiclePermission = this.menuList.some(item => item.permissionCode === 'dvp:fullVehicle:list');
          const hasSystemPermission = this.menuList.some(item => item.permissionCode === 'dvp:systemDVP:list');
          const hasPartPermission = this.menuList.some(item => item.permissionCode === 'dvp:componentsDVP:list');

        // 判断是否跳转403页面
          if ((this.dvpType === '0' && !hasVehiclePermission) ||
              (this.dvpType === '1' && !hasSystemPermission) ||
              (this.dvpType === '2' && !hasPartPermission)) {
            this.viewHeader = false;
            this.$router.push({ name: 'forbiddenAuthority' });
          } else {   // 拥有对应DVP的编制权限，正常跳转页面
            // 改变步骤条状态并跳转到对应页面
            this.changeStepsStatus(this.$store.getters.dvpId, this.currentStep);
          }
        } else {  // 获取用户权限响应失败，跳转403页面
          this.viewHeader = false;
          this.$router.push({ name: 'forbiddenAuthority' });
        }
      });
    },

    /**
     * 获取header信息
     */
    initBaseInfo() {
      // dvpFlag-判断是从整车性能、系统DVP、零部件DVP，哪一个跳转过来的
      let dvpFlag = getUrlParam("from");
      let _that = this;
      let data = {
        dvpId: _that.$store.getters.dvpId
      }
      if (dvpFlag === "fullVehicle") {
        _that.headerFlag = 1;
        _that.$api.initDvpBasicInformation(data).then(res => {
          if (res.flag) {
            _that.projectNo = res.data.projectNo;
            _that.performanceModule = res.data.performanceModuleCode;
            // 储存性能模块
            this.$store.dispatch("dvp/set", {
              key: "performanceModuleCode",
              value: _that.performanceModule
            });
            _that.versionNO = res.data.versionNO.toString();
            _that.storageOwnerInfo(res.data.ownerId,res.data.owner);
          } else {
            _that.$message.error(res.message, 1);
          }
        });
      } else if(dvpFlag === "systemDvp") {
        _that.headerFlag = 2;
        _that.$api.systemDvpBasicInformation(data).then(res => {
          if (res.flag) {
            _that.projectNo = res.data.projectNo;
            _that.systemName = res.data.systemName;
            _that.versionNO = res.data.versionNO.toString();
            _that.storageOwnerInfo(res.data.ownerId,res.data.owner);
          } else {
            _that.$message.error(res.message, 1);
          }
        });
      } else {
        _that.headerFlag = 3;
        _that.$api.getComponentsDvpBasicInformation(data).then( res => {
          if (res.flag) {
            _that.projectNo = res.data.projectNo;
            _that.storageOwnerInfo(res.data.ownerId,res.data.owner);
          } else {
            _that.$message.error(res.message,1);
          }
        });
      }
    },

    /**
     * 初始化步骤条
     */
   initStep(){
      // dvpFlag-判断是从整车性能、系统DVP、零部件DVP，哪一个跳转过来的
      let dvpFlag = getUrlParam("from");
      if (dvpFlag === "fullVehicle"){      // 整车性能
        this.stepsList = [
          {
            // 01 基本信息
            path: "/vehicleInfo",
            name: "header.basic-info",
            status: "wait",
            background: "transparent"
          },
          {
            // 02 DVP计划
            path: "/dvpPlan",
            name: "header.dvp-plan",
            status: "wait",
            background: "transparent"
          },
          {
            // 03 DVP验证
            path: "/dvpVerify",
            name: "header.dvp-verify",
            status: "wait",
            background: "transparent"
          }
        ];
        this.dvpType = "0";
        // 储存dvpType
        this.$store.dispatch("dvp/set", {
          key: "dvpType",
          value: parseInt(this.dvpType,10)
        });
      } else if (dvpFlag === "systemDvp") {         // 系统DVP
        this.stepsList = [
          {
            // 01 基本信息
            path: "/systemDVP",
            name: "header.basic-info",
            status: "wait",
            background: "transparent"
          },
          {
            // 02 DVP计划
            path: "/sysDvpPlan",
            name: "header.dvp-plan",
            status: "wait",
            background: "transparent"
          },
          {
            // 03 DVP验证
            path: "/sysDvpVerify",
            name: "header.dvp-verify",
            status: "wait",
            background: "transparent"
          }
        ]
        this.dvpType = "1";
        // 储存dvpType
        this.$store.dispatch("dvp/set", {
          key: "dvpType",
          value: parseInt(this.dvpType,10)
        });
      } else {                        // 零部件DVP
        this.stepsList = [
          {
            // 01 基本信息
            path: "/componentsDVP",
            name: "header.basic-info",
            status: "wait",
            background: "transparent"
          },
          {
            // 02 DVP计划
            path: "/componentsDvpPlan",
            name: "header.dvp-plan",
            status: "wait",
            background: "transparent"
          },
          {
            // 03 DVP验证
            path: "/componentsDvpVerify",
            name: "header.dvp-verify",
            status: "wait",
            background: "transparent"
          }
        ]
        this.dvpType = "2";
        // 储存dvpType
        this.$store.dispatch("dvp/set", {
          key: "dvpType",
          value: parseInt(this.dvpType,10)
        });
      }

    },

    /**
     * 获取Dvp对应的Step
     */
    getDvpCurrentStep() {
      let data = {
        dvpId: this.$store.getters.dvpId,
        dvpType: this.dvpType
      }
      this.$api.getDvpCurrentStep(data).then(res => {
        if (res.flag){
          this.currentStep = res.data;
          this.libStep = res.data;
          // 如果dvp状态是关闭状态，当前阶段设置为dvp验证
          if (this.currentStep === 3) {
            this.currentStep = 2;
            this.libStep = 2;
          }
        }
      });
    },

    // 改变步骤条状态并跳转
    changeStepsStatus(dvpId, step) {
      this.stepsList.forEach(item => {
        item.background = 'transparent';
      });
      //将当前步骤选中
      let currentStepForPage = step;
        this.stepsList[step].status = "process";
        this.stepsList[step].background = '#1890FF';
      for (let i = 0; i < step; i++) {
        this.stepsList[i].status = "finish";
      }
      // 拿到跳转页面的URL相关信息
      let _from = getUrlParam("from");
      let backUrl = utils.getUrlKey('back');
      let _mainDvpId = this.mainDvpId;
      this.$router.push(
        this.stepsList[currentStepForPage].path +
        "?dvpId=" + dvpId +
        "&mainDvpId=" + _mainDvpId +
        "&from=" + _from +
        "&back=" + backUrl +
        '&ntimet=' + new Date().getTime()
      );
      // 储存dvpId
      this.$store.dispatch("dvp/set", {
        key: "dvpId",
        value: dvpId
      });
    },

    // 进度条切换事件
    onChange(val) {
      if (val <= this.libStep) {
        this.stepsList.forEach(item => {
          item.background = 'transparent';
          item.status = 'wait';
        });
        let stepList = this.stepsList[val];
        this.stepsList[val].background = '#1890FF';
        this.stepsList[val].status = 'process';
        let dvpId = getUrlParam("dvpId");
        let _mainDvpId = this.mainDvpId;
        let _from = getUrlParam("from");
        let backUrl = utils.getUrlKey('back');
        this.$router.push(
          stepList.path + "?dvpId=" + dvpId +
          "&mainDvpId=" + _mainDvpId +
          "&from=" + _from +
          "&back=" + backUrl +
          '&ntimet=' + new Date().getTime()
        );
        this.footerButtonChange(false);
      } else {
        return false;
      }
    },
    // 查询dvp相关信息
    getDvpInfo() {
      let _that = this;
      let from = getUrlParam("from");
      if (from === 'fullVehicle') {
        // 查询dvp相关信息-整车
        let data = {
          dvpId: _that.$store.getters.dvpId
        }
        _that.$api.getFullVehicleDvoList(data).then(res => {
          if (res.flag) {
            let tempData = res.data.data;
            if (tempData) {
              _that.departmentId = tempData[0].departmentId;
              _that.realLifeState = tempData[0].realLifeState;
              _that.mainDvpId = tempData[0].mainDvpId;
            }
          }
        });
      } else if (from === 'systemDvp') {
        // 查询dvp相关信息-系统
        let data = {
          dvpId: _that.$store.getters.dvpId
        }
        _that.$api.getSystemDvpList(data).then(res => {
          if (res.flag) {
            let tempData = res.data.data;
            if (tempData) {
              _that.departmentId = tempData[0].departmentId;
              _that.realLifeState = tempData[0].realLifeState;
              _that.mainDvpId = tempData[0].mainDvpId;
            }
          }
        });
      } else {
        // 查询dvp相关信息-零部件
        let data = {
          dvpId: _that.$store.getters.dvpId
        }
        _that.$api.getComponentsDVPList(data).then(res => {
          if (res.flag) {
            let tempData = res.data.data;
            if (tempData) {
              _that.departmentId = tempData[0].departmentId;
              _that.realLifeState = tempData[0].realLifeState;
            }
          }
        });
      }
    },
    // 提交
    async toSubmit() {
      let _that = this;
      // 如果是基本信息页面，点击提交，不走审批
      if (_that.libStep === 0) {
        let data = {
          dvpId: _that.$store.getters.dvpId,
          dvpFlag: _that.dvpType
        };
        _that.$api.saveDvpCurrentStep(data).then(res => {
          if (res.flag) {
            _that.getDvpCurrentStep();
          } else {
            _that.$message.error(res.message);
          }
        });
      } else {
        // 检验数据是否填写完整
        let frequencyFlag = false; // DVP频次完整标记
        let changeFlag = false; // 变更处理完成标记
        let dvpId = _that.$store.getters.dvpId;
        let materialsEngineerId = undefined; // 材料工程师id
        let testEngineerId = undefined; // 试验工程师id
        await _that.$api.dvpPlanFullCheck({
          dvpId: dvpId,
          dvpType: _that.dvpType
        }).then(res => {
          if (!res.flag) {
            _that.checkDataFlag = false;
            frequencyFlag = res.message === "frequency";
            changeFlag = res.message === "change";
          } else {
            _that.checkDataFlag = true;
            materialsEngineerId = res.data.materialsEngineerId;
            testEngineerId = res.data.testEngineerId;
          }
        });
        if (!_that.checkDataFlag) {
          if (frequencyFlag) {
            _that.$message.warning(_that.$t('dvp.full.vehicle.dvp.dvp-frequency') + _that.$t('dvp.check-data-complete'));
          } else if (changeFlag) {
            _that.$message.warning(_that.$t('dvp.check-change-data-complete'));
            // 变更管理未完成--变更管理处理弹窗
            _that.$refs.changeContentModal.visible = true;
          } else {
            _that.$message.warning(_that.$t('dvp.check-data-complete'));
          }
          return false;
        }
        // 整车dvp验证不走部门审批,直接走下一步
        if (_that.headerFlag === 1 && _that.libStep === 2) {
          let data = {
            dvpId: _that.$store.getters.dvpId,
            dvpFlag: _that.dvpType
          };
          _that.$api.saveDvpCurrentStep(data).then(res => {
            if (res.flag) {
              _that.getDvpCurrentStep();
            } else {
              _that.$message.error(res.message);
            }
          }).finally(() => {
            let back = utils.getUrlKey('back');
            let backUrl = _that.$api.fmUrl + '/#' + back;
            window.open(backUrl, '_top');
          });
        } else {
          _that.$refs.submitApproval.inputArgs.dvpId = _that.$store.getters.dvpId;
          _that.$refs.submitApproval.inputArgs.dvpType = _that.dvpType;
          if (_that.realLifeState === '10') {
            if (_that.headerFlag === 3) {
              // 零部件DVP 计划/验证审批
              _that.submitApprovalTitle = _that.$t('dvp.part-dvp-approval');
              _that.$refs.submitApproval.inputArgs.approveType = '71';
              // 材料工程师
              _that.$refs.submitApproval.inputArgs.materialsEngineerId = materialsEngineerId;
              // 试验工程师
              _that.$refs.submitApproval.inputArgs.testEngineerId = testEngineerId;
            } else if (_that.headerFlag === 2 && _that.libStep === 2) {
              // 系统DVP 验证审批
              _that.submitApprovalTitle = _that.$t('dvp.system-dvp-verify-approval');
              _that.$refs.submitApproval.inputArgs.approveType = '72';
            } else {
              // 部门审批
              _that.submitApprovalTitle = _that.$t('dvp.project-approval');
              _that.$refs.submitApproval.inputArgs.approveType = '70';
            }
          }
          _that.$refs.submitApproval.inputArgs.delayFlag = false;
          _that.submitApprovalVisible = true;
        }
        }
    },
    // 储存Owner信息
    storageOwnerInfo(ownerId,ownerName) {
      // 储存dvpOwnerId
      this.$store.dispatch("dvp/set", {
        key: "dvpOwnerId",
        value: ownerId
      });
      // 储存dvpOwnerName
      this.$store.dispatch("dvp/set", {
        key: "dvpOwnerName",
        value: ownerName
      });
      // 储存ownerDepartmentId
      this.$store.dispatch("dvp/set", {
        key: "ownerDepartmentId",
        value: getUrlParam("departmentId")
      });
    },

    /**
     * 更改底部按钮组显示
     * @param val
     */
    footerButtonChange(val) {
      this.footerButtonFlag = val;
    },

    /**
     *零部件创建试验计划页面，返回零部件DVP计划页面
     */
    returnToUpper() {
      let backUrl = utils.getUrlKey('back');
      this.$router.push({
        path: '/componentsDvpPlan',
        query: {
          dvpId: this.$store.getters.dvpId,
          back: backUrl,
          ntimet: new Date().getTime()
        }
      });
      this.footerButtonFlag = false;
    }
  }
}
</script>

<style lang="less" scoped>
.border-b {
  border-bottom: 1px solid #f0f2f5
}

.content {
  background-color: #f0f2f5;
  overflow-y: hidden;
}

.step-bar {
  height: 48px;
  padding: 12px 66px 12px 66px;
  background-color: #FFFFFF;
  // border-top: 1px solid #1890FF;
}

.step-detail {
  margin-top: 12px;
}

/deep/ .ant-card-body {
  padding: 0;
}

.clear {
  clear: both;
}

.fl {
  float: left;
}

.fr {
  float: right;
}

.zin99 {
  z-index: 99;
}

.mt5 {
  margin-top: 5px;
}

.mt10 {
  margin-top: 10px;
}

.mt15 {
  margin-top: 15px;
}

.mt20 {
  margin-top: 20px;
}

.mt30 {
  margin-top: 30px;
}

.mt40 {
  margin-top: 40px;
}

.mt50 {
  margin-top: 50px;
}

.ml5 {
  margin-left: 5px;
}

.ml10 {
  margin-left: 10px;
}

.ml15 {
  margin-left: 15px;
}

.ml20 {
  margin-left: 20px;
}

.ml30 {
  margin-left: 30px;
}

.ml40 {
  margin-left: 40px;
}

.ml50 {
  margin-left: 50px;
}

.mr5 {
  margin-right: 5px;
}

.mr10 {
  margin-right: 10px;
}

.mr15 {
  margin-right: 15px;
}

.mr20 {
  margin-right: 20px;
}

.mr30 {
  margin-right: 30px;
}

.mr40 {
  margin-right: 40px;
}

.mr50 {
  margin-right: 50px;
}

.mb5 {
  margin-bottom: 5px;
}

.mb10 {
  margin-bottom: 10px;
}

.mb15 {
  margin-bottom: 15px;
}

.mb20 {
  margin-bottom: 20px;
}

.mb30 {
  margin-bottom: 30px;
}

.mb40 {
  margin-bottom: 40px;
}

.mb50 {
  margin-bottom: 50px;
}

.pt5 {
  padding-top: 5px;
}

.pt10 {
  padding-top: 10px;
}

.pt15 {
  padding-top: 15px;
}

.pt20 {
  padding-top: 20px;
}

.pt30 {
  padding-top: 30px;
}

.pt40 {
  padding-top: 40px;
}

.pt50 {
  padding-top: 50px;
}

.pl5 {
  padding-left: 5px;
}

.pl10 {
  padding-left: 10px;
}

.pl15 {
  padding-left: 15px;
}

.pl20 {
  padding-left: 20px;
}

.pl30 {
  padding-left: 30px;
}

.pl40 {
  padding-left: 40px;
}

.pl50 {
  padding-left: 50px;
}

.pr5 {
  padding-right: 5px;
}

.pr10 {
  padding-right: 10px;
}

.pr15 {
  padding-right: 15px;
}

.pr20 {
  padding-right: 20px;
}

.pr30 {
  padding-right: 30px;
}

.pr40 {
  padding-right: 40px;
}

.pr50 {
  padding-right: 50px;
}

.pb5 {
  padding-bottom: 5px;
}

.pb10 {
  padding-bottom: 10px;
}

.pb15 {
  padding-bottom: 15px;
}

.pb20 {
  padding-bottom: 20px;
}

.pb30 {
  padding-bottom: 30px;
}

.pb40 {
  padding-bottom: 40px;
}

.pb50 {
  padding-bottom: 50px;
}

.m0 {
  margin: 0;
}

.m5 {
  margin: 5px;
}

.m10 {
  margin: 10px;
}

.m15 {
  margin: 15px;
}

.m20 {
  margin: 20px;
}

.p0 {
  padding: 0;
}

.p5 {
  padding: 5px;
}

.p10 {
  padding: 10px;
}

.p15 {
  padding: 15px;
}

.p20 {
  padding: 20px;
}

.clickRowStyl {
  background-color: rgb(230, 247, 255);
}

.ant-table-thead > tr > th .ant-table-header-column {
  color: #040B29;
}

.ant-table-tbody > tr > td {
  color: #040B29;
}

.ant-btn .ant-btn-primary {
  border-radius: 4px;
}
.titleStyle {
  border-style: dashed;
  border-width: 1px;
}
</style>
