<template>
  <div class="app-container">
    <div class="unfollowed-list-title">
      <span>{{ "代理商新增项目统计" }}</span>
      <el-date-picker
        v-model="queryParams.weekData"
        type="week"
        value-format="yyyy-MM-dd"
        format="yyyy 第 WW 周"
        @change="getList"
        :picker-options="{'firstDayOfWeek': 6}"
        placeholder="选择周"
        :clearable="false"/>
        <el-button style="margin-left: 10px;" type="primary" icon="el-icon-search" size="mini" @click="getList">{{ $t('common.search') }}
        </el-button>
    </div>
    <card-table :loading="loading" :modalData="project" :searchParams="queryParams" :tableSearch="true" labelWidth="120px" @columnSearch="handleQuery"
                @pagination="getList"  @resetList="resetQuery" max-height="600px" @sortChange="sortChange"
                >
      <template #operations="{ selections }">
        <el-button v-hasPermi="['bt:business:quotation:export']" icon="el-icon-download" plain size="mini"
                   @click="handleExport">{{ $t('common.export') }}
        </el-button>
      </template>
      <template #default="{ list }">
<!--        <el-table-column align="center" type="selection" width="55" :selectable="checkSelectable"/>-->
        <el-table-column label="No." type="index" width="50" align="center" fixed />
        <!--区域-->
        <Column :label="$t('user.area')" prop="areaId" :showSearch="true" searchType="select" :searchDict="areaList" :min-width="200" :selectMore="true"/>
        <!--国家-->
        <Column :label="$t('account.country')" prop="countryId" :showSearch="true" searchType="select" :searchDict="curCountryOps" :min-width="200" :selectMore="true"/>
        <!--城市-->
        <Column :label="$t('project.city')" prop="city" show-search :searchParams="queryParams"/>
        <!--代理商-->
<!--        <Column :label="$t('agent.agent')" prop="ownerAgent" :showSearch="true" searchType="select" :searchDict="curAgentOps" :min-width="200" :selectMore="true"/>-->

        <Column :label="$t('lead.agent')" prop="ownerAgent" :showSearch="true" search-type="select"
                :searchParams="queryParams" :search-dict="agentList" select-more value-prop="agentId"
                label-prop="agentName" width="250px">
          <template #default="{ row }">
                        <span>{{
                            row.ownerAgentName == 'common.head' ? $t(row.ownerAgentName) :
                              row.ownerAgentName
                          }}</span>
          </template>
        </Column>
        <!--所属客户-->
        <Column :label="$t('agentAddProject.accountName')" prop="accountName"  show-search :searchParams="queryParams"/>
        <!--新建项目数量-->
        <Column :label="$t('agentAddProject.sumProjectWeek')" prop="sumProjectWeek" />

        <!--新建项目台数-->
        <Column :label="$t('agentAddProject.sumEngineeringWeek')" prop="sumEngineeringWeek" />

        <!--新建项目金额-->
        <Column :label="$t('agentAddProject.priceWeek')"prop="priceWeek" align="right">
          <template #default="{ row }">
            <!--每三位一个逗号-->
            <span>{{ row.priceWeek ? toDecimal2(numFormat(row.priceWeek)) : '-' }}</span>
          </template>
        </Column>
        <!--合计项目数量-->
        <Column :label="$t('agentAddProject.sumProjectTotal')" prop="sumProjectTotal"/>

        <!--合计项目台数-->
        <Column :label="$t('agentAddProject.sumEngineeringTotal')" prop="sumEngineeringTotal" />

        <!--合计项目金额-->
        <Column :label="$t('agentAddProject.priceTotal')" prop="priceTotal" align="right">
          <template #default="{ row }">
            <!--每三位一个逗号-->
            <span>{{ row.priceTotal ? toDecimal2(numFormat(row.priceTotal)) : '-' }}</span>
          </template>
        </Column>
      </template>
    </card-table>

  </div>
</template>

<script>


import {listAccount, listAccountNewAdd, } from "@/api/business/crm/account";
import ColorDictTag from "@/views/crmManagement/lead/ColorDictTag/index.vue";
import Column from "@/components/element/table/Column.vue";
import {getAllAreaList} from "@/api/user/area";
import {curAgent} from "@/api/business/crm/lead";
import {getCountryList} from "@/api/business/crm/follow";
import {listAllAgent, selectForAccount} from "@/api/user/agent";
import {listAgentAddProject} from "@/api/board/agent4ProjectAndAccount";
import moment from "moment";

