<template>
  <div v-loading="loading">
    <div class="search clear" style="align-items: center;">
      <span style="font-size: 15px;">结算单E企购-月度完成情况</span>

      <div style="float:right">
        <el-date-picker 
          class="fr picker no-padding" 
          v-model="daytime" 
          style="width:95px" 
          value-format="yyyy-MM-dd"
          :editable="false" 
          :disabled="isEmpty" 
          :clearable="false" 
          :size="'small'" 
          format="yyyy-MM-dd" 
          type="date"
          align="right" 
          placeholder="选择日期"
          :picker-options="{ disabledDate: time => time.getTime() > Date.now() }"
          @change="requestData"
        />
      </div>
    </div>

    <el-row style="margin-top:10px;margin-top:10px" v-if="!isEmpty">
      <el-table 
        border 
        size="mini" 
        :data="[...totalAmount, ...selfSupport.companyArr, ...otherSupport.companyAmount]"
        :header-cell-class-name="setHeaderClassName"
        :cell-class-name="setCellClassName"
        row-key="companyNo"
        :load="load"
        lazy
       >
       <el-table-column type="" fixed="left" label="" prop="order_type" align="center" width="120px">
        <template slot-scope="scope">
          {{ scope.row.order_type }}
        </template>
       </el-table-column>


        <el-table-column label="公司" prop="companyName" align="center" width="120px">
          <template slot-scope="scope">
            <span v-if="scope.row.companyName.indexOf('合计-') === -1">
              {{ mapCompany2[scope.row.companyName] || scope.row.companyName }}
            </span>
            <span v-else>
              元隆雅图
            </span>
          </template>
        </el-table-column>


        <el-table-column label="当日营业收入" align="center" width="95px">
          <template slot-scope="scope">
            {{ 
                isAmountProp(scope.row.companyName) 
                  ? unit2TenThousand(calcAmount('sale_total', scope.row.companyNo), isTenThound)  
                  : unit2TenThousand(scope.row.sale_total, isTenThound) 
            }}
          </template>
        </el-table-column>

          <el-table-column label="营收目标" align="center" min-width="95px">
            <template slot-scope="scope">
              {{ 
                isAmountProp(scope.row.companyName)
                  ? unit2TenThousand(calcAmount('total_tips',scope.row.companyNo), isTenThound)  
                  : unit2TenThousand(scope.row.total_tips, isTenThound)
              }}
            </template>
          </el-table-column>

          <el-table-column label="营业收入(净)" align="center" min-width="115px">
            <template slot-scope="scope">
              <div 
                style="display:flex;justify-content:center" 
                :style="`${
                  isAmountProp(scope.row.companyName) 
                    ? getTotalValueStyle(scope.row, 'msale_total') 
                    : getCurrentValueStyle(scope.row.msale_total, scope.row.total_tips)
                  }`"
              >
               {{ 
                isAmountProp(scope.row.companyName)
                  ? unit2TenThousand(calcAmount('msale_total', scope.row.companyNo), isTenThound)
                  : unit2TenThousand(scope.row.msale_total, isTenThound) 
                }}
              </div>
            </template>
          </el-table-column>

          <el-table-column label="营收完成%" align="center" min-width="85px">
            <template slot-scope="scope">
              <div :style="`${isAmountProp(scope.row.companyName) ? getTotalRateStyle(scope.row,'completion_rate') : getCurrentRateStyle(scope.row.completion_rate)}`">
                {{ 
                    isAmountProp(scope.row.companyName) 
                    ? calcAmountCompletionRate(scope.row.companyNo) 
                    : isLineRete((String(scope.row.completion_rate) === 'NaN' || Math.abs(scope.row.completion_rate) === Infinity ? 0 :  scope.row.completion_rate))
                    }}
              </div>
            </template>
          </el-table-column>


          <template v-if="costField">
            <el-table-column label="毛利目标" align="center" min-width="90px">
              <template slot-scope="scope">
                {{ 
                  costField 
                  ? isAmountProp(scope.row.companyName) ? unit2TenThousand(calcAmount('cost_tips',scope.row.companyNo), isTenThound) : unit2TenThousand(scope.row.cost_tips, isTenThound) 
                  : '***' 
                }}
              </template>
            </el-table-column>

            <el-table-column label="毛利完成" align="center" min-width="90px">
              <template slot-scope="scope">
                <div :style="`${isAmountProp(scope.row.companyName) ? getTotalValueStyle(scope.row,'gross_completion', true) : getCurrentValueStyle(scope.row.gross_completion, scope.row.cost_tips)}`">
                  {{ costField 
                    ?  isAmountProp(scope.row.companyName) ? unit2TenThousand(calcAmount('gross_completion', scope.row.companyNo), isTenThound) : unit2TenThousand(scope.row.gross_completion, isTenThound) 
                    : '***' 
                  }}
                </div>
              </template>
            </el-table-column>
            </template>

            <el-table-column label="毛利完成%" align="center" min-width="85px">
              <template slot-scope="scope">
                <div :style="isAmountProp(scope.row.companyName) ? getTotalRateStyle(scope.row, 'gross_completion_rate') : getCurrentRateStyle(scope.row.gross_completion_rate)">
                  {{  isAmountProp(scope.row.companyName) ? calcAmountGrossCompletionRate(scope.row.companyNo) : scope.row.gross_completion_rate === '-' ? '-' : scope.row.gross_completion_rate  + '%' }}
                </div>
              </template>
            </el-table-column>

          <template v-if="costField">
            <el-table-column label="成本合计" align="center" min-width="125px">
              <template slot-scope="scope">
                <div style="display:flex;justify-content:center" v-if="costField">
                  {{  
                    isAmountProp(scope.row.companyName)
                      ? unit2TenThousand(calcAmount('mcost_total', scope.row.companyNo), isTenThound) 
                      : unit2TenThousand(scope.row.mcost_total, isTenThound) 
                  }}
                </div>

                <p v-else>***</p>
              </template>
            </el-table-column>

            <el-table-column label="实际毛利率" align="center" width="85px">
              <template slot-scope="scope">
                {{ costField 
                  ? isAmountProp(scope.row.companyName) ? calcAmountRealRate(scope.row.companyNo)  : unit2TenThousand(scope.row.gross_sale_completion_rate) + "%" 
                  : '***' 
                }}
              </template>
            </el-table-column>
          </template>
      </el-table>
    </el-row>

    <template v-else>
      <div style="text-align:center;line-height:60px;user-select:none">当前账号没有访问权限</div>
    </template>
    <!--  -->
  </div>
</template>


<script>
import { addition, unit2TenThousand, subtraction, multiplication, division } from "../newReport/src/_utils";
import asyncRequest from "@/api/newResults";
import { mapCompany2 } from "./mapCompany";

import { amountData } from "./calc"
import dayjs from "dayjs"

export default {
  props: ['companies', 'costField', 'isTenThound'],
  data() {
    return {
      lastSupportCompany: '',
      totalAmount:[],
      selfSupport:{ companyArr: [] },
      otherSupport: { companyArr: [], companyAmount: [] },
      daytime: "",
      loading: false,
      tableData: [],
      companyNo: "",
      plat_cp_companies:[],
      cp_companies: [],
      isEmpty: false,
      mapCompany2,
     composeCompanies: ['QS2206011447553544', 'QS2304031312553756', 'QS2203150147012961'],
     otherCompanise: [],
     notOtherCompanise: ['QS2206011447553544', 'QS2304031312553756', 'QS2203150147012961','QS2203150147013805','QS2203150147015222','QS2206011103304501']
    }
  },
  mounted() {
    let hasCompose = false;
    const jxIndex = this.companies.findIndex((item) => item.label === "北京锦兴弘昌科技有限公司");
    const prIndex = this.companies.findIndex((item) => item.label === "北京普润心堂商贸有限公司");
    const zsIndex = this.companies.findIndex((item) => item.label === "北京知事文化产业发展有限公司");

    if (jxIndex !== -1 || prIndex !== -1 || zsIndex !== -1) hasCompose = true;
    this.cp_companies = this.companies.filter((item) => item.label !== "北京锦兴弘昌科技有限公司" && item.label !== "北京普润心堂商贸有限公司" && item.label !== "北京知事文化产业发展有限公司")
    if (hasCompose) this.cp_companies = [...this.cp_companies, { value: "GS2302231124114965", label: "普润&锦兴&知事" }]

    this.isEmpty = this.cp_companies.length === 0;
    if (this.isEmpty) return;

    this.cp_companies = this.cp_companies.map((item, index) => {
      let label = '';
      if (item.label === '北京万宇恒通国际科贸有限公司') { label = '平台公司: 万宇' }
      if (item.label === '北京泰文创供应链管理有限公司') { label = '平台公司: 泰文创' }
      if (item.label === '北京元隆雅图文化传播股份有限公司') { label = '预订单E企购' }
      if (item.label === '结算单E企购') { label = '结算单E企购' }
      if (item.label === "普润&锦兴&知事") { label = `业务公司: 普润&锦兴&知事` }
      if (label === '') label = `业务公司: ${mapCompany2[item.label]}`;
      return ({ ...item, label })
    })


    let plat_list = ['所有平台公司','平台公司: 万宇', '平台公司: 泰文创', '预订单E企购', '结算单E企购']
    const plat_cp_list = this.cp_companies.map((item) => item.label);
    plat_list = plat_list.filter(item => plat_cp_list.includes(item));
    this.plat_cp_companies = plat_list.map((item) => this.cp_companies.find((cp_item) => cp_item.label === item));

    if(this.plat_cp_companies.length === 4){ this.plat_cp_companies =  [{ value: "", label: "所有平台公司" }, ...this.plat_cp_companies] }

    this.companyNo = this.plat_cp_companies[0].value;
    // this.daytime = "2024-07-31"
    this.daytime = this.transformTime();
    this.requestData();
  },
  methods: {
    isLineRete(value){
      return value === '-' ? '-' : value + '%'
    },
    calcAmountRealRate(companyNo){
      const msale_total = this.calcAmount('msale_total',companyNo)
      const gross_completion = this.calcAmount('gross_completion',companyNo) 
      const value = Number(multiplication(Number(division(gross_completion, msale_total)).toFixed(2), 100)).toFixed(2)
      return isNaN(value) ? '0%' : value + '%'
    },
    calcAmountGrossCompletionRate(companyNo){
       if(companyNo === 'selfSupportOrderPR') return '-'
       let cost_tips = ''

       if(companyNo === 'selfSupportOrderAmount'){
        cost_tips = this.selfSupport.cost_tips
       } else if(companyNo === 'otherSupportOrderAmount'){
        cost_tips = this.otherSupport.cost_tips
       }else {
         cost_tips = this.calcAmount('cost_tips', companyNo)
       }

      const gross_completion = this.calcAmount('gross_completion', companyNo)
      return Number(multiplication(Number(division(gross_completion, cost_tips)).toFixed(2), 100)).toFixed(2) + '%'
    },
    getTotalValueStyle(row, prop, isCost = false){
      const days = dayjs(this.daytime).daysInMonth();
        const total_tips = this.calcAmount(isCost ? 'cost_tips' : 'total_tips', row.companyNo)
        const current = this.calcAmount(prop, row.companyNo)
        const oneDay = Number(division(total_tips, days)).toFixed(2);
        const currentDay = dayjs(this.daytime).date();
        const currentTotalTip = Number(multiplication(currentDay, oneDay)).toFixed(2);

        console.log(current,currentTotalTip)
        return Number(currentTotalTip) > Number(current) ? 'color: red' : '';
    },
    getTotalRateStyle(row, prop) {
        const days = dayjs(this.daytime).daysInMonth();
        const oneDay = Number(division(100, days)).toFixed(2);
        const currentDay = dayjs(this.daytime).date();
        let currentTotalTip = Number(multiplication(currentDay, oneDay))
        currentTotalTip = Number(currentTotalTip > 100 ? 100 : currentTotalTip).toFixed(2)
        let current = ''
        
        if(prop === 'completion_rate'){
          current = this.calcAmountCompletionRate(row.companyNo)
        }{
          current = this.calcAmountGrossCompletionRate(row.companyNo)
        }

      
        if(String(current).indexOf('%')) current = current.replace('%','')
        return Number(currentTotalTip) > Number(current) ? 'color:red' : ''
    },
    getCurrentRateStyle(current) {
      const days = dayjs(this.daytime).daysInMonth();
      const oneDay = Number(division(100, days)).toFixed(2);
      const currentDay = dayjs(this.daytime).date();
      const currentTotalTip = Number(multiplication(currentDay, oneDay)).toFixed(2);
      return Number(currentTotalTip) > Number(current) ? 'color:red' : ''
    },
    getCurrentValueStyle(current, total = 0) {
      const days = dayjs(this.daytime).daysInMonth();
      const oneDay = Number(division(total, days)).toFixed(2);
      const currentDay = dayjs(this.daytime).date();
      const currentTotalTip = Number(multiplication(currentDay, oneDay)).toFixed(2);
      return Number(currentTotalTip) > Number(current) ? 'color: red' : '';
    },
    calcAmountCompletionRate(companyNo){
      const msale_total = this.calcAmount('msale_total', companyNo)
      const total_tips = this.calcAmount('total_tips', companyNo)
      return Number(multiplication(Number(division(msale_total, total_tips)).toFixed(2), 100)).toFixed(2) + '%'
    },
    calcAmount(prop, companyNo){
      let sourceData = []

      if(companyNo === 'totalAmount'){
        const selfTotal = this.calcAmount(prop, 'selfSupportOrderAmount')
        const otherTotal = this.calcAmount(prop, 'otherSupportOrderAmount')
        return Number(addition(selfTotal, otherTotal)).toFixed(2)
      }

      if(companyNo === 'selfSupportOrderPR') {
        sourceData = this.selfSupport.companyArr.find(({companyName}) => companyName === '普润').children
        if(prop === 'total_tips' || prop === 'cost_tips'){ return sourceData[0][prop]  }
      }


      if(companyNo === 'otherSupportOrderAmount'){
        if(prop === 'total_tips'){
          return this.otherSupport.total_tips
        }

        if(prop === 'cost_tips'){
          return this.otherSupport.cost_tips
        }

        sourceData = this.otherSupport.companyArr
      }

      if(companyNo === 'selfSupportOrderAmount') {
        const children = this.selfSupport.companyArr.find(({companyName}) => companyName === '普润').children

        if(prop === 'cost_tips'){
          return this.selfSupport.cost_tips
        }

        if(prop === 'total_tips'){
          return this.selfSupport.total_tips
        }

        sourceData = [...this.selfSupport.companyArr, ...children]
        if(prop === 'cost_tips') { return '-' }
      }


      return sourceData.reduce((prev, current) => {
        if(!current) return 0
        const value = Number(addition(prev,isNaN(current[prop]) ? 0 : current[prop]))
        return value === 0 ? 0 : value.toFixed(2)
      }, 0)
    },
    isAmountProp(companyName){
      return companyName === '普润' || companyName === '其他' || companyName === '合计'
    },
    load(_1,_2,resolve){
      const ylBusiness = this.tableData.find(({companyNo}) => companyNo === 'compoeseSupplier')
      resolve(ylBusiness ? ylBusiness.children : [])
    },
    unit2TenThousand,
    handleData(data){
      let companyArr = []
      data.companyArr.forEach(({ 
          supplierName,
          supplierNo,
          total_tips = '-',
          monthinfo, 
          cost_tips = '-',
          dayinfo,
          is_sup = '-'
         }) => {
          
          total_tips = Number(total_tips) === 0 ? '-' : total_tips
          const mapResponseType = { '1': '自营' }
          const types = Object.keys(mapResponseType)
          let prev_sale_total = 0;
          let prev_msale_total = 0;
          let prev_cost_total = 0;
          let prev_mcost_total = 0;

          const item = types.map(type => {
    
            let _monthinfo = (Array.isArray(monthinfo) ? monthinfo : [monthinfo])[0]
            let _dayinfo = (Array.isArray(dayinfo) ? dayinfo : [dayinfo])[0]
            const defaultMonthInfo = { mcgd_th_total :  "0.00", mcgd_total:"0.00", msale_total: "0.00", mth_total: "0.00", type }
            const defaultDayinfo = { "sale_total": "0.00", "th_total": "0.00", "type": "1", "cgd_total": "0.00", "cgd_th_total": "0.00", type }

            if(!_monthinfo) _monthinfo = defaultMonthInfo
            if(!_dayinfo) _dayinfo = defaultDayinfo

            /** 月营业收入 = 月销售额 - 月退货额  */
            let msale_total = 0;
            if('msale_th_total' in _monthinfo){ _monthinfo.mth_total = _monthinfo.msale_th_total }
            // if(Number(type) !== 4){
              msale_total = subtraction(_monthinfo.msale_total, _monthinfo.mth_total) || 0
            // }
            /** 日营业收入 = 日销售额 - 日退货额 */
            const sale_total = subtraction(_dayinfo.sale_total, _dayinfo.sale_th_total) || 0;
            /** 日成本 = 日采购额 - 日退货额 */
            const cost_total = subtraction(_dayinfo.cgd_total, _dayinfo.cgd_th_total) || 0;
            /** 月成本 = 月采购额 - 月退货额 */
            let mcost_total = 0;
            // if(Number(type) !== 4){
              mcost_total = subtraction(_monthinfo.mcgd_total, _monthinfo.mcgd_th_total) || 0;
            // }else{
            //   mcost_total = Number(_monthinfo.mcgd_total || 0).toFixed(2);
            // }
            prev_sale_total = Number(addition(prev_sale_total, sale_total)).toFixed(2);
            prev_msale_total = Number(addition(prev_msale_total, msale_total)).toFixed(2);
            prev_cost_total = Number(addition(prev_cost_total, cost_total)).toFixed(2);
            prev_mcost_total = Number(addition(prev_mcost_total, mcost_total)).toFixed(2);

            return {
              type: mapResponseType[type],
              dayinfo: { ..._dayinfo, sale_total },
              monthinfo: { ...monthinfo, msale_total, mcost_total }
            }
          })

          const gross_completion = Number(subtraction(prev_msale_total, prev_mcost_total)).toFixed(2) //当月毛利完成 = 月营收 - 月成本

          companyArr = [
            ...companyArr,
            {
              is_sup,
              companyNo: supplierNo,
              companyName: supplierName,  // 公司名称
              cost_tips, // 当月成本指标
              total_tips, // 当月营收目标
              info: item[0], // 直营..渠道 销售
              sale_total: prev_sale_total, // 当日营业收入
              cost_total: prev_cost_total, // 当日成本总额
              msale_total: prev_msale_total, // 当月营业收入
              mcost_total: prev_mcost_total,// 当月成本总额
              gross_completion, //当月毛利完成 = 月营收 - 月成本
              completion_rate: total_tips === '-' ? '-' : multiplication(Number(division(prev_msale_total, total_tips)).toFixed(2), 100).toFixed(2), // 当月应收完成率
              gross_completion_rate: cost_tips === '-' ? '-' :Number(cost_tips) === 0 ? 0 : multiplication(division(gross_completion, cost_tips) || 0, 100).toFixed(2), // 当月毛利完成率
              gross_sale_completion_rate: Number(multiplication(Number(division(gross_completion, prev_msale_total)).toFixed(2), 100)).toFixed(2), // 本月毛利率 =  当月毛利完成 / 当月营业收入
            }
          ]
       })

      return companyArr
    },

    setCellClassName({ column, row, columnIndex }) {
      const { label } = column;
      let base = ''

      if(
        (columnIndex === 0  && (row.order_type === '自营订单' || row.order_type === undefined)) &&
        row.companyName !== this.lastSupportCompany
      ) {
         base += 'no-border-bottom '
      }

      if(row.companyName === "北京万宇恒通国际科贸有限公司") {
        base += 'font-bold '
      }

      if (label === "营收目标")  {
        base += "bg__success"
        return base
      }

      if ((label.indexOf('营业') !== -1 || label.indexOf('营收') !== -1) && label !== '当日营业收入') {
        base += "bg__success_1"
        return base;
      }

      if (label === "毛利目标") {
        base += "bg__primary"
        return base
      }

      if (label.indexOf('毛利') !== -1) {
        base += "bg__primary_1"
        return base;
      }
      if (label.indexOf('成本') !== -1) {
        base += "bg__warning_1"
        return base;
      }
      return base
    },
    setHeaderClassName({ column }) {
      const { label } = column;
      if (label === "营收目标") { return "bg__success" }

      if ((label.indexOf('营业') !== -1 || label.indexOf('营收') !== -1) && label !== '当日营业收入'){
         return "bg__success_1"
      }

      if (label === "毛利目标"){ return "bg__primary" }
      if (label.indexOf('毛利') !== -1) { return "bg__primary_1" }
      if (label.indexOf('成本') !== -1) { return "bg__warning_1" }
    },
    transformTime() {
      let time = new Date();
      let y = time.getFullYear();
      let M = time.getMonth() + 1;
      let d = time.getDate();
      return y + "-" + (M < 10 ? "0" + M : M) + "-" + (d < 10 ? "0" + d : d);
    },
    async requestData() {
      this.loading = true;
      this.tableData = [];
      const res = await asyncRequest.supplier({ daytime: this.daytime });
      if (res.code === 1 && res.data) {
        let { '2': selfSupport, '3': otherSupport } = JSON.parse(JSON.stringify(res.data))

        console.log(JSON.parse(JSON.stringify(selfSupport)))

        selfSupport.companyArr = this.handleData(selfSupport) 
        otherSupport.companyArr = this.handleData(otherSupport)


        this.otherSupport = otherSupport
        this.selfSupport = selfSupport

        let children = this.selfSupport.companyArr.filter(({companyNo}) => this.composeCompanies.includes(companyNo))

        const companies = ['北京普润心堂商贸有限公司', '北京锦兴弘昌科技有限公司', '北京知事文化产业发展有限公司']
        children = companies.map(companyName => {
          return children.find(item => item.companyName === companyName)
        }).filter(item => item !== undefined)


        this.selfSupport.companyArr = this.selfSupport.companyArr.filter(({companyNo}) => !this.composeCompanies.includes(companyNo))


        this.selfSupport.companyArr = [
          {
            ...amountData,
            companyNo: 'selfSupportOrderAmount',
            companyName: '合计'
          },
          ...(children.length === 0? [] : [{
            ...amountData,
            companyNo: 'selfSupportOrderPR',
            companyName: '普润',
            children
          }]),
          ...this.selfSupport.companyArr
        ]

        this.otherSupport.companyAmount = [
          {
            ...amountData,
            order_type: '地推订单',
            companyName: '合计',
            companyNo: 'otherSupportOrderAmount'
          }
        ]
        this.totalAmount = [{
          ...amountData,
          companyNo: 'totalAmount',
          order_type: '结算单E企购',
          companyName: '合计'
        }]


        const zrIndex =  this.selfSupport.companyArr.findIndex(({companyNo}) => companyNo === 'QS2206011103304501')
        const hyIndex = this.selfSupport.companyArr.findIndex(({companyNo}) => companyNo === 'QS2203150147015222')
        if(zrIndex !== -1 && hyIndex !== -1){
          const temp = this.selfSupport.companyArr[zrIndex]
          this.selfSupport.companyArr[zrIndex] = this.selfSupport.companyArr[hyIndex]
          this.selfSupport.companyArr[hyIndex] = temp
        }

               

      console.log(this.selfSupport.companyArr)

       if(this.selfSupport.companyArr.length === 1){
        this.selfSupport.companyArr[0].order_type = '自营订单'
       }else{
         this.lastSupportCompany = this.selfSupport.companyArr[this.selfSupport.companyArr.length -1].companyName
        const middle = Math.floor(this.selfSupport.companyArr.length / 2)
        this.selfSupport.companyArr[middle].order_type = '自营订单'
       }


        // this.otherCompanise = sourceData.filter(({is_sup}) => is_sup === 1)
        // sourceData = sourceData.filter(({companyNo}) =>  !this.composeCompanies.includes(companyNo) && this.notOtherCompanise.includes(companyNo))
        // , hasChildren: true, children
        // this.tableData = sourceData
      } else {
        this.tableData = [];
      }
      this.loading = false;
    }
  }
}
</script>

<style lang="scss" scoped>


.new-results {
  .search {
    height: 36px;
    padding: 0px 10px;
    margin-top: 10px;
    flex-wrap: wrap;
  }
}

.table-size {
  display: flex;
  width: 200px;
  border: 1px solid #ebeef5;
  flex-direction: column;

  p {
    flex: 1;
    border-bottom: 1px solid #ebeef5;
    padding: 5px 10px;
    margin: 0px;

    &:last-child {
      border: none;
    }
  }
}
</style>

