<script>
import {
  exportXlsx, listAllDeptSummary,
  search
} from "@/api/cso_sys_dept";
import scorePackageStatusDict from "@/utils/dict/ScorePackageStatus";
import {getDictMap} from "@/api/cso_sys_dict";
import ColumnsSelect from "@/components/ColumnsSelect/index.vue";

export default {
  name: 'CsoSysDept',
  components: {ColumnsSelect},
  data() {
    return {
      searchForm: {
        name: null,
        taxCode: null,
        subjectType:null,
        delFlag:null,
        subjectLocation:null,
      },
      searchParams: {
        name: null,
        taxCode: null,
        subjectType:null,
        delFlag:null,
        subjectLocation:null,
      },
      data: null,
      pageSize: 10,
      scorePackageStatusDict,
      showLevel: -1,
      nextId:0,
      loading:false,
      allDepts:[],
      subTypeDict:{},
      subjectLocationDict:{},
      delFlagDict:[{label:'启用',value:0},{label:'停用',value:1}],
      columns: [
        { key: 0, label: `企业名称`, visible: true },
        { key: 1, label: `统一社会信用代码`, visible: true },
        { key: 2, label: `企业类型`, visible: true },
        { key: 3, label: `是否渠道`, visible: true },
        { key: 4, label: `结算渠道及企业限额`, visible: true },
        { key: 5, label: `认证人数`, visible: true },
        { key: 6, label: `服务人数`, visible: true },
        { key: 7, label: `签约类型`, visible: true },
        { key: 8, label: `上年月均年化`, visible: true },
        { key: 9, label: `当年月均年化`, visible: true },
        { key: 10, label: `NRR(%)`, visible: true },
        { key: 11, label: `状态`, visible: true }
      ],
    }
  },
  computed: {
    hasSearchParams() {
      for (const key of Object.keys(this.searchParams)) {
        const value = this.searchParams[key]
        if (value === null || value === undefined) {
          continue
        }
        if (typeof value === 'string') {
          if (value.trim().length > 0) {
            return true
          }
        } else if (Array.isArray(value)) {
          if (value.length > 0) {
            return true
          }
        }
      }
      return false
    }
  },
  watch:{
    showLevel(){
      this.search()
    }
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      await Promise.all([this.loadAllDict(), this.search()])
    },
    async loadAllDict() {
      this.allDepts = await listAllDeptSummary()
      this.subTypeDict=await getDictMap('sub_type')
      this.subjectLocationDict=await getDictMap('subject_location')
    },
    async search() {
      this.searchParams = {
        name: this.searchForm.name,
        taxCode: this.searchForm.taxCode,
        subjectType:this.searchForm.subjectType,
        delFlag: this.searchForm.delFlag,
        subjectLocation: this.searchForm.subjectLocation
      }
      await this.loadData(1)
    },
    async loadData(page) {
      this.loading=true
      try {
        const params = {
          page: page - 1,
          size: this.pageSize,
          ...this.searchParams
        }
        if (this.showLevel === -1 && !this.hasSearchParams) {
          params.root = true
        } else if (this.showLevel === 0) {
          params.level = 2
        } else if (this.showLevel === 1) {
          params.level = 3
        } else if (this.showLevel === 2) {
          params.level = 4
        }
        params.fetchChildrenCount = this.showLevel === -1
        const data = await search(params)
        for(let i=0;i<data.content.length;i++){
          const row=data.content[i]
          row.no = (data.page * data.size + i + 1) + ""
          this.processRow(row)
        }
        this.data = data
      } finally {
        this.loading=false
      }
    },
    processRow(row){
      row.rid=++this.nextId
      if (this.showLevel === -1) {
        row.hasChildren = row.childrenCount>0
      }
      row.levelName=['','要易业务管理平台','药企','一级CSO','二级CSO','其他'][row.level]
      row.delFlagName=row.delFlag==='1'?'停用':'启用'
      if(row.subjectLocationAndLimitAmount){
        const group1=[]
        const group2=[]
        row.subjectLocationAndLimitAmount.split(',').forEach(i=>{
          const kv=i.split(':')
          const ki=kv[0].indexOf('(')
          const name=kv[0].substring(0,ki)
          const status=kv[0].substring(ki)
          let label
          if(kv.length>1&&kv[1]){
            label = name + ":" + this.formatMoney(parseFloat(kv[1]))
          }else{
            label = name + ":"
          }
          if(status==='(启用)'){
            group1.push(label)
          }else{
            group2.push(label)
          }
        })
        row.subjectLocationAndLimitAmount=[group1,group2]
      }else{
        row.subjectLocationAndLimitAmount=[[],[]]
      }
      row.nrr = new Intl.NumberFormat('zh-CN', {style: 'percent', maximumFractionDigits: 2}).format(row.nrr)
    },
    async loadChildren(row, treeNode, resolve) {
      const data = await search({
        page: 0,
        size: 10000,
        delFlag: this.searchForm.delFlag,
        parentId: row.deptId,
        fetchChildrenCount: this.showLevel === -1
      })
      const parentNo=row.no
      for(let i=0;i<data.content.length;i++){
        const row=data.content[i]
        row.no = parentNo+"."+(data.page * data.size + i + 1)
        this.processRow(row)
      }
      resolve(data.content)
    },
    async exportXlsx() {
      this.$modal.loading("正在导出数据，请稍后...")
      try {
        const params = {
          ...this.searchParams
        }
        if (this.showLevel === 0) {
          params.level = 2
        } else if (this.showLevel === 1) {
          params.level = 3
        } else if (this.showLevel === 2) {
          params.level = 4
        }
        const filename = await exportXlsx(params)
        this.$download.name(filename, true)
      } finally {
        this.$modal.closeLoading()
      }
    },
    formatMoney(value){
      if(typeof value!=='number'){
        return value
      }else{
        return new Intl.NumberFormat('zh-CN',{maximumFractionDigits:0}).format(value)
      }
    },
    async handleSizeChange(val){
      this.pageSize=val
      await this.search()
    }
  }
}
</script>