export default {
  name: "AgentAddProject",
  components: {
    Column, ColorDictTag

  },
  computed:{
    localLabelSuffix() {
      return localStorage.getItem('labelSuffix') || '';
    }
  },
  data() {
    return {
      loading:false,
      project:[],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        language: this.$i18n.locale,
        countryId: [],
        areaId: [],
        ownerAgent:[],
        city: null,
        permissionChar:this.$store.state.user.permissionChar,
        accountName:null,
        weekData:undefined
      },
      areaList:[],
      curCountryOps:[],
      curAgentOps:[],
      agentList: [],
      permissionChar: '',
      continueFlag:false,
    };
  },

  created() {
    // 获取国际化     this.$i18n.locale = val
    const lang = localStorage.getItem('local');
    if (lang) {
      this.$i18n.locale = lang;
    }
    this.permissionChar = this.$store.state.user.permissionChar
    this.curAgent()
    this.getAreaList()
    this.curCountry()
    this.getAgentList()
    // this.getList()
    this.queryParams.weekData = moment().startOf('week').format('YYYY-MM-DD')
    this.getList()
  },

  methods: {
    /** 导出按钮操作 */
    async handleExport() {
      await  this.handleWeekChange()
      if(this.continueFlag){
        this.download('business/agent4ProjectAndAccount/exportAgentAddProject', {
          ...this.queryParams
        }, `代理商新建项目统计_${new Date().getTime()}.xlsx`)
      }
    },
    getAgentList() {
      selectForAccount().then(res => {
        this.agentList = res.data;
        if (this.userInfo.deptId == 0) {
          this.agentList.unshift({agentId: 0, agentName: this.$t('common.head')});
        }
      })
    },
    //获取国家
    async curCountry() {
      const response = await getCountryList()
      response.data.forEach(item=>{
        this.curCountryOps.push({
          label: item['second' + this.localLabelSuffix],
          value: parseInt(item.first)
        })
      })
    },

    //获取代理商
    async curAgent() {
      const response = await listAllAgent()
      response.data.forEach(item => {
        this.curAgentOps.push({
          label: item['agentName' + this.localLabelSuffix],
          value:item.agentId
        })
      })
      // 如果存在 ownerAgent =0，则添加总部选项
      this.curAgentOps.unshift({value: 0, label: this.$t('agent.headquarters')})
    },
    // 获取区域
    getAreaList() {
      this.areaList = []
      getAllAreaList().then(response => {
        if (response.data) {
          response.data.forEach(item => {
            this.areaList.push({
              label: item['areaName' + this.localLabelSuffix],
              value: parseInt(item.areaId)
            })
          })
        }
      });
    },
    sortChange({column, prop, order}) {
      if (order === 'ascending') {
        this.queryParams.orderByColumn = prop;
        this.queryParams.isAsc = 'asc';
      } else if (order === 'descending') {
        this.queryParams.orderByColumn = prop;
        this.queryParams.isAsc = 'desc';
      } else {
        this.queryParams.orderByColumn = null;
        this.queryParams.isAsc = null;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$set(this.queryParams, 'pageNum', 1);
      this.$set(this.queryParams, 'pageSize', 10);
      this.$set(this.queryParams, 'language', this.$i18n.locale);
      this.$set(this.queryParams, 'countryId', []);
      this.$set(this.queryParams, 'areaId', []);
      this.$set(this.queryParams, 'city', null);
      this.$set(this.queryParams, 'ownerAgents', []);
      this.$set(this.queryParams, 'permissionChar', this.$store.state.user.permissionChar);
      this.$set(this.queryParams, 'accountName', null);
      this.getList();
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList();
    },
    handleWeekChange(){
      this.continueFlag  = true
      if(this.queryParams.weekData == null || this.queryParams.weekData.length === 0 ){
        this.$message.warning("请选择周！")
        this.continueFlag  = false
        return
      }
      // 原始日期字符串
      const dateString = this.queryParams.weekData;
      // 创建 Date 对象
      const date = new Date(dateString);
      // 提取日期部分
      const year = date.getUTCFullYear();
      const month = String(date.getUTCMonth() + 1).padStart(2, '0'); // 月份需要加1并补零
      const day = String(date.getUTCDate()).padStart(2, '0'); // 补零
      // 组装成所需格式
      this.queryParams.week = `${year}-${month}-${day} 00:00:00`
    },
    async getList(){
      this.loading = true;
      await  this.handleWeekChange()
      if(this.continueFlag){
        this.queryParams.language = this.$i18n.locale;
        this.queryParams.permissionChar = this.permissionChar;
        const res = await listAgentAddProject(this.queryParams)
        this.project = res.rows;
        this.queryParams.total = res.total;
      }
      this.loading = false
    }
  }
};

</script>

<style lang="scss" scoped>
.unfollowed-list-title {
  padding: .5rem;
  font-size: 16px;
  font-weight: bold;

  margin-bottom: 24px;
  white-space: nowrap;
  display: flex;
  align-items: center;
  gap: 1vw;
  background-color: #f5f5f5;
}
.dashboard {
  // 全屏容器
  height: 100vh;

  //padding: 32px;
  padding: 1rem;
  //background-color: rgb(240, 242, 245);
  background-color: lightblue;
  position: relative;

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 24px;
    border-radius: .75rem;
  }
}

@media (max-width: 1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
