<template>
  <div class="workbenchdetail" v-loading="fullLoading">
    <div class="page-main clear">
      <div>
        <div class="left">
          <div class="left-main">
            <div class="left-card" v-if="sitem">
              <div class="page-main-title">需求信息</div>
              <ul class="page-main-ul clear">
                <li>需求单号：</li>
                <li>{{ sitem.reqCode }}</li>
                <!-- <li>任务截止时间：</li>
                <li>{{ sitem.req_endtime }}</li> -->
                <!-- <li>任务剩余时间：</li>
                <li>{{ countdown }}</li> -->
                <li>当前状态：</li>
                <li>{{ (demandStatusOptions.find(item => item.value === String(sitem.status)) || {}).label || '--'  }}</li>
                <li>联系方式：</li>
                <li>{{ sitem.req_tel || "--" }}</li>
              </ul>
            </div>
            <div class="left-card" v-if="sitem">
              <div class="page-main-title">活动要求</div>
              <ul class="page-main-ul clear">
                <li>活动城市：</li>
                <li>{{ sitem.shortname || '--' }}</li>
                <li>活动时间：</li>
                <li>{{ sitem.act_time || '--'}}</li>
                <li>活动类型：</li>
                <li>{{sitem.require_item_name || '--'}}</li>
                <li>活动人数：</li>
                <li>
                  <span v-if="Number(sitem.participant_max) === 0">{{sitem.participant_min}}+</span>
                  <span v-else>{{sitem.participant_min}} ~ {{sitem.participant_max}}</span> 人
                </li>
                <li>项目预算：</li>
                <li>{{ sitem.budget_name || '--'}}</li>
                <li>活动需求：</li>
                <li v-if="sitem && sitem.req_demand_name">
                  {{sitem.req_demand_name.map(({name}) => name).join("+") || '--'}}
                </li>
              </ul>
            </div>
          </div>
        </div>

        <div class="p-right">
           <div style="margin:15px 0px">
             <el-alert
               title="使用说用:"
               type="warning"
               show-icon
               description="评估预算函、计划预算函上传默认为草稿数据,需要发布后客户才能看到!"
               :closable="true"
             />
          </div>

          <div style="margin:15px 0px" v-if="!isNegotiate">
             <el-alert
               title="订单已过磋商阶段，不允许上传方案。"
               type="warning"
               show-icon
               :closable="false"
             />
          </div>

          <el-collapse v-model="actives">
            <el-collapse-item 
              name="1" 
              title="评估预算函" 
              v-if="(String(sitem.status) === '1' || String(sitem.status) === '2') || !isNegotiate">
              <letter
                ref="evaLetter"
                :status="1"
                type="budget"
                :id="sitem.id"
                :isFile="true"
                :isSelection="true"
                :readonly="Number(sitem.status) !== 1 || !isNegotiate"
                @selection="handleSelection($event, 'evalute')"
                @updateLetter="linkToLetterUpdate"
                :requsetMethod="requestBudgetLetter"
                @refresh="refresh('eva')"
                @abnormal="abnormal"
              />
            </el-collapse-item>

            <el-collapse-item 
              name="2"
              title="活动方案管理" 
              v-if="(String(sitem.status) === '2' || String(sitem.status) === '3') || !isNegotiate">
              <letter 
                :status="2"
                ref="actLetter"
                type="activity"
                :id="sitem.id"
                :isFile="true"
                :isSelection="true"
                :readonly="Number(sitem.status) !== 2 || !isNegotiate"
                :beforeModalVisible="beforeActivityModalVisible"
                @selection="handleSelection($event, 'activity')"
                :updateLoading="updateLoading"
                @refresh="refresh('act')"
                @abnormal="abnormal"
              />
            </el-collapse-item>

            <el-collapse-item 
             name="3"
             title="计划预算函管理" 
             v-if="String(sitem.status) === '3' || !isNegotiate">
              <letter
                ref="proLetter"
                :status="3"
                type="project"
                :id="sitem.id"
                :isFile="true"
                :readonly="Number(sitem.status) !== 3 || !isNegotiate"
                @selection="handleSelection($event, 'project')"
                :requsetMethod="requsetProjectLetter"
                :beforeModalVisible="beforeProjectModalVisible"
                :updateLoading="updateLoading"
                @refresh="refresh('pro')"
                @abnormal="abnormal"
              />
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import asyncRequest from "@/apis/service/customerService/workbench";
import baseForm from "./components/baseForm";
import { demandStatusOptions } from '@/assets/js/statusList';
import EvaluteBudgetLetter from "./components/evaluateBudgetLetter/index.vue"
import PlanBudgetLetter from "./components/planBudgetLetter/index.vue"
import ActivityLetter from "./components/activityLetter/index.vue"
import resToken from "@/mixins/resToken";
import { mapGetters } from "vuex";
import dayjs from "dayjs"