<template>
  <div class="app-container">
    <el-form inline v-model="searchForm">
      <el-form-item label="企业名称">
        <el-select v-model="searchForm.name" filterable clearable multiple>
          <el-option
            v-for="item in allDepts"
            :key="item.deptId"
            :label="item.name"
            :value="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="统一社会信用代码">
        <el-input v-model="searchForm.taxCode"></el-input>
      </el-form-item>
      <el-form-item label="结算平台">
        <el-select v-model="searchForm.subjectType" filterable clearable>
          <el-option
            v-for="(label,value) in subTypeDict"
            :key="value"
            :label="label"
            :value="value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="结算渠道">
        <el-select v-model="searchForm.subjectLocation" filterable clearable>
          <el-option
            v-for="(label,value) in subjectLocationDict"
            :key="value"
            :label="label"
            :value="value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.delFlag" filterable clearable>
          <el-option
            v-for="item in delFlagDict"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="search" type="primary">检索</el-button>
      </el-form-item>
    </el-form>
    <div class="table-toolbar">
      <div class="table-toolbar-left">
        <el-form inline size="mini" class="no-errors">
          <el-form-item label="显示企业">
            <el-radio-group v-model="showLevel">
              <el-radio-button :label="-1">所有</el-radio-button>
              <el-radio-button :label="0">药企</el-radio-button>
              <el-radio-button :label="1">一级CSO</el-radio-button>
              <el-radio-button :label="2">二级CSO</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <div class="table-toolbar-right">
        <el-button icon="el-icon-download" size="mini" @click="exportXlsx">导出</el-button>
        <columns-select :columns="columns"/>
      </div>
    </div>
    <div>
      <el-table v-loading="loading" :data="data?data.content:[]" style="width: 100%" row-key="rid" border lazy max-height="600" :load="loadChildren">
        <el-table-column prop="no" label="序号" width="120"></el-table-column>
        <el-table-column prop="name" label="企业名称" width="300" v-if="columns[0].visible"></el-table-column>
        <el-table-column prop="taxCode" label="统一社会信用代码" width="200" v-if="columns[1].visible"></el-table-column>
        <el-table-column prop="levelName" label="企业类型" width="90" v-if="columns[2].visible"></el-table-column>
        <el-table-column prop="isChannel" label="是否渠道" width="80" v-if="columns[3].visible">
          <span slot-scope="{row}">{{row.isChannel?'是':'否'}}</span>
        </el-table-column>
        <el-table-column prop="subjectLocationAndLimitAmount" label="结算渠道及企业限额" min-width="150" v-if="columns[4].visible">
          <div slot-scope="{row}" style="display: inline-flex;gap: 5px;flex-wrap: wrap;">
            <el-tag v-for="i in row.subjectLocationAndLimitAmount[0]" :key="'g1'+i" effect="plain" type="success" style="width: 200px;">{{i}}</el-tag>
            <el-tag v-for="i in row.subjectLocationAndLimitAmount[1]" :key="'g2'+i" effect="plain" type="info" style="width: 200px;">{{i}}</el-tag>
          </div>
        </el-table-column>
        <el-table-column prop="certifiedUserCount" label="认证人数" width="80" v-if="columns[5].visible"></el-table-column>
        <el-table-column prop="packageUserCount" label="服务人数" width="80" v-if="columns[6].visible"></el-table-column>
        <el-table-column prop="signProduct" label="签约类型" width="80" v-if="columns[7].visible"></el-table-column>
        <el-table-column prop="lastYearGmv" label="上年月均年化" width="80" v-if="columns[8].visible"></el-table-column>
        <el-table-column prop="currentYearGmv" label="当年月均年化" width="80" v-if="columns[9].visible"></el-table-column>
        <el-table-column prop="nrr" label="NRR(%)" width="80" v-if="columns[10].visible"></el-table-column>
        <el-table-column prop="delFlagName" label="状态" width="80" v-if="columns[11].visible"></el-table-column>
      </el-table>
    </div>
    <div v-if="data" class="pagination-container">
      <el-pagination class="zshk-result-panel-pagination"
                     @current-change="loadData"
                     @size-change="handleSizeChange"
                     :current-page="data.page+1"
                     :page-size="pageSize"
                     layout="total, sizes, prev, pager, next"
                     :total="data.totalElements">
      </el-pagination>
    </div>
  </div>
</template>

<style scoped lang="scss">

</style>
