<template>
  <view class="project">
    <!-- Tabs栏 -->
    <view class="cc-tabs tabs">
      <view class="tab" :class="{'active': activeTab === 0}" @click="changeTab(0)">
        <view class="tab-text">项目管理</view>
      </view>
      <view class="tab" :class="{'active': activeTab === 1}" @click="changeTab(1)">
        <view class="tab-text">草稿</view>
      </view>
      <view class="tab" :class="{'active': activeTab === 2}" @click="changeTab(2)">
        <view class="tab-text">上报记录</view>
      </view>
    </view>

    <!-- 搜索框 -->
    <view class="cc-search search-bar">
      <view class="search-box">
        <image src="/static/images/icon/search.png" />
        <input v-model="searchQuery" type="text" placeholder="请输入项目名称或项目编号" />
      </view>
    </view>

    <!-- 行政区划和项目类型下拉框 -->
    <view class="cc-query-dropdowns dropdowns">
      <view class="uni-picker" @click="handleOpenSelect">
        <view class="dropdown">
          <view class="d-text">{{cityName}}</view>
          <image src="/static/images/icon/down.png" />
        </view>
      </view>
      <picker mode="selector" :range="projectTypes" @change="onProjectTypePickerChange">
        <view class="dropdown">{{projectType}}<image src="/static/images/icon/down.png" /></view>
      </picker>
      <picker v-if="activeTab===2" mode="selector" :range="checkStatusOption" @change="onCheckStatusPickerChange">
        <view class="dropdown">{{checkStatus}}<image src="/static/images/icon/down.png" /></view>
      </picker>
    </view>

    <!-- 项目列表 -->
    <view class="cc-project-list project-list" :class="{'no-bottom':activeTab!==0}">
      <view v-for="(project, index) in projects" :key="index" class="project-card">
        <view class="attr-item project-title">{{ project.projectName }}</view>
        <view class="attr-item">
          <view class="attr-title">项目编号</view>
          <view class="attr-value">{{ project.proCode }}</view>
        </view>
        <view class="attr-item">
          <view class="attr-title">行政区划</view>
          <view class="attr-value">{{ project.adcdName }}</view>
        </view>
        <view class="attr-item">
          <view class="attr-title">项目类型</view>
          <view class="attr-value">{{ project.projectTypeName }}</view>
        </view>
        <view v-if="activeTab===2" class="attr-item">
          <view class="attr-title">审核状态</view>
          <view
            class="attr-value"
            :class="project.applicationStatus==0 || project.applicationStatus==2? 'no-done' : 'success'"
          >{{ project.checkStatusName }}</view>
        </view>
        <view class="operate-buttons">
          <view class="buttons-group">
            <view v-if="activeTab===0" class="primary-button__text button" @click="handleSeeProject(project)">查看</view>
            <view v-if="activeTab!==2" class="primary-button__text button" @click="handleEditProject(project)">编辑</view>
            <view v-if="activeTab!==2" class="error-button__text button" @click="handleDeleteProject(project)">删除</view>
            <view v-if="activeTab===2" class="primary-button__text button">
              <view v-if="project.status==0" @click="handleExamineProject(project)">审批</view>
              <view v-else @click="handleExamineSeeProject(project)">查看</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view v-if="activeTab===0" class="cc-operation-buttons operation-buttons">
      <view class="buttons-group">
        <view class="primary-button button" @click="handleAddProject()">新增</view>
      </view>
    </view>

    <cityPicker :column="column" :default-value="defaultValue" :mask-close-able="maskCloseAble" @confirm="confirm" @cancel="cancel" :visible="visible"/>
  </view>
</template>

