<template>
  <div class="bargainListDetail">
    <div class="bargainListDetail-main">
      <el-tabs v-model="projectTabs" v-loading="loading">
        <el-tab-pane label="需求订单详情" name="1">
          <el-collapse v-model="activeNames" style="margin: -18px 0 0 0">
           <el-collapse-item title="需求订单详情" name="1">
             <demand-detail :sitem="sitem" @refresh="refresh" @switchNode="handleSwitchNode" />
           </el-collapse-item>

           <el-collapse-item :title="Number(sitem.status) > 1 ? '评估预算函' :'评估预算函管理'" name="2" v-if="Number(sitem.status) >= 1">
             <manage-budgeet-letter
              :sitem="sitem" 
              :readonly="Number(sitem.status) > 1"
              @selectedChange="handleSelectedChange($event,'budget')" 
            />
           </el-collapse-item> 

           <el-collapse-item :title="Number(sitem.status) > 2  ? '活动方案' :'活动方案管理'" name="3" v-if="Number(sitem.status) >= 2">
             <manage-activity-scheme 
              :sitem="sitem" 
              :readonly="Number(sitem.status) > 2"
              @selectedChange="handleSelectedChange($event,'activity')"
            />
           </el-collapse-item> 
           
           <el-collapse-item :title="Number(sitem.status) > 3 ? '计划预算函' : '计划预算函管理'" name="10" v-if="Number(sitem.status) >= 3">
             <manage-project-letter
              :sitem="sitem" 
              :readonly="Number(sitem.status) > 3"
              @selectedChange="handleSelectedChange($event,'project')" 
            />
           </el-collapse-item> 
           
           <!-- 审批时查看凭证 驳回可以重新上传凭证 -->
           <el-collapse-item 
              v-if="Number(sitem.status) === 4 || Number(sitem.status) === 8"
              :title="Number(sitem.status) > 4 && Number(sitem.status) !== 8 ? '凭证图片' : '待客户上传确认凭证'" 
              name="4"
            >
              <credentials-node
                :readonly="Number(sitem.status) !== 4 && Number(sitem.status) !== 8"
                :url="sitem.ReqProof ? sitem.ReqProof.filter(({user_type}) => user_type === 1).map(({proof_url}) => proof_url) : ''"
                @confirm="handleCustomerConfirm($event)" 
              />
           </el-collapse-item>

           <el-collapse-item title="待平台审核执行凭证" name="5" v-if="Number(sitem.status) === 5">
             <wait-execute-certificate :sitem="sitem" @refresh="initData" />
           </el-collapse-item>
           
           <el-collapse-item title="待供应商确认已执行" name="6" v-if="Number(sitem.status) === 6">
             <wait-supplier-confirm :sitem="sitem" @refresh="initData"  />
           </el-collapse-item> 
           
           <el-collapse-item title="待客户确认已执行" name="7" v-if="Number(sitem.status) === 7">
             <wait-customer-confirm :sitem="sitem" @refresh="initData" />
           </el-collapse-item>
           
          <el-collapse-item 
            :title="Number(sitem.status) >= 9 && Number(sitem.status) !== 11 ? '结算函' : '待客户上传结算函'"
             v-if="Number(sitem.status) >= 9"
             name="8" 
          >
             <letter 
              :id="sitem.id" 
              type="settlement" 
              ref="letter"
              status="4"
              :readonly="Number(sitem.status) > 9 && Number(sitem.status) !== 11"
              :requsetMethod="handleUploadLetter" 
              @publish-ok="refresh"
              :isFile="true" 
            />
           </el-collapse-item> 
           
           <el-collapse-item title="待客户确认结算函" name="9" v-if="Number(sitem.status) === 10">
             <normal-node @confirm="handleConfirmSettlement" />
           </el-collapse-item>
          </el-collapse>
        </el-tab-pane>
       </el-tabs>
    </div>
  </div>
</template>
<script>
import asyncRequest from "@/apis/service/customerService/demandOrder";
import privateField from '@/mixins/privateField'
import DemandDetail from "./components/demandDetail/index.vue"
import ManageBudgeetLetter from "./components/manageBudgetLetter.vue"
import ManageProjectLetter from "./components/manageProjectLetter.vue"
import WaitSupplierConfirm from "./components/waitSupplierConfirm.vue"
import WaitCustomerConfirm from "./components/waitCustomerConfirm.vue"
import SettlementLetter from "./components/settlementLetter/index.vue"
import ManageActivityScheme from "./components/manageActivityScheme.vue"
import WaitExecuteCertificate from "./components/waitExecuteCertificate.vue"

import { mapGetters } from "vuex";
import { statusList } from "./columns";
import resToken from "@/mixins/resToken";

