<template>
  <div class="project-inventory-page">
    <!-- 查询表单 -->
    <div class="query-form-container">
      <div class="query-form-basic">
        <el-form class="query-form-fields" :inline="true" :model="queryForm" size="small">
          <el-form-item label="项目名称">
            <el-input v-model="queryForm.projectName" clearable placeholder="请输入" style="width: 180px" />
          </el-form-item>
          <el-form-item label="项目状态">
            <el-select v-model="queryForm.projectStatus" clearable placeholder="请选择" style="width: 150px">
              <el-option v-for="item in projectStatusOptions" :key="item.key" :label="item.value" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="计划交付时间">
            <el-date-picker
              v-model="queryForm.planDeliveryTimeRange"
              end-placeholder="结束日期"
              range-separator="至"
              start-placeholder="开始日期"
              style="width: 260px"
              type="daterange"
              value-format="yyyy-MM-dd" />
          </el-form-item>
        </el-form>
        <div class="query-form-actions">
          <el-button icon="el-icon-search" type="primary" @click="handleSearch">查询</el-button>
          <el-button icon="el-icon-refresh-right" @click="handleReset">重置</el-button>
          <el-button type="text" @click="showAdvanced = !showAdvanced">
            {{ showAdvanced ? '收起' : '高级筛选' }}
            <i :class="showAdvanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" />
          </el-button>
          <el-divider direction="vertical" />
          <el-button icon="el-icon-download" type="success" @click="handleExport">导出</el-button>
        </div>
      </div>

      <div v-show="showAdvanced" class="query-form-advanced">
        <el-form :inline="true" :model="queryForm" size="small">
          <el-form-item label="合同编号">
            <el-input v-model="queryForm.contractNo" clearable placeholder="请输入" style="width: 150px" />
          </el-form-item>
          <el-form-item label="产品线">
            <el-select v-model="queryForm.productLine" clearable placeholder="请选择" style="width: 130px">
              <el-option v-for="item in productLineOptions" :key="item.key" :label="item.value" :value="item.key" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="main-content">
      <!-- 左侧人员筛选 -->
      <div :class="['person-sidebar', { collapsed: sidebarCollapsed }]">
        <div class="sidebar-header">
          <div v-if="!sidebarCollapsed" class="sidebar-title-group">
            <span class="sidebar-title">人员筛选</span>
          </div>
          <div class="sidebar-actions">
            <button
              class="collapse-trigger"
              :title="sidebarCollapsed ? '展开' : '折叠'"
              type="button"
              @click="toggleSidebar">
              <i :class="sidebarCollapsed ? 'el-icon-d-arrow-right' : 'el-icon-d-arrow-left'" />
            </button>
          </div>
        </div>
        <div v-if="sidebarCollapsed" class="sidebar-collapsed-label">人员列表</div>
        <template v-if="!sidebarCollapsed">
          <!-- 页签切换 -->
          <div class="person-tabs">
            <div :class="['person-tab', { active: personTab === 'delivery' }]" @click="switchPersonTab('delivery')">
              交付
            </div>
            <div :class="['person-tab', { active: personTab === 'operation' }]" @click="switchPersonTab('operation')">
              运维
            </div>
          </div>
          <!-- 人员搜索 -->
          <el-input
            v-model="personSearch"
            class="person-search"
            clearable
            placeholder="搜索人员姓名"
            prefix-icon="el-icon-search"
            size="small" />
          <!-- 人员列表 -->
          <div class="person-list">
            <div
              v-if="allPersonOption"
              :class="['person-item', 'person-item--all', { active: selectedPerson === allPersonOption.userId }]"
              @click="selectPerson(allPersonOption.userId)">
              <div>
                <div class="person-name">{{ allPersonOption.userName }}</div>
                <div class="person-desc">查看全部项目</div>
              </div>
            </div>
            <div
              v-for="person in filteredPersonList"
              :key="person.userId"
              :class="['person-card', { active: selectedPerson === person.userId }]"
              @click="selectPerson(person.userId)">
              <div class="person-card-info">
                <span class="person-name">{{ person.nickName || person.userName }}</span>
                <span class="person-role">{{ person.roleName }}</span>
              </div>
              <div v-if="person.deptName" class="person-dept">{{ person.deptName }}</div>
              <i v-if="selectedPerson === person.userId" class="el-icon-check person-card-check" />
            </div>
          </div>
        </template>
      </div>

      <!-- 右侧数据表格 -->
      <div class="table-container">
        <div class="table-scroll-wrapper">
          <el-table
            v-loading="loading"
            border
            class="project-inventory-table"
            :data="tableData"
            :fit="false"
            height="100%"
            stripe
            style="width: 100%">
            <el-table-column align="center" type="index" width="50" />
            <el-table-column label="合同编号" prop="contractNo" show-overflow-tooltip width="120" />
            <el-table-column label="项目名称" min-width="200" prop="projectName" show-overflow-tooltip />
            <el-table-column label="产品线" prop="productLine" width="120">
              <template slot-scope="{ row }">
                <el-tag effect="plain" size="small" type="primary">
                  {{ getProductLineLabel(row.productLine) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="项目状态" prop="projectStatus" width="100">
              <template slot-scope="{ row }">
                <el-tag size="small" :type="getProjectStatusType(row.projectStatus)">
                  {{ getProjectStatusLabel(row.projectStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="交付节点" prop="deliveryNode" width="120">
              <template slot-scope="{ row }">
                {{ getDeliveryNodeLabel(row.deliveryNode) }}
              </template>
            </el-table-column>
            <el-table-column label="交付负责人" prop="deliveryUserName" show-overflow-tooltip width="120" />
            <el-table-column label="销售负责人" prop="salesUserName" show-overflow-tooltip width="120" />
            <el-table-column label="计划交付时间" prop="planDeliveryTime" width="120">
              <template slot-scope="{ row }">
                {{ formatDate(row.planDeliveryTime) }}
              </template>
            </el-table-column>
            <el-table-column label="计划验收时间" prop="planAcceptTime" width="120">
              <template slot-scope="{ row }">
                {{ formatDate(row.planAcceptTime) }}
              </template>
            </el-table-column>
            <el-table-column align="right" header-align="center" label="合同金额" prop="contractAmount" width="150">
              <template slot-scope="{ row }">
                <span class="amount-text">{{ formatAmount(row.contractAmount) }}</span>
              </template>
            </el-table-column>
            <el-table-column align="right" header-align="center" label="回款金额" prop="collectedAmount" width="150">
              <template slot-scope="{ row }">
                <span :class="['amount-text', { 'text-success': row.collectedAmount >= row.contractAmount }]">
                  {{ formatAmount(row.collectedAmount) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="客户名称" min-width="180" prop="custName" show-overflow-tooltip />
            <el-table-column align="center" fixed="right" header-align="center" label="操作" width="100">
              <template slot-scope="{ row }">
                <el-button size="mini" type="text" @click="handleViewDetail(row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            background
            :current-page.sync="queryForm.pageNum"
            layout="total, sizes, prev, pager, next, jumper"
            :page-size.sync="queryForm.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange" />
        </div>
      </div>
    </div>

    <!-- 产品详情浮窗 -->
    <el-dialog
      :title="`产品清单 - ${currentProject ? currentProject.projectName : ''}`"
      :visible.sync="productDialogVisible"
      width="800px">
      <el-table border :data="productList" stripe>
        <el-table-column align="center" type="index" width="50" />
        <el-table-column label="产品型号" prop="prodCode" show-overflow-tooltip width="150" />
        <el-table-column label="产品名称" min-width="180" prop="prodName" show-overflow-tooltip />
        <el-table-column label="产品类别" prop="prodClass" show-overflow-tooltip width="120" />
        <el-table-column align="center" label="数量" prop="prodNum" width="80" />
        <el-table-column align="right" header-align="center" label="成交价格" prop="tranPrice" width="120">
          <template slot-scope="{ row }">
            {{ formatAmount(row.tranPrice) }}
          </template>
        </el-table-column>
        <el-table-column align="right" header-align="center" label="合同总价" prop="contractPrive" width="120">
          <template slot-scope="{ row }">
            {{ formatAmount(row.contractPrive) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="维保期" prop="maintTerm" width="100">
          <template slot-scope="{ row }">{{ row.maintTerm }}个月</template>
        </el-table-column>
        <el-table-column label="备注" min-width="150" prop="remark" show-overflow-tooltip />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
  import projectInventoryApi from '@/api/devops/projectInventory'
  import { parseTime } from '@/utils'
  import to from 'await-to-js'
  import { projectStatusTagTypes, getTagType } from '@/config/devopsTagTypes'

  export default {
    name: 'ProjectInventory',
    data() {
      return {
        loading: false,
        showAdvanced: false,
        sidebarCollapsed: false,
        productDialogVisible: false,
        currentProject: null,
        productList: [],
        queryForm: {
          pageNum: 1,
          pageSize: 20,
          contractNo: '',
          projectName: '',
          productLine: '',
          projectStatus: '',
          deliveryUserId: null,
          opsManagerUserId: null,
          salesUserId: null,
          planDeliveryTimeRange: [],
        },
        personSearch: '',
        personTab: 'delivery',
        selectedPerson: 'all',
        allPersonOption: { userId: 'all', userName: '全部人员', nickName: '全部人员' },
        personList: [],
        tableData: [],
        total: 0,
        productLineOptions: [],
        projectStatusOptions: [],
        deliveryNodeOptions: [],
      }
    },
    computed: {
      filteredPersonList() {
        if (!this.personSearch) return this.personList
        const search = this.personSearch.toLowerCase()
        return this.personList.filter(
          (p) =>
            (p.userName && p.userName.toLowerCase().includes(search)) ||
            (p.nickName && p.nickName.toLowerCase().includes(search))
        )
      },
    },
    created() {
      this.initDicts()
      this.loadPersonList()
      this.loadData()
    },
    methods: {
      getTagType,
      initDicts() {
        Promise.all([
          this.getDicts('sys_product_line'),
          this.getDicts('delivery_project_status'),
          this.getDicts('delivery_node'),
        ])
          .then(([productLine, projectStatus, deliveryNode]) => {
            this.productLineOptions = productLine.data.values || []
            this.projectStatusOptions = projectStatus.data.values || []
            this.deliveryNodeOptions = deliveryNode.data.values || []
          })
          .catch((err) => console.log(err))
      },
      loadPersonList() {
        projectInventoryApi.getProjectManagers('all').then((res) => {
          if (res.code === 0 || res.code === 200) {
            this.personList = res.data || []
          }
        })
      },
      loadData() {
        this.loading = true
        const params = { ...this.queryForm }

        if (params.planDeliveryTimeRange && params.planDeliveryTimeRange.length === 2) {
          params.planDeliveryTimeStart = params.planDeliveryTimeRange[0]
          params.planDeliveryTimeEnd = params.planDeliveryTimeRange[1]
        }
        delete params.planDeliveryTimeRange

        // 根据页签类型设置对应的人员ID过滤
        if (this.selectedPerson !== 'all') {
          if (this.personTab === 'delivery') {
            params.deliveryUserId = parseInt(this.selectedPerson)
          } else if (this.personTab === 'operation') {
            params.opsManagerUserId = parseInt(this.selectedPerson)
          }
        }

        projectInventoryApi
          .getList(params)
          .then((res) => {
            if (res.code === 0 || res.code === 200) {
              this.tableData = res.data?.list || []
              this.total = res.data?.total || 0
            }
          })
          .finally(() => {
            this.loading = false
          })
      },
      handleSearch() {
        this.queryForm.pageNum = 1
        this.loadData()
      },
      handleReset() {
        this.queryForm = {
          pageNum: 1,
          pageSize: 20,
          contractNo: '',
          projectName: '',
          productLine: '',
          projectStatus: '',
          deliveryUserId: null,
          opsManagerUserId: null,
          salesUserId: null,
          planDeliveryTimeRange: [],
        }
        this.selectedPerson = 'all'
        this.loadData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.loadData()
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.queryForm.pageNum = 1
        this.loadData()
      },
      toggleSidebar() {
        this.sidebarCollapsed = !this.sidebarCollapsed
      },
      switchPersonTab(tab) {
        this.personTab = tab
        this.selectedPerson = 'all'
        this.queryForm.pageNum = 1
        this.loadData()
      },
      selectPerson(userId) {
        this.selectedPerson = userId
        this.queryForm.pageNum = 1
        this.loadData()
      },
      handleViewDetail(row) {
        if (row.contractId) {
          this.currentProject = row
          projectInventoryApi.getContractProducts(row.contractId).then((res) => {
            if (res.code === 0 || res.code === 200) {
              this.productList = res.data || []
              this.productDialogVisible = true
            }
          })
        }
      },
      async handleExport() {
        const params = {
          contractNo: this.queryForm.contractNo,
          projectName: this.queryForm.projectName,
          productLine: this.queryForm.productLine,
          projectStatus: this.queryForm.projectStatus,
        }

        // 根据页签类型设置对应的人员ID过滤
        if (this.selectedPerson !== 'all') {
          if (this.personTab === 'delivery') {
            params.deliveryUserId = parseInt(this.selectedPerson)
          } else if (this.personTab === 'operation') {
            params.opsManagerUserId = parseInt(this.selectedPerson)
          }
        }

        if (this.queryForm.planDeliveryTimeRange && this.queryForm.planDeliveryTimeRange.length === 2) {
          params.planDeliveryTimeStart = this.queryForm.planDeliveryTimeRange[0]
          params.planDeliveryTimeEnd = this.queryForm.planDeliveryTimeRange[1]
        }

        const [err, res] = await to(projectInventoryApi.exportList(params))
        if (err) {
          this.$message.error('导出失败')
          return
        }
        if (res.data?.content) {
          try {
            const binaryString = window.atob(res.data.content)
            const len = binaryString.length
            const bytes = new Uint8Array(len)
            for (let i = 0; i < len; i++) {
              bytes[i] = binaryString.charCodeAt(i)
            }
            const blob = new Blob([bytes], {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            })
            const link = document.createElement('a')
            const url = window.URL.createObjectURL(blob)
            link.href = url
            link.download = `项目清单_${new Date().getTime()}.xlsx`
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            window.URL.revokeObjectURL(url)
            this.$message.success('导出成功')
          } catch (e) {
            console.error('下载失败', e)
            this.$message.error('文件下载失败')
          }
        } else {
          this.$message.warning('没有可导出的数据')
        }
      },
      formatDate(time) {
        return time ? parseTime(time, '{y}-{m}-{d}') : '-'
      },
      formatAmount(amount) {
        if (amount === null || amount === undefined) return '-'
        return '¥' + parseFloat(amount).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
      },
      getProductLineLabel(value) {
        const label = this.selectDictLabel(this.productLineOptions, value)
        return label || value || '-'
      },
      getProjectStatusLabel(value) {
        const label = this.selectDictLabel(this.projectStatusOptions, value)
        return label || value || '-'
      },
      getProjectStatusType(value) {
        return getTagType(projectStatusTagTypes, value, 'info')
      },
      getDeliveryNodeLabel(value) {
        const label = this.selectDictLabel(this.deliveryNodeOptions, value)
        return label || value || '-'
      },
    },
  }
</script>

<style lang="scss" scoped>
  .project-inventory-page {
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    min-height: 0;
    height: calc(100vh - 122px);
    padding: 4px;
    background: #f5f7fa;
    overflow: hidden;

    .query-form-container {
      flex-shrink: 0;
      margin-bottom: 4px;
      padding: 8px 12px;
      background: #fff;
      border-radius: 6px;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);

      .query-form-basic {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        gap: 16px;

        .query-form-fields {
          flex: 1;
          min-width: 0;
        }

        .query-form-actions {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          flex-shrink: 0;
          min-height: 32px;
          white-space: nowrap;
        }

        ::v-deep .el-form {
          display: flex;
          flex-wrap: wrap;
          align-items: center;
          row-gap: 2px;
        }

        ::v-deep .el-form-item {
          margin-right: 20px;
          margin-bottom: 2px;
        }

        ::v-deep .el-form-item__label {
          padding-right: 8px;
          font-size: 13px;
          color: #606266;
        }

        ::v-deep .el-divider--vertical {
          margin: 0 12px;
        }
      }

      .query-form-advanced {
        margin-top: 8px;
        padding-top: 8px;
        border-top: 1px dashed #e4e7ed;

        ::v-deep .el-form {
          display: flex;
          flex-wrap: wrap;
          align-items: center;
          row-gap: 2px;
        }

        ::v-deep .el-form-item {
          margin-right: 20px;
          margin-bottom: 2px;
        }

        ::v-deep .el-form-item__label {
          padding-right: 8px;
          font-size: 13px;
          color: #606266;
        }
      }
    }

    .main-content {
      flex: 1;
      display: flex;
      gap: 4px;
      overflow: hidden;
      min-height: 0;

      .person-sidebar {
        display: flex;
        flex-direction: column;
        width: 280px;
        min-height: 0;
        background: #fff;
        border-radius: 4px;
        padding: 8px;
        flex-shrink: 0;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
        transition: width 0.2s ease, padding 0.2s ease;
        overflow: hidden;

        &.collapsed {
          width: 44px;
          padding: 8px 4px;
          align-items: center;
        }

        .sidebar-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 6px;

          .sidebar-title-group {
            display: flex;
            align-items: center;
            gap: 6px;

            .sidebar-title {
              font-weight: 500;
              font-size: 14px;
              color: #303133;
            }
          }

          .sidebar-actions {
            .collapse-trigger {
              background: none;
              border: none;
              cursor: pointer;
              color: #909399;
              padding: 4px;

              &:hover {
                color: #409eff;
              }
            }
          }
        }

        .sidebar-collapsed-label {
          writing-mode: vertical-rl;
          text-orientation: mixed;
          padding: 16px 4px;
          font-size: 14px;
          font-weight: 500;
          color: #606266;
          text-align: center;
        }

        .person-tabs {
          display: flex;
          gap: 8px;
          margin-bottom: 8px;

          .person-tab {
            flex: 1;
            text-align: center;
            padding: 8px 12px;
            border-radius: 4px;
            background: #f5f7fa;
            cursor: pointer;
            font-size: 14px;
            color: #606266;
            transition: all 0.2s ease;

            &:hover {
              background: #ecf5ff;
              color: #409eff;
            }

            &.active {
              background: #409eff;
              color: #fff;
            }
          }
        }

        .person-search {
          margin-bottom: 8px;
        }

        .person-list {
          flex: 1;
          overflow-y: auto;
          padding-right: 2px;

          .person-item--all {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px;
            margin-bottom: 8px;
            border-radius: 4px;
            background: #f5f7fa;
            cursor: pointer;

            &:hover,
            &.active {
              background: #ecf5ff;
            }

            .person-name {
              font-weight: 600;
              font-size: 14px;
              color: #303133;
            }

            .person-desc {
              font-size: 12px;
              color: #909399;
              margin-top: 4px;
            }
          }

          .person-card {
            position: relative;
            padding: 12px;
            border-radius: 4px;
            cursor: pointer;
            margin-bottom: 8px;
            border: 1px solid #ebeef5;

            &:hover {
              border-color: #409eff;
              background: #f5f7fa;
            }

            &.active {
              border-color: #409eff;
              background: #ecf5ff;
            }

            .person-card-info {
              display: flex;
              align-items: center;
              gap: 8px;
              margin-bottom: 4px;

              .person-name {
                font-weight: 500;
                font-size: 14px;
                color: #303133;
              }

              .person-role {
                font-size: 11px;
                color: #409eff;
                background: #ecf5ff;
                padding: 2px 6px;
                border-radius: 2px;
              }
            }

            .person-dept {
              font-size: 12px;
              color: #909399;
            }

            .person-card-check {
              position: absolute;
              top: 8px;
              right: 8px;
              color: #409eff;
            }
          }
        }
      }

      .table-container {
        flex: 1;
        display: flex;
        flex-direction: column;
        min-width: 0;
        min-height: 0;
        padding: 6px 8px;
        overflow: hidden;
        background: #fff;
        border-radius: 4px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);

        .table-scroll-wrapper {
          display: flex;
          flex: 1;
          min-width: 0;
          min-height: 0;
          overflow: hidden;
        }

        .pagination-wrapper {
          margin-top: auto;
          display: flex;
          justify-content: flex-end;
          padding-top: 4px;

          ::v-deep .el-pagination {
            padding: 0;
            line-height: 32px;
          }
        }
      }
    }

    .amount-text {
      font-family: 'Roboto Mono', monospace;
      font-weight: 500;

      &.text-success {
        color: #67c23a;
      }
    }

    .project-inventory-table {
      flex: 1;
      min-width: 0;
    }
  }
</style>
