<template>
  <!-- 基础页面 -->
  <div class="app-container">
    <el-form v-show="showSearch" :model="queryParams" ref="queryForm" size="small" inline @submit.native.prevent>
            <el-form-item label="分公司" prop="impUnitName">
        <el-select
          v-model="queryParams.impUnitName"
          placeholder="请选择分公司"
          clearable
          filterable
          style="width: 240px"
          @change="handleImpUnitChange"
        >
          <el-option
            v-for="item in impUnitOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="项目部" prop="departName">
        <el-select
          v-model="queryParams.departName"
          placeholder="请选择项目部"
          clearable
          filterable
          style="width: 240px"
          @change="handleDepartChange"
        >
          <el-option
            v-for="item in departOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="工程" prop="proId">
        <el-select
          v-model="queryParams.proId"
          placeholder="请选择工程"
          clearable
          filterable
          style="width: 240px"
          @change="getTeamListAndSubUnit"
        >
          <el-option v-for="(item, index) in proOptions" :key="index" :label="item.proName" :value="item.proId" />
        </el-select>
      </el-form-item>

      <el-form-item label="班组名称" prop="teamName">
        <el-select
          v-model="queryParams.teamName"
          placeholder="请选择班组"
          clearable
          filterable
          style="width: 240px"
        >
          <el-option
            v-for="item in teamOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="工程名称" prop="proId">
        <el-select
          v-model="queryParams.proId"
          placeholder="请选择工程名称"
          filterable
          style="width: 240px"
          @change="changePro"
        >
          <el-option v-for="(item, index) in projectList" :key="index" :label="item.proName" :value="item.proId" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="关键字" prop="keyWord">
        <el-input
          v-model="queryParams.keyWord"
          placeholder="请输入关键字"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 240px"
        />
      </el-form-item>

      <!-- 表单按钮 -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出数据</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table :data="tableList" fit highlight-current-row style="width: 100%" v-loading="isLoading" :max-height="650">
      <el-table-column
        type="index"
        width="55"
        label="序号"
        align="center"
        :index="index => (queryParams.pageNum - 1) * queryParams.pageSize + index + 1"
      />
      <el-table-column
        v-for="(column, index) in tableColumns"
        :show-overflow-tooltip="!column.unShowTooltip"
        :width="column.width"
        :key="index"
        :label="column.label"
        :prop="column.prop"
        align="center"
      >
        <!-- 插槽 -->
        <template v-slot="{ row }" v-if="column.prop == 'teamStatus'">
          <el-tag v-if="row.teamStatus == 1" type="info">空闲</el-tag>
          <el-tag v-else-if="row.teamStatus == 2" type="success">申报</el-tag>
          <el-tag v-else-if="row.teamStatus == 3">进场</el-tag>
        </template>
        <template v-slot="{ row }" v-else-if="column.prop == 'isDismiss'">
          <el-tag v-if="row.isDismiss == 0">否</el-tag>
          <el-tag v-else type="danger">是</el-tag>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { getTeamInOrOutInfoApi, getListProject,getImpUnitListApi, getDepartListByImpUnitApi, getProListByDepartApi, getTeamList, } from '@/api/materialsStation'