<script>
import { getProjectListApi, projectApplyListApi } from '@/api/system/project'
import { addressList } from '@/uni_modules/piaoyi-cityPicker/components/piaoyi-cityPicker/cityData.js'
export default {
  data() {
    return {
      activeTab: 0,  // 当前选中的Tab索引
      searchQuery: '',  // 搜索框的内容
      selectedDistrict: 0,  // 行政区划选择的索引
      selectedProjectType: 0,  // 项目类型选择的索引
      districts: ['请选择', '北京市', '上海市', '广州市'],  // 行政区划数据
      projectTypes: ['建筑', 'IT', '教育'],  // 项目类型数据
      checkStatusOption: ['审核', '未审核'],
      projects: [  // 项目列表
        // { name: '项目1', code: '010101', district: '北京市', type: '建筑', status: 1 },
        // { name: '项目2', code: '010102', district: '上海市', type: 'IT', status: 0},
        // { name: '项目3', code: '010103', district: '广州市', type: '教育', status: 1},
        // { name: '项目4', code: '010104', district: '北京市', type: '建筑', status: 1},
        // { name: '项目5', code: '010105', district: '北京市', type: '建筑', status: 1}
      ],
      // 省市区选项属性
      visible: false,
      maskCloseAble: true,
      str: '',
      defaultValue: '420103',
      column: 3,
      cityName: '行政区划',
      projectType: '项目类型',
      checkStatus: '审核状态',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        params: {orderBy: "create_time", sortBy: "desc"},
        data: {}
      },
      pages: 0,
      // 省市区数据
      addressTreeList: addressList,
      addressList: [],
      // 重大项目字典
      zd_projectTypeOptions: [],
      // 面上项目字典
      ms_projectTypeOptions: [],
      reviewStatus:[],
    };
  },
  computed: {
    // filteredProjects() {
    //   return this.projects.filter(project => {
    //     // 根据搜索内容、行政区划和项目类型进行筛选
    //     const matchesSearch = project.name.toLowerCase().includes(this.searchQuery.toLowerCase());
    //     const matchesDistrict = this.selectedDistrict === 0 || project.district === this.districts[this.selectedDistrict];
    //     const matchesType = this.selectedProjectType === 0 || project.type === this.projectTypes[this.selectedProjectType];
    //     return matchesSearch && matchesDistrict && matchesType;
    //   });
    // }
    
  },
  created() {
    this.handleAddressTreeData()
    this.getProjectList()
    this.getDicts("major_project").then((response) => {
      this.zd_projectTypeOptions = response.data
    })
    this.getDicts("general_project").then((response) => {
      this.ms_projectTypeOptions = response.data
    })
    this.getDicts("review_status").then((response)=>{
      this.reviewStatus = response.data
    })
  },
  onReachBottom() {
    if (this.queryParams.pageNum < this.pages) {
      this.queryParams.pageNum++; // 页码加1
      this.judgeGetList()
    }
  },
  methods: {
    // 切换tab栏
    changeTab(index) {
      this.activeTab = index
      this.resetQuery()
      this.projects = []
      this.judgeGetList()
    },

    // 初始化列表参数
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        params: { orderBy: "create_time", sortBy: "desc" },
        data: {}
      }
    },

    // 判断获取哪个列表
    judgeGetList() {
      if (this.activeTab === 0) {
        this.getProjectList()
      } else if (this.activeTab === 1) {
        this.getProjectDraftList()
      } else {
        this.getProjectApplyList()
      }
    },

    // 获取项目列表
    getProjectList() {
      uni.showLoading({
        title: '加载中...',
        mask: true
      })
      getProjectListApi(this.queryParams).then(res => {
        this.projects = [...this.projects, ...res.records]
        this.pages = res.pages
        this.projects.forEach(projectItem => {
          projectItem.adcdName = this.formatAdcd(projectItem)
          projectItem.projectTypeName = this.projectTypeFormat(projectItem)
        })
        uni.hideLoading()
      })
    },

    // 获取项目草稿列表
    getProjectDraftList() {
      uni.showLoading({
        title: '加载中...',
        mask: true
      })
      getProjectListApi(this.queryParams).then(res => {
        this.projects = [...this.projects, ...res.records]
        this.pages = res.pages
        this.projects.forEach(projectItem => {
          projectItem.adcdName = this.formatAdcd(projectItem)
          projectItem.projectTypeName = this.projectTypeFormat(projectItem)
        })
        uni.hideLoading()
      })
    },

    // 获取项目草稿列表
    getProjectApplyList() {
      uni.showLoading({
        title: '加载中...',
        mask: true
      })
      projectApplyListApi(this.queryParams).then(res => {
        this.projects = [...this.projects, ...res.records]
        this.pages = res.pages
        this.projects.forEach(projectItem => {
          projectItem.adcdName = this.formatAdcd(projectItem)
          projectItem.projectTypeName = this.projectTypeFormat(projectItem)
          projectItem.checkStatusName = this.reviewFormat(projectItem)
        })
        uni.hideLoading()
      })
    },

    // 将省市区的树状数据分解成列表,并在后面补零
    handleAddressTreeData() {
      let result = [];
      function traverse(node) {
        result.push({ code: node.code, name: node.name, dictLabel: node.name, dictValue: node.code}); // 将当前节点添加到结果中
        if (node.children) {
          node.children.forEach(child => traverse(child)); // 递归遍历子节点
        }
      }
      this.addressTreeList.forEach(node => traverse(node)); // 遍历树的每个根节点
      this.addressList = result
      this.addressList.forEach(item => {
        if (item.code.length===2) {
          item.code = item.dictValue = item.code + '0000'
        }
        if (item.code.length===4) {
          item.code = item.dictValue = item.code + '00'
        }
      })
    },

    // 处理省市区显示
    formatAdcd(row) {
      if (row.adcd) {
        let provinceCode = row.adcd.slice(0, 2)+"0000";
        let cityCode = row.adcd.slice(0, 4)+"00";
        let areaCode = row.adcd;
        let s="";
        if (areaCode.length > 2) {
            s=this.areaCodeFormat(provinceCode)
            if (cityCode!=provinceCode){
              s+="-"+this.areaCodeFormat(cityCode)
            }
            if (areaCode!=cityCode){
              s+="-" + this.areaCodeFormat(areaCode)
            }
         }
        return s
      }
    },

    //行政区划字典
    areaCodeFormat(adcd, column) {
      return this.selectDictLabel(
        this.addressList,
        adcd
      );
    },

    // 项目类型字典翻译
    projectTypeFormat(row, column) {
      if (row.isMajor == "zd") {
        return this.selectDictLabel(
          this.zd_projectTypeOptions,
          row.projectType
        );
      } else if (row.isMajor == "ms") {
        return this.selectDictLabel(
          this.ms_projectTypeOptions,
          row.projectType
        );
      }else if (row.isMajor !=null){
        return '其他'
      }
    },

    // 判断审核状态
    reviewFormat(row, column){
      return this.selectDictLabel(
        this.reviewStatus,
        row.applicationStatus,
      );
    },

    // 展开省市区选项
    handleOpenSelect() {
      this.visible = true
    },
    cancel () {
      this.visible = false
    },
    confirm (val) {
      console.log(val)
      this.str = JSON.stringify(val)
      this.cityName = val.name
      this.visible = false
    },
    // 监听项目类型切换
    onProjectTypePickerChange(event) {
      this.projectType = this.projectTypes[event.detail.value]
    },
    // 监听审核状态
    onCheckStatusPickerChange(event) {
      this.checkStatus = this.checkStatusOption[event.detail.value]
    },
    handleAddProject() {
      // 跳转到新增项目页面
      uni.navigateTo({
        url: `/pages/project/edit/index?operateType=add`
      });
    },
    handleEditProject() {
      // 跳转到编辑项目页面
      uni.navigateTo({
        url: '/pages/project/edit/index?operateType=edit&id=123123'
      });
    },
    handleSeeProject() {
      // 跳转到编辑项目页面
      uni.navigateTo({
        url: '/pages/project/edit/index?operateType=see&id=123123'
      });
    },
    handleExamineProject() {
      // 跳转到编辑项目页面
      uni.navigateTo({
        url: '/pages/project/edit/index?operateType=examine&id=123123'
      });
    },
    handleExamineSeeProject() {
      // 跳转到编辑项目页面
      uni.navigateTo({
        url: '/pages/project/edit/index?operateType=examineSee&id=123123'
      });
    },
    handleDeleteProject() {
      uni.showToast({
        title: `删除项目`,
        icon: 'none'
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.project {
}
</style>