<script>
import scorePackageStatusDict from "@/utils/dict/ScorePackageStatus";
import {getDictMap} from "@/api/cso_sys_dict";
import {search, listConsignees, listConsignors,exportXlsx} from "@/api/sys_impl_plan";
import dayjs from "@/plugins/dayjs";
import ColumnsSelect from "@/components/ColumnsSelect/index.vue";

export default {
  name: 'SysImplPlan',
  components: {ColumnsSelect},
  data() {
    return {
      searchForm: {
        planName: null,
        createTimeRange: null,
        consignorId:null,
        consigneeId:null,
        planState:null,
        disassembleState:null,
      },
      searchParams: {
        planName: null,
        createTimeGe: null,
        createTimeLe:null,
        consignorId:null,
        consigneeId:null,
        planState:null,
        disassembleState:null,
      },
      data: null,
      pageSize: 10,
      scorePackageStatusDict,
      showLevel: -1,
      nextId:0,
      loading:false,
      consignors:[],
      consignees:[],
      planStateDict:{},
      disassembleStateDict:{},
      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 }
      ],
    }
  },
  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.consignors = await listConsignors()
      this.consignees = await listConsignees()
      this.planStateDict=await getDictMap('plan_state')
      this.disassembleStateDict=await getDictMap('disassemble_state')
    },
    async search() {
      this.searchParams = {
        planName: this.searchForm.planName,
        createTimeGe: this.searchForm.createTimeRange ? this.formatStartDate(this.searchForm.createTimeRange[0]) : null,
        createTimeLe: this.searchForm.createTimeRange ? this.formatEndDate(this.searchForm.createTimeRange[1]) : null,
        consignorId: this.searchForm.consignorId,
        consigneeId: this.searchForm.consigneeId,
        planState: this.searchForm.planState,
        disassembleState: this.searchForm.disassembleState
      }
      await this.loadData(1)
    },
    formatStartDate(value){
      return dayjs(value).startOf('date').toISOString()
    },
    formatEndDate(value){
      return dayjs(value).endOf('date').toISOString()
    },
    async loadData(page) {
      this.loading=true
      try {
        const params = {
          page: page - 1,
          size: this.pageSize,
          ...this.searchParams,
          fetchChildrenCount:true
        }
        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
      row.hasChildren = row.childrenCount>0
      row.planDuration=row.planIssue+'至'+row.planExpiry
      row.createTime=dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')
    },
    formatPlanState(planState){
      return this.planStateDict[planState]||planState
    },
    formatDisassembleState(disassembleState){
      return this.disassembleStateDict[disassembleState]||disassembleState
    },
    async loadChildren(row, treeNode, resolve) {
      const data = await search({
        page: 0,
        size: 10000,
        parentId: row.planId,
        fetchChildrenCount: true
      })
      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
        }
        const filename = await exportXlsx(params)
        this.$download.name(filename, true)
      } finally {
        this.$modal.closeLoading()
      }
    },
    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-input v-model="searchForm.planName"></el-input>
      </el-form-item>
      <el-form-item label="源头包发包时间">
        <el-date-picker v-model="searchForm.createTimeRange" type="daterange" style="width: 230px;"></el-date-picker>
      </el-form-item>
      <el-form-item label="来源对象">
        <el-select v-model="searchForm.consignorId" filterable clearable>
          <el-option
            v-for="item in consignors"
            :key="item.deptId"
            :label="item.name"
            :value="item.deptId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="承接对象">
        <el-select v-model="searchForm.consigneeId" filterable clearable>
          <el-option
            v-for="item in consignees"
            :key="item.deptId"
            :label="item.name"
            :value="item.deptId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="下发状态">
        <el-select v-model="searchForm.planState" filterable clearable>
          <el-option
            v-for="(label,value) in planStateDict"
            :key="value"
            :label="label"
            :value="value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="拆解状态">
        <el-select v-model="searchForm.disassembleState" filterable clearable>
          <el-option
            v-for="(label,value) in disassembleStateDict"
            :key="value"
            :label="label"
            :value="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">
      </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="planId" border lazy max-height="600" :load="loadChildren">
        <el-table-column prop="no" label="序号" width="120"></el-table-column>
        <el-table-column prop="planName" label="计划包名称" v-if="columns[0].visible"></el-table-column>
        <el-table-column prop="planScore" label="计划分值" width="100" v-if="columns[1].visible"></el-table-column>
        <el-table-column prop="planDuration" label="计划周期" width="190" v-if="columns[2].visible"></el-table-column>
        <el-table-column prop="consignor.name" label="来源对象" v-if="columns[3].visible"></el-table-column>
        <el-table-column prop="consignee.name" label="承接对象" v-if="columns[4].visible"></el-table-column>
        <el-table-column prop="sku" label="推广药品" v-if="columns[5].visible"></el-table-column>
        <el-table-column prop="planState" label="下发状态" width="90" v-if="columns[6].visible">
          <span slot-scope="{row}">{{formatPlanState(row.planState)}}</span>
        </el-table-column>
        <el-table-column prop="disassembleState" label="拆解状态" width="90" v-if="columns[7].visible">
          <span slot-scope="{row}">{{formatDisassembleState(row.disassembleState)}}</span>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" v-if="columns[8].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>