export default {
  components: { 
    DemandDetail, 
    SettlementLetter,
    ManageProjectLetter,
    ManageBudgeetLetter, 
    WaitSupplierConfirm, 
    WaitCustomerConfirm, 
    ManageActivityScheme, 
    WaitExecuteCertificate
  },
  name: "demandOrderDetail",
  mixins: [resToken, privateField],
  computed: {
    ...mapGetters([
      "tablebtnSize", 
      "searchSize",
      "private_field", 
      "isSupertube",
      "size",
    ]),
    powers() {
      const { btnList } = this.$store.getters;
      const tran = btnList.find((item) => item.menu_route == "demandOrderDetail") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
    ppowers() {
      const { roleProcess } = this.$store.getters;
      const tran = roleProcess.find((i) => i.process_type === "YJD") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },

  data() {
    return {
      selected: {
        budget: 0,
        activity: 0,
        project:0
      },
      size: "small",
      statusList,
      projectTabs: "1",
      activeNames: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9","10", "20"],
      newTime: "",
      loading: false,
      queryType: "",
      queryId: "",
      status: "",
      sitem: {},

      orderItem: {},
      moneyDirItem: {},
      moneyItem: {},
      BossItem: {},
    };
  },
  mounted() {
    this.initForm();
  },
  methods: {
    handlePlatExec(data){
      console.log(data)
    },
    handleUploadCredentials(data){
      console.log(data)
    },
    async initForm() {
      const { id, type } = this.$route.query;
      this.queryId = id;
      this.queryType = type;
      this.projectTabs = "1";
      this.loading = true;
      await this.initData();
      this.loading = false;
    },
    handleSelectedChange(val,key){
      this.selected[key] = val
      console.log(val)
    },
    handleClick(row) {
      console.log(row);
    },
    async refresh() {
      this.initData()
    },
    async initData() {
      this.loading = true;
      const { code, message, data } = await asyncRequest.detail({
        id: this.queryId,
      });
      this.loading = false;
      if (code === 1) {
        this.sitem = JSON.parse(JSON.stringify(data));
        this.getNewTime();
      } else {
        this.$message.warning(message);
      }
    },
    getNewTime() {
      this.newTime = new Date().valueOf();
    },
    async handleSwitchNode(mode){
      const minuend = mode === 'next' ? 1 : -1
      const updatedStatus = this.sitem.status + minuend

      console.log(this.selected)
      
      if(mode === 'next'){
        if(updatedStatus === 2 && this.selected.budget === 0){
          this.$message.warning('未选择评估预算函')
          return
        }

        if(updatedStatus === 3 && this.selected.activity === 0){
          this.$message.warning('未选择活动方案')
          return
        }

        if(updatedStatus === 4 && this.selected.project !== 1){
          const warn = this.selected.project === 0 ? '未选择计划预算函' : '只能选一个计划预算函'
          this.$message.warning(warn)
          return
        }
      }

      const { code } = await asyncRequest.checkNode({id: this.sitem.id, status: updatedStatus })
      if(code !== 1) return
      this.initForm()
    },
    async handleUploadLetter(plan_info, file, store_id){
      const params = {
        req_id: this.sitem.id,
        plan_type: 4,
        plan_info,
        store_id,
        file,
      }

      const { code, msg, data } = await asyncRequest.planCreate(params)
      
      if(code === 1){
        this.initData()
      } 

      return {
        code,
        data,
        msg
      }
    },
    async handleCustomerConfirm(data){
      const { credentials: proof_url  } = data
      const { code } = await asyncRequest.proofCheck({ id: this.sitem.id,proof_url, status: 5 })
      if(code !== 1) return
      this.initData()
    },
    async handleSupplierConfirm(data){
      const { credentials: proof_url  } = data
      const { code } = await asyncRequest.proofCheck({ id: this.sitem.id,proof_url, status: 7  })
      if(code !== 1) return
      this.initData()
    },
    async handleConfirmSettlement(data){
      const { code } = await asyncRequest.status({ id:this.sitem.id, ...data, status:data.status === '1' ? '12' : '11' })
      if(code !== 1) return
      await this.initData() 
      // letter
      this.$refs.letter.searchList()
    },
    async statusSubmit(model, title) {
      if (model.status === "0") model.status = "2";
      const { code, message } = await asyncRequest.status(model);
      this.loading = false;
      if (code === 0) {
        this.$notify.success({ title: title + "成功！", message: "" });
        await this.initForm();
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(message);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.bargainListDetail {
  position: relative;
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  .bargainListDetail-main {
    position: relative;
    padding: 10px;
    height: 100%;
    width: 100%;
  } 
  .bargainListDetail-title {
    border-top: 1px solid #ebeef5;
    span {
      height: 50px;
      line-height: 50px;
      font-family: "微软雅黑", sans-serif;
      font-weight: 400;
      font-style: normal;
      font-size: 16fpx;
      text-align: left;
    }
  }
  /deep/ .ddiv {
    border-top: 1px solid #dcdfe6;
  }
  /deep/ .dtitle {
    width: 40px;
    text-align: center;
    height: 100%;
    min-height: 100%;
    ul {
      padding: 12px 0 0 0;
    }
  }
  /deep/ .dmain {
    padding: 20px 0 0 0;
    width: calc(100% - 40px);
    border-left: 1px solid #dcdfe6;
  }
}
</style>