export default {
  name: "workbenchDetail",
  components: {
    baseForm,
    ActivityLetter,
    PlanBudgetLetter,
    EvaluteBudgetLetter,
  },
  mixins: [resToken],
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    powers() {
      const tran = this.$store.getters.btnList.find((item) => item.menu_route == "workbenchDetail") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  data() {
    return {
      isNegotiate: true,
      fullLoading:false,
      refreshTimer: null,
      storeId: "",
      demandStatusOptions,
      countdown:'00:00:00',
      timer:null,
      actives:["1","2","3"],
      selected:{
        evalute:[],
        activity:[]
      },
      num: 60,
      timer: null,
      loading: false,
      showModel: false,
      tableData: [],
      baseSitem: {},
      isDetail: false,
      modelId: 0,
      queryId: "",
      status: "",
      sitem: {},
      newTime: "",
      editId: "add",
      editType: "wait",
      planList:[],
      pageInfo:{
        total:0
      },
      parmValue: {
        page: 1,
        size: 100,
        zxNo: "",
        infoNo: "",
        bidNo: "",
        projectNo: "",
        is_own: "1",
      },
    };
  },
  mounted() {
    this.initForm()
    this.regiterRefreshTimer()
  },
  beforeDestroy() {
    this.clearRefreshTimer()
    this.clearTimer()
  },
  methods: {
    async initForm() {
      this.editType = "wait";
      const { id } = this.$route.query;
      this.queryId = id;
      this.loading = true;

      await this.initData();
      this.loading = false;
    },
    async getPageData(){
      await this.initForm()
      const letters = ['evaLetter','actLetter','proLetter']
      letters.forEach(letter => this.$refs[letter] && this.$refs[letter].searchList())
    },
    async abnormal(){
      console.log(111,222);
      await this.getPageData()
      this.clearRefreshTimer()
      this.regiterRefreshTimer()
    },
    regiterRefreshTimer(){
      this.refreshTimer = setInterval(async () => this.getPageData(), 60000)
    },
    clearRefreshTimer(){
      if(!this.refreshTimer) return
      window.clearInterval(this.refreshTimer)
      this.refreshTimer = null
    },
    getTime(value) {
      var secondTime = parseInt(value);// 秒
      var minuteTime = 0;// 分
      var hourTime = 0;// 小时
      if(secondTime > 60) {//如果秒数大于60，将秒数转换成整数
        //获取分钟，除以60取整数，得到整数分钟
        minuteTime = parseInt(secondTime / 60);
        //获取秒数，秒数取余，得到整数秒数
        secondTime = parseInt(secondTime % 60);
        //如果分钟大于60，将分钟转换成小时
        if(minuteTime > 60) {
          //获取小时，获取分钟除以60，得到整数小时
          hourTime = parseInt(minuteTime / 60);
          //获取小时后取余的分，获取分钟除以60取余的分
          minuteTime = parseInt(minuteTime % 60);
        }
      }

      const s = String(secondTime)
      var result = s.length === 1 ? '0' + s : s

      if(minuteTime > 0) {
        const m = String(minuteTime)
        result = "" + (m.length === 1 ? '0' + m : m) + ":" + result;
      }

      if(hourTime > 0) {
        const h =  String(hourTime)
        result = "" + (h.length === 1 ? '0' + h : h) + ":" + result;
      }

      return result;
    },
    async initData() {
      const { code, message, data } = await asyncRequest.detail({
        id: this.queryId
      });
      if (code === 1) {
        this.sitem = data
        const { req_endtime , flow_stage } = this.sitem;

        this.isNegotiate = flow_stage === "磋商阶段"

        this.timer = setInterval(() => {
          let now = dayjs(new Date())
          const minuend = now.diff(req_endtime, 'second')
          this.countdown = minuend < 0 ? this.getTime(Math.abs(minuend)) : '00:00:00'
        },1000) 
        
        this.getNewTime();
      }  else {
        this.$message.warning(message);
      }
    },
    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.num = 0;
      }
    },
    handleSelection(val, key){
      this.selected[key] = val
    },
    getNewTime() {
      this.newTime = new Date().valueOf();
    },
    updateLoading(value){
      this.fullLoading = value
    },
    openModal(bidNo, type) {
      const { id } = this.$route.query;
      this.queryId = id;
      this.editId = bidNo;
      this.editType = type;
      this.getNewTime();
    },
    beforeActivityModalVisible(){
      if(this.selected.evalute.length === 0){
        this.$message.warning('必须选择一个评估预算函')
        return false
      }

      if(this.selected.evalute.length > 1){
        this.$message.warning('只能选择一个评估预算函')
        return false
      }

      if(Number(this.selected.evalute[0].is_check) !== 1){
        this.$message.warning('必须选择被选中的预算函')
        return
      }

      return {
        req_id: this.$route.query.id,
        id: this.selected.evalute[0].id,
        form: 'activity'
      }
    },
    beforeProjectModalVisible(){
      if(this.selected.activity.length === 0){
        this.$message.warning('必须选择一个活动方案')
        return false
      }

      if(this.selected.activity.length > 1){
        this.$message.warning('只能选择一个活动方案')
        return false
      }

      return {
        req_id:this.$route.query.id,
        id: this.selected.activity[0].id,
        form: 'project'
      }
    },
    async refresh(refPrefix){
      const currentRef = refPrefix + 'Letter'
      const letters = ['evaLetter','actLetter','proLetter']
      letters.forEach(letter => letter !== currentRef && this.$refs[letter].searchList())
    },
    async requsetProjectLetter(plan_info, file, store_id){
      const params = {
        file,
        store_id,
        plan_info,
        plan_type: 3,
        req_id:this.sitem.id,
      }

      const result = await asyncRequest.planCreate(params)

      if(result.code === 0){
        this.abnormal()
      }

      return result
    },
    async requestBudgetLetter(plan_info,file, store_id){
      const params = {
        file,
        req_id : this.sitem.id,
        plan_type: 1,
        store_id,
        plan_info
      }

      const result = await asyncRequest.planCreate(params)

      if(result.code === 0){
        this.abnormal()
      }

      return result
    },
  },
};
</script>
<style lang="scss" scoped>
@import "~@/styles/mixin.scss";
.workbenchdetail {
  //
  position: relative;
  width: 100%;
  height: calc(100vh - 50px);
  box-sizing: border-box;
  overflow: hidden;

  .page-main {
    position: relative;
    background: #f2f2f2;
    width: 100%;
    height: calc(100vh - 50px);
    box-sizing: border-box;
    // padding:16px;
    .left {
      position: absolute;
      top: 16px;
      left: 16px;
      width: 280px;
      overflow: hidden;
      height: calc(100vh - 82px);
      .left-main {
        background: rgba(242, 242, 242, 1);
        width: 100%;
        overflow-y: scroll;
        overflow-x: hidden;
        // background: #fff;
        height: calc(100vh - 82px);
        @include scrollBar();
      }
    }
    .p-right {
      top: 16px;
      right: 16px;
      padding:0px 10px 10px 10px;
      width: calc(100% - 318px);
      height: calc(100vh - 96px);
      overflow-y: scroll;
      background: #fff;
      overflow-x: hidden;
      position: absolute;
      @include scrollBar();
      .right-mian-wait {
        .title {
          height: 45px;
          font-size: 17px;
          line-height: 45px;
          box-sizing: border-box;
          padding: 0 16px;
          border-bottom: 1px solid rgba(242, 242, 242, 1);
        }
        .main {
          text-align: center;
          line-height: 180px;
        }
      }
    }
    .bottom {
      position: absolute;
      bottom: 16px;
      right: 16px;
      background: #fff;
      width: calc(100% - 258px);
      height: 180px;
      min-height: 180px;
      overflow-y: scroll;
      overflow-x: hidden;
      @include scrollBar();
      padding: 16px;
    }
    .left-card,
    .right-card,
    .bottom-card {
      background: #fff;
      font-size: 12px;
      // padding:16px;
      line-height: 18px;
      margin: 8px 0 0 0;
      &:first-child {
        margin: 0;
      }
      .page-main-title {
        height: 45px;
        font-size: 17px;
        line-height: 45px;
        box-sizing: border-box;
        padding: 0 16px;
        border-bottom: 1px solid rgba(242, 242, 242, 1);
      }
      .page-main-ul {
        padding: 10px 16px 16px 16px;
        li {
          float: left;
          font-size: 12px;
          line-height: 25px;

          &:nth-child(2n + 1) {
            width: 60px;
            text-align: right;
          }
          &:nth-child(2n + 2) {
            width: calc(100% - 80px);
          }
        }
      }
    }
  }
}

.empty-warning{
  display: flex;
  justify-content: center;
  align-content: center;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  // margin-top: 100px;
}
</style>
