<script setup>
import { computed, reactive, ref, toRef, watch } from 'vue'
import ScreenModal from '@/components/ScreenModal.vue'
import { getCooperativeDevelopments } from '@/api/home'
import { displayEmpty } from '@/utils/displayEmpty'
import { buildScreenYearOptions } from '@/utils/screenYearOptions'
import { useDialogStatYearSync } from '@/utils/useDialogStatYearSync'
import { useScreenTownVillageOptions } from '@/utils/screenTownVillage'

const TAB_BASIC = 'basic'
const TAB_LIVESTOCK = 'livestock'
const TAB_MEMBER = 'member'
const TAB_BENEFIT = 'benefit'
const TAB_EMPLOYMENT = 'employment'
const TAB_TRAINING = 'training'
const TAB_SCOPE = 'scope'

const BUSINESS_SCOPE_COLUMNS = [
  '养殖业',
  '种养结合',
  '农产品加工',
  '农机服务',
  '劳务输出',
  '建筑工程',
  '旅游服务',
  '运输',
  '特色产品制作及销售',
  '其他'
]

const props = defineProps({
  modelValue: { type: Boolean, default: false }
})

const emit = defineEmits(['update:modelValue'])

const visible = computed({
  get: () => props.modelValue,
  set: (v) => emit('update:modelValue', v)
})

const query = reactive({
  statYear: undefined,
  statMonth: undefined,
  townDeptId: undefined,
  villageDeptId: undefined
})

const { townOptions, villageOptions, loadTownVillageOptions } = useScreenTownVillageOptions(
  toRef(query, 'townDeptId')
)
const loading = ref(false)
const tableRows = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const activeTab = ref(TAB_BASIC)

const yearSelectOptions = buildScreenYearOptions()

const { syncDialogYearFromGlobal } = useDialogStatYearSync(query, {
  visible,
  onSynced: () => {
    pageNum.value = 1
    fetchList()
  }
})

const monthOptions = Array.from({ length: 12 }, (_, i) => i + 1)

function parseBusinessScopeList(value) {
  if (value === null || value === undefined || value === '') {
    return []
  }
  return String(value)
    .split(/[,，]/)
    .map((s) => s.trim())
    .filter(Boolean)
}

/** 经营范围多选：命中显示「是」，否则走空值展示 */
function scopeCell(row, name) {
  const list = parseBusinessScopeList(row?.businessScope)
  if (!list.length) {
    return displayEmpty(null)
  }
  return list.includes(name) ? '是' : displayEmpty(null)
}

async function fetchList() {
  loading.value = true
  try {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      statYear: query.statYear,
      statMonth: query.statMonth
    }
    if (query.townDeptId != null && query.townDeptId !== '') {
      params.townDeptId = query.townDeptId
    }
    if (query.villageDeptId != null && query.villageDeptId !== '') {
      params.villageDeptId = query.villageDeptId
    }
    const res = await getCooperativeDevelopments(params)
    tableRows.value = res.rows || []
    total.value = Number(res.total) || 0
  } catch {
    tableRows.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  pageNum.value = 1
  fetchList()
}

function handleReset() {
  syncDialogYearFromGlobal()
  query.statMonth = undefined
  query.townDeptId = undefined
  query.villageDeptId = undefined
  activeTab.value = TAB_BASIC
  pageNum.value = 1
  fetchList()
}

function onTownChange() {
  query.villageDeptId = undefined
}

function onOpen() {
  syncDialogYearFromGlobal()
  query.statMonth = undefined
  query.townDeptId = undefined
  query.villageDeptId = undefined
  activeTab.value = TAB_BASIC
  pageNum.value = 1
  loadTownVillageOptions().then(() => fetchList())
}

function onClose() {
  tableRows.value = []
  total.value = 0
}

watch([pageNum, pageSize], () => {
  if (visible.value) {
    fetchList()
  }
})
</script>