export default {
  name: 'TeamEntrance',
  data() {
    return {
      isLoading: false,
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: '', // 关键字
        proId: '',
        startTime: '', // 开始时间
        endTime: '', // 结束时间
        impUnitName: null,
        departName: null,
        proName: null,
        teamName: null,
      },
      total: 0, // 总条数
      // 表头
      tableColumns: [
        { label: '分公司', prop: 'impUnitName', unShowTooltip: true },
        { label: '项目部', prop: 'departName', unShowTooltip: true },
        { label: '工程名称', prop: 'projectName', unShowTooltip: true },
        { label: '班组分包名称', prop: 'subcontractor', unShowTooltip: true },
        { label: '班组名称', prop: 'teamName' },
        { label: '班组状态', prop: 'teamStatus', width: 120 },
        { label: '是否解散', prop: 'isDismiss', width: 120 },
        { label: '实际进场时间', prop: 'actualProcessTime', width: 150 },
        { label: '实际出场时间', prop: 'actualExitTime', width: 150 }
      ],
      // 表格数据
      tableList: [],
      projectList: [],
      impUnitOptions: [],   // 分公司下拉
      departOptions: [],    // 项目部下拉
      proOptions: [],       // 工程下拉
      teamOptions: [],      // 班组下拉
    }
  },
  async created() {
    await this.getImpUnitOptions()
    await this.handleImpUnitChange()
    await this.handleDepartChange()
    await this.getTeamListAndSubUnit()
    await this.getList()
  },
  methods: {
    format(date) {
      const y = date.getFullYear()
      const m = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${y}-${m}-${day}`
    },
    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.queryParams.keyWord = ''
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.queryParams.impUnitName = null
      this.queryParams.departName = null
      this.queryParams.teamName = null
      this.tableList = []
      this.getList()
    },

    /** 获取分公司下拉 */
    async getImpUnitOptions() {
      try {
        const res = await getImpUnitListApi() // 调后台接口
        this.impUnitOptions = res.data.map(item => ({
          label: item.impUnitName,   // 这里根据实际字段替换
          value: item.impUnitName
        }))
      } catch (e) {
        console.error('获取分公司下拉失败:', e)
      }
    },
    /** 分公司选择变化，加载项目部 */
    async handleImpUnitChange() {
      this.queryParams.departName = null // 清空项目部已选
      this.departOptions = []            // 清空原有下拉

      try {
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
          departName: this.queryParams.departName, // 项目部名称
          proName: this.queryParams.proName,
          teamName:this.queryParams.teamName,
          subUnitName:this.queryParams.subUnitName,
        }
        const res = await getDepartListByImpUnitApi(params)
        this.departOptions = res.data.map(item => ({
          label: item.departName,   // 项目部名称字段
          value: item.departName
        }))
      } catch (e) {
        console.error('获取项目部下拉失败:', e)
      }
    },

    // async projectInfoList() {
    //   try {
    //     const res = await getListProject({ unitId: null, isApp: true,impUnit:this.queryParams.impUnitName })
    //     if (res.data.length === 0) return
    //     this.proOptions = res.data
    //     console.log('🚀 ~ projectInfoList ~ this.queryParams.proId:', this.queryParams.proId)
    //     this.getList()
    //   } catch (error) {
    //     console.log('🚀 ~ projectInfoList ~ error:', error)
    //   }
    // },

    /** 项目部选择变化，加载工程 */
    async handleDepartChange() {
      this.queryParams.proId = null // 清空工程已选
      this.proOptions = []            // 清空原有下拉

      try {
        // 同时传入分公司和项目部参数
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
          departName: this.queryParams.departName,
          unitId: null, isApp: true,
        }
        const res = await getListProject(params)
        this.proOptions = res.data
        this.queryParams.proId = res.data[0].proId
        this.queryParams.proName = res.data[0].proName
        console.log("zzzzzzzzzzzzzzzzzz",this.queryParams.proName)
      } catch (e) {
        console.error('获取工程下拉失败:', e)
      }
    },

    async getTeamListAndSubUnit() {
      this.queryParams.teamName = null // 清空工程已选
      this.teamOptions = []            // 清空原有下拉
      console.log("yyyyyyyyyyyyyyyy",this.queryParams.proName)
      this.queryParams.proName = this.proOptions.find(item => item.proId == this.queryParams.proId)?.proName || null;
      console.log("Xxxxxxxxxxxxxxxxxxx",this.queryParams.proName)
      try {
        // 同时传入分公司和项目部参数
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
          departName: this.queryParams.departName, // 项目部名称
          proName: this.queryParams.proName,
          teamName:this.queryParams.teamName,
        }
        const res = await getTeamList(params)
        this.teamOptions = res.data.map(item => ({
          label: item.teamName,   // 工程名称字段
          value: item.teamName
        }))
      } catch (e) {
        console.error('获取班组下拉失败:', e)
      }
    },

    // changePro() {
    //   this.getList()
    // },
    // /** 工程-下拉选 */
    // async projectInfoList() {
    //   try {
    //     const res = await getListProject({ unitId: null, isApp: true })
    //     if (res.data.length === 0) return
    //     this.projectList = res.data
    //     this.queryParams.proId = res.data[0].proId
    //     console.log('🚀 ~ projectInfoList ~ this.queryParams.proId:', this.queryParams.proId)
    //     this.getList()
    //   } catch (error) {
    //     console.log('🚀 ~ projectInfoList ~ error:', error)
    //   }
    // },
    // 获取列表
    async getList() {
      console.log('列表-查询', this.queryParams)
      this.isLoading = true
      try {
        const params = {
          ...this.queryParams,
          // startTime: this.queryParams.timeRange ? this.queryParams.timeRange[0] : '',
          // endTime: this.queryParams.timeRange ? this.queryParams.timeRange[1] : ''
        }
        delete params.timeRange
        console.log('🚀 ~ getList ~ params:', params)
        const res = await getTeamInOrOutInfoApi(params)
        console.log('🚀 ~ 获取列表 ~ res:', res)
        this.tableList = res.data.rows || []
        this.total = res.data.total || 0
      } catch (error) {
        console.log('🚀 ~ 获取列表 ~ error:', error)
        this.tableList = []
        this.total = 0
      } finally {
        this.isLoading = false
      }
    },
    // 导出数据
    formatTime(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}${month}${day}_${hours}${minutes}${seconds}`
    },
    // 导出数据
    handleExport() {
      try {
        let fileName = `班组进出场查询_${this.formatTime(new Date())}.xLsx`
        let url = '/material/material_maMachine/exportTeamInOrOutInfo'
        const params = { ...this.queryParams }
        console.log('🚀 ~ 导出 ~ params:', params)
        this.download(url, params, fileName)
      } catch (error) {
        console.log('导出数据失败', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>
