<template>
  <div class="new-report" v-loading="state.loading" style="min-height:300px">
    <div v-if="!state.error && isShow">
      <div v-loading="dayCompanyLoading">
        <div class="main-title">
          <p class="title">业务公司开票(每日)</p>


          <div style="display: flex;">
            <ElDatePicker style="width:135px" placeholder="日期" v-model="companyDayDate" :clearable="false"
              @change="requestCompanyDay" size="mini" datetype="year" value-format="yyyy-MM-dd" />
          </div>
        </div>
        <el-table size="small" border :data="dayCompany">
          <el-table-column label="业务公司" prop="companyName" width="160px" show-overflow-tooltip />

          <el-table-column label="开票金额" min-width="80px">
            <template slot-scope="scope">
              {{ scope.row.dayinfo.inv_fee }}
            </template>
          </el-table-column>

          <el-table-column label="开票金额(退)" min-width="100px">
            <template slot-scope="scope">
              {{ scope.row.dayinfo.return_inv_fee }}
            </template>
          </el-table-column>

          <el-table-column label="成本金额" min-width="80px">
            <template slot-scope="scope">
              {{ scope.row.dayinfo.cost_fee }}
            </template>
          </el-table-column>

          <el-table-column label="成本金额(退)" min-width="100px">
            <template slot-scope="scope">
              {{ scope.row.dayinfo.return_cost_fee }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-loading="dayCompanyLoading">
        <div class="main-title" style="flex-wrap: wrap;">
          <p class="title">业务公司开票(每月)</p>


          <div style="display: flex;">
            <ElSelect v-model="monthCompanyNo" @change="requestCompanyMonth" size="mini" style="margin-right: 10px">
              <ElOption v-for="comp in companies" :label="comp.companyName" :value="comp.companyNo" />
            </ElSelect>

            <ElDatePicker size="mini" style="width:135px" placeholder="日期" v-model="companyMonthDate" :clearable="false"
              @change="requestCompanyMonth" value-format="yyyy" type="year" />
          </div>
        </div>
        <el-table size="small" border :data="monthCompany">
          <el-table-column label="月份" width="80px" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.year }}-{{ String(scope.row.month).length === '1' ? '0' + scope.row.month : scope.row.month
              }}
            </template>
          </el-table-column>

          <el-table-column label="开票指标" min-width="80px" show-overflow-tooltip prop="inv_tips" />

          <el-table-column label="开票金额" min-width="80px" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.month_info.month_inv_fee }}
            </template>
          </el-table-column>

          <el-table-column label="开票金额(退)" min-width="100px" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.month_info.month_return_inv_fee }}
            </template>
          </el-table-column>

          <el-table-column label="成本指标" min-width="80px" show-overflow-tooltip prop="cost_tips" />

          <el-table-column label="成本金额" min-width="80px" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.month_info.month_cost_fee }}
            </template>
          </el-table-column>

          <el-table-column label="成本金额(退)" min-width="100px" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.month_info.month_return_cost_fee }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-loading="dayAccountLoading">
        <div class="main-title">
          <p class="title">业务经理开票(每日)</p>
          <ElDatePicker style="width:135px" placeholder="日期" v-model="dayDate" :clearable="false"
            @change="requestAccountDay" size="mini" value-format="yyyy-MM-dd" />
        </div>

        <el-table size="small" border :data="dayAccount">
          <el-table-column label="用户" prop="uname" width="100px" show-overflow-tooltip />

          <el-table-column label="开票金额" min-width="80px">
            <template slot-scope="scope">
              {{ scope.row.dayinfo.inv_fee }}
            </template>
          </el-table-column>

          <el-table-column label="开票金额(退)" min-width="100px">
            <template slot-scope="scope">
              {{ scope.row.dayinfo.return_inv_fee }}
            </template>
          </el-table-column>

          <el-table-column label="成本金额" min-width="80px">
            <template slot-scope="scope">
              {{ scope.row.dayinfo.cost_fee }}
            </template>
          </el-table-column>

          <el-table-column label="成本金额(退)" min-width="100px">
            <template slot-scope="scope">
              {{ scope.row.dayinfo.return_cost_fee }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-loading="monthLoading" style="margin-top: 10px">
        <div class="main-title" style="flex-wrap: wrap;">
          <p class="title">业务经理开票(每月)</p>

          <div style="display: flex;justify-self: end;">
            <UserSelect :value.sync="monthUser" :year="monthDate" style="margin-right: 10px"
              @change="requestAccountMonth" @clear="monthAccount = []" />

            <ElDatePicker size="mini" style="width:135px" placeholder="日期" v-model="monthDate" :clearable="false"
              @change="requestAccountMonth" value-format="yyyy" type="year" />
          </div>
        </div>

        <el-table size="small" border :data="monthAccount">
          <el-table-column label="月份" prop="month" width="100px" show-overflow-tooltip />

          <el-table-column label="开票金额" min-width="80px" prop="month_inv_fee" />
          <el-table-column label="开票金额(退)" min-width="100px" prop="month_return_inv_fee" />

          <el-table-column label="成本金额" min-width="80px" prop="month_cost_fee" />
          <el-table-column label="成本金额(退)" min-width="100px" prop="month_return_cost_fee" />
        </el-table>
      </div>





    </div>

    <template v-else-if="!state.loading">
      <unusual-state :hasPermission="isShow" :message="state.message" path="newReport" />
    </template>
  </div>
</template>

<script>
import PeriodDatePicker from "../components/period-date-picker";


import dayjs from "dayjs"
import UnusualState from "@/components/unusual/index.vue";
import { getOpenid, getParameterByName, removeOpenid, setOpenid } from "../utils/auth";
import asyncRequest from "@/api/newResults";

import userRequest from "@/api/index";
import UserSelect from "@/components/userSelect/index.vue"
// import { ElDatePicker } from "element-ui/types/date-picker";


export default {
  name: "invData",
  components: {
    PeriodDatePicker,
    UnusualState,
    UserSelect
  },
  data() {
    return {
      zxTotal: 0,
      isDisplay: false,

      companies: [],


      monthCompanyNo: '',
      companyMonthLoading: false,
      companyMonthDate: '',
      monthCompany: [],

      dayCompanyNo: '',
      companyDayLoading: false,
      companyDayDate: '',
      dayCompany: [],

      monthUser: '',
      monthAccount: [],
      monthLoading: false,
      monthDate: '',

      dayAccountLoading: false,
      dayAccount: [],
      dayDate: '',
      
      state:{
        message: '',
        error: false,
        loading: false
      }
    };
  },
  mounted() {
    document.title = "数据统计"
    if(!getParameterByName('code')){ this.login() }else{
      this.requestUserinfo()
    }
    
    this.dayDate = dayjs(new Date()).format("YYYY-MM-DD")
    this.monthDate = dayjs(new Date()).format("YYYY")
    this.companyDayDate = dayjs(new Date()).format("YYYY-MM-DD")
    this.companyMonthDate = dayjs(new Date()).format("YYYY")

  },
  methods: {
    async requestCompanyDay() {
      this.companyDayLoading = true
      const { data, code } = await asyncRequest.everyCompanyDay({ daytime: this.companyDayDate })
      this.companyDayLoading = false
      if (code === 0) { this.dayCompany = data }
    },
    async requestCompanyMonth() {
      this.companyMonthLoading = true
      const { data, code } = await asyncRequest.everyCompanMonth({ year: this.companyMonthDate, companyNo: this.monthCompanyNo })
      this.companyMonthLoading = false
      if (code === 0) { this.monthCompany = data }
    },
    async requestAccountDay(){
      this.dayAccountLoading = true
      const { data, code } = await asyncRequest.everyAccountDay({ daytime: this.dayDate })
      this.dayAccountLoading = false
      if (code === 0) { this.dayAccount = data }
    },
    async requestAccountMonth() {
      if (this.monthDate !== '2025'){
        console.log('joined', this.monthUser)
        this.monthAccount = []
        return
      }

      this.monthAccountLoading = true
      const { data, code } = await asyncRequest.everyAccountMonth({ year: this.monthDate, uid: this.monthUser })
      this.monthAccountLoading = false
      if (code === 0) { this.monthAccount = data }
    },
    async requestData(){
      this.requestAccountDay()
      // this.requestAccountMonth()
      this.requestCompanyDay()
      this.requestCompanyMonth()
      // const data = await asyncRequest.everyAccountMonth({ year: '2025' })
    },
    async time(e) {
      const { startTime, endTime } = e;
      this.start = startTime || "";
      this.end = endTime || "";

      const { start, end } = this;
      if ((start !== "" && end === "") || (start === "" && end !== "")) {
        this.$message.warning("时间区间不完整！");
        this.date = []
        return;
      }

      if(this.start && this.end){
        this.date = [this.start + " 00:00:00", this.end + " 23:59:59"]
      }else{
        this.date = [this.start, this.end]
      }

    },
    async requestUserinfo(){
       this.state.loading = true;
       const openid = getOpenid()
       const code = getParameterByName('code')
       const result = await userRequest.userinfo({  ...( openid ? { openid } :  { code })  })

      // const result ={
      // "code": 0,
      // "message": "获取成功",
      // "data": {
		  //     "id": "1",
		  //     "openid": "oOpc26KiZFBKIm7SB8knFGvov1qg",
		  //     "mobile": "",
		  //     "gender": "0",
		  //     "nickname": "雪寒",
		  //     "avatar": "",
		  //     "subscribe_time": "2022-12-21 15:52:14",
		  //     "addr": "\/\/",
		  //     "status": "1",
		  //     "is_show": ["1", "2", "4"],
		  //     "companyArr": [{
		  //     	"companyNo": "GS2302231125079621",
		  //     	"companyName": "北京百辰荣达国际科贸有限公司",
		  //     	"info": [1,2]
		  //     }, {
		  //     	"companyNo": "GS2302231323386950",
		  //     	"companyName": "北京泓源广诚国际商贸有限公司",
		  //     	"info": [1,2]
		  //     }, {
		  //     	"companyNo": "GS2304031312553746",
		  //     	"companyName": "北京锦兴弘昌科技有限公司",
		  //     	"info": [1, 2]
		  //     }, {
		  //     	"companyNo": "GS2302231124114965",
		  //     	"companyName": "北京普润心堂商贸有限公司",
		  //     	"info": [1, 2]
		  //     }, {
		  //     	"companyNo": "GS2203161855277894",
		  //     	"companyName": "北京万宇恒通国际科贸有限公司",
		  //     	"info": [1, 2]
		  //     }],
		  //     "addtime": "2023-04-10 18:11:07",
		  //     "updatetime": "2023-05-09 16:22:33"
      // 	}
      // }
      
        this.state.loading = false
        switch(Number(result.code)){
          case 0:
           this.isShow =  (result.data.is_show || []).includes(4) || (result.data.is_show || []).includes('4')
           this.companies = result.data.companyArr.map(item => ({ companyNo: item.companyNo, companyName: item.companyName }))
           this.monthCompanyNo = this.companies[0].companyNo
            this.requestData()
           break
          default:
           this.state.error = true
           this.state.message = result.message
           openid && removeOpenid()
           break
        }
      },
    login(){
      const redirect_url = encodeURIComponent('http://stat.caixiao365.com/accountsReceivable')
      var state = 'wx_' + Math.random().toString(36).substr(2, 15)
      const scope = 'snsapi_userinfo'
      const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${config.appId}&redirect_uri=${redirect_url}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`
      window.location.href = url
    },
  }
}
</script>

<style lang="scss" scoped>
.new-report {
    width: calc(100vw - 20px);
    height: 100vh;
    left: 0px;
    position: fixed;
    overflow: auto;
    padding: 10px;

  .title {
    font-size: 14px;
    margin: 0px;
  }

  /deep/.el-input__prefix{
      height: auto !important;
  }
}

.main-title{
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  margin-top: 10px;
}


</style>