<template>
  <ScreenModal
    v-model="visible"
    title="合作社数据明细"
    width="1480px"
    height="780px"
    max-width="98vw"
    max-height="94vh"
    @open="onOpen"
    @close="onClose"
  >
    <el-form :inline="true" :model="query" class="cd-form" @submit.prevent>
      <el-form-item label="年份">
        <el-select v-model="query.statYear" clearable placeholder="年份" style="width: 110px">
          <el-option v-for="y in yearSelectOptions" :key="y" :label="`${y}年`" :value="y" />
        </el-select>
      </el-form-item>
      <el-form-item label="月份">
        <el-select v-model="query.statMonth" clearable placeholder="月份" style="width: 100px">
          <el-option v-for="m in monthOptions" :key="m" :label="`${m}月`" :value="m" />
        </el-select>
      </el-form-item>
      <el-form-item label="乡镇">
        <el-select
          v-model="query.townDeptId"
          placeholder="全部乡镇"
          clearable
          filterable
          style="width: 160px"
          @change="onTownChange"
        >
          <el-option
            v-for="t in townOptions"
            :key="t.deptId"
            :label="t.deptName"
            :value="t.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="村">
        <el-select
          v-model="query.villageDeptId"
          placeholder="全部村"
          clearable
          filterable
          style="width: 160px"
        >
          <el-option
            v-for="v in villageOptions"
            :key="v.deptId"
            :label="v.deptName"
            :value="v.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="cd-tabs">
      <el-radio-group v-model="activeTab" size="small">
        <el-radio-button :value="TAB_BASIC">基础档案信息</el-radio-button>
        <el-radio-button :value="TAB_LIVESTOCK">牲畜存栏情况</el-radio-button>
        <el-radio-button :value="TAB_MEMBER">农牧民入社情况</el-radio-button>
        <el-radio-button :value="TAB_BENEFIT">年度效益发挥情况</el-radio-button>
        <el-radio-button :value="TAB_EMPLOYMENT">吸纳就业情况</el-radio-button>
        <el-radio-button :value="TAB_TRAINING">社员培训情况</el-radio-button>
        <el-radio-button :value="TAB_SCOPE">经营范围及模式</el-radio-button>
      </el-radio-group>
    </div>

    <el-table
      :key="activeTab"
      v-loading="loading"
      :data="tableRows"
      border
      stripe
      height="100%"
      class="cd-table"
      empty-text="暂无数据"
    >
      <el-table-column prop="statYear" label="年份" width="80" align="center">
        <template #default="{ row }">{{ displayEmpty(row.statYear) }}</template>
      </el-table-column>
      <el-table-column prop="statMonth" label="月份" width="70" align="center">
        <template #default="{ row }">{{ displayEmpty(row.statMonth) }}</template>
      </el-table-column>
      <el-table-column prop="villageName" label="村" min-width="100" show-overflow-tooltip>
        <template #default="{ row }">{{ displayEmpty(row.villageName) }}</template>
      </el-table-column>
      <el-table-column prop="cooperativeName" label="合作社名称" min-width="140" show-overflow-tooltip>
        <template #default="{ row }">{{ displayEmpty(row.cooperativeName) }}</template>
      </el-table-column>

      <template v-if="activeTab === TAB_BASIC">
        <el-table-column label="法定代表人" min-width="110" show-overflow-tooltip>
          <template #default="{ row }">{{ displayEmpty(row.legalRepresentative) }}</template>
        </el-table-column>
        <el-table-column label="成立时间" min-width="110" align="center">
          <template #default="{ row }">{{ displayEmpty(row.establishDate) }}</template>
        </el-table-column>
        <el-table-column label="注册资本(万元)" min-width="130" align="right">
          <template #default="{ row }">{{ displayEmpty(row.registeredCapital) }}</template>
        </el-table-column>
        <el-table-column label="截止年度总资产(万元)" min-width="160" align="right">
          <template #default="{ row }">{{ displayEmpty(row.yearEndTotalAssets) }}</template>
        </el-table-column>
        <el-table-column label="注册商标产品数量(个)" min-width="160" align="right">
          <template #default="{ row }">{{ displayEmpty(row.trademarkProductCount) }}</template>
        </el-table-column>
        <el-table-column label="农产品质量认证产品数量(个)" min-width="200" align="right">
          <template #default="{ row }">{{ displayEmpty(row.qualityCertProductCount) }}</template>
        </el-table-column>
        <el-table-column label="运营情况" min-width="100" align="center">
          <template #default="{ row }">{{ displayEmpty(row.operationStatus) }}</template>
        </el-table-column>
      </template>

      <template v-else-if="activeTab === TAB_LIVESTOCK">
        <el-table-column label="牛存栏(头)" min-width="110" align="right">
          <template #default="{ row }">{{ displayEmpty(row.cattleInventoryCount) }}</template>
        </el-table-column>
        <el-table-column label="牛出栏(头)" min-width="110" align="right">
          <template #default="{ row }">{{ displayEmpty(row.cattleOutboundCount) }}</template>
        </el-table-column>
        <el-table-column label="羊存栏(只)" min-width="110" align="right">
          <template #default="{ row }">{{ displayEmpty(row.sheepInventoryCount) }}</template>
        </el-table-column>
        <el-table-column label="羊出栏(只)" min-width="110" align="right">
          <template #default="{ row }">{{ displayEmpty(row.sheepOutboundCount) }}</template>
        </el-table-column>
      </template>

      <template v-else-if="activeTab === TAB_MEMBER">
        <el-table-column label="户数(户)" min-width="90" align="right">
          <template #default="{ row }">{{ displayEmpty(row.memberHouseholdCount) }}</template>
        </el-table-column>
        <el-table-column label="人数(人)" min-width="90" align="right">
          <template #default="{ row }">{{ displayEmpty(row.memberPopulationCount) }}</template>
        </el-table-column>
        <el-table-column label="防返贫检测(人)" min-width="130" align="right">
          <template #default="{ row }">{{ displayEmpty(row.povertyMonitorCount) }}</template>
        </el-table-column>
        <el-table-column label="牛入股(头)" min-width="100" align="right">
          <template #default="{ row }">{{ displayEmpty(row.cattleShareCount) }}</template>
        </el-table-column>
        <el-table-column label="羊入股(只)" min-width="100" align="right">
          <template #default="{ row }">{{ displayEmpty(row.sheepShareCount) }}</template>
        </el-table-column>
        <el-table-column label="牲畜总入股(头只)" min-width="140" align="right">
          <template #default="{ row }">{{ displayEmpty(row.livestockShareTotal) }}</template>
        </el-table-column>
        <el-table-column label="草场入股(万亩)" min-width="130" align="right">
          <template #default="{ row }">{{ displayEmpty(row.grasslandShareArea) }}</template>
        </el-table-column>
        <el-table-column label="劳动力入股(人)" min-width="130" align="right">
          <template #default="{ row }">{{ displayEmpty(row.laborShareCount) }}</template>
        </el-table-column>
        <el-table-column label="现金入股(万元)" min-width="130" align="right">
          <template #default="{ row }">{{ displayEmpty(row.cashShareAmount) }}</template>
        </el-table-column>
        <el-table-column label="其他入股(万元)" min-width="130" align="right">
          <template #default="{ row }">{{ displayEmpty(row.otherShareAmount) }}</template>
        </el-table-column>
      </template>

      <template v-else-if="activeTab === TAB_BENEFIT">
        <el-table-column label="总收入(万元)" min-width="120" align="right">
          <template #default="{ row }">{{ displayEmpty(row.totalIncome) }}</template>
        </el-table-column>
        <el-table-column label="纯收入(万元)" min-width="120" align="right">
          <template #default="{ row }">{{ displayEmpty(row.netIncome) }}</template>
        </el-table-column>
        <el-table-column label="现金分红(万元)" min-width="130" align="right">
          <template #default="{ row }">{{ displayEmpty(row.cashDividend) }}</template>
        </el-table-column>
        <el-table-column label="实物分红折算(万元)" min-width="150" align="right">
          <template #default="{ row }">{{ displayEmpty(row.inKindDividend) }}</template>
        </el-table-column>
        <el-table-column label="周转金(万元)" min-width="120" align="right">
          <template #default="{ row }">{{ displayEmpty(row.revolvingFund) }}</template>
        </el-table-column>
        <el-table-column label="亏损(万元)" min-width="110" align="right">
          <template #default="{ row }">{{ displayEmpty(row.lossAmount) }}</template>
        </el-table-column>
      </template>

      <template v-else-if="activeTab === TAB_EMPLOYMENT">
        <el-table-column label="吸纳大学生(人)" min-width="130" align="right">
          <template #default="{ row }">{{ displayEmpty(row.collegeGraduateCount) }}</template>
        </el-table-column>
        <el-table-column label="大学生工资性收入(万元)" min-width="180" align="right">
          <template #default="{ row }">{{ displayEmpty(row.collegeGraduateWage) }}</template>
        </el-table-column>
        <el-table-column label="农牧民转移就业(人)" min-width="150" align="right">
          <template #default="{ row }">{{ displayEmpty(row.farmerTransferEmploymentCount) }}</template>
        </el-table-column>
        <el-table-column label="农牧民工资性收入(万元)" min-width="180" align="right">
          <template #default="{ row }">{{ displayEmpty(row.farmerTransferWage) }}</template>
        </el-table-column>
      </template>

      <template v-else-if="activeTab === TAB_TRAINING">
        <el-table-column label="管理能力(人)" min-width="120" align="right">
          <template #default="{ row }">{{ displayEmpty(row.trainingManageCount) }}</template>
        </el-table-column>
        <el-table-column label="专业技能(人)" min-width="120" align="right">
          <template #default="{ row }">{{ displayEmpty(row.trainingSkillCount) }}</template>
        </el-table-column>
        <el-table-column label="其他(人)" min-width="100" align="right">
          <template #default="{ row }">{{ displayEmpty(row.trainingOtherCount) }}</template>
        </el-table-column>
      </template>

      <template v-else>
        <el-table-column
          v-for="name in BUSINESS_SCOPE_COLUMNS"
          :key="name"
          :label="name"
          min-width="110"
          align="center"
        >
          <template #default="{ row }">{{ scopeCell(row, name) }}</template>
        </el-table-column>
        <el-table-column label="经营模式分类" min-width="140" align="center" show-overflow-tooltip>
          <template #default="{ row }">{{ displayEmpty(row.businessModel) }}</template>
        </el-table-column>
      </template>
    </el-table>

    <div class="cd-pager">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        background
        layout="total, sizes, prev, pager, next"
        :total="total"
        :page-sizes="[10, 20, 50]"
      />
    </div>
  </ScreenModal>
</template>

<style scoped>
.cd-form {
  flex-shrink: 0;
  margin-bottom: 8px;
}

.cd-form :deep(.el-form-item__label) {
  color: #a8d4c8;
}

.cd-tabs {
  flex-shrink: 0;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.cd-table {
  width: 100%;
  flex: 1;
  min-height: 0;
}

.cd-pager {
  flex-shrink: 0;
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}
</style>
