<template>
  <view class="project">
    <!-- Tabs栏 -->
    <view class="cc-header">
      <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="queryParams.data.projectName" type="text" @confirm="handleSearchProjectList" placeholder="请输入项目名称" />
        </view>
      </view>
  
      <!-- 行政区划和项目类型下拉框 -->
      <view class="cc-query-dropdowns dropdowns">
        <region-picker @trigge-method="handleRegionParams" :isClearSelect="isClearSelect" />
        <project-type-picker @trigge-method="handleProjectTypeParams" :isClearSelect="isClearSelect" />
        <picker v-if="activeTab===2" mode="selector" :range="checkStatusOption" @change="onCheckStatusPickerChange">
          <view class="dropdown">{{checkStatusName}}<image src="/static/images/icon/down.png" /></view>
        </picker> 
      </view>
    </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">
            <template v-if="activeTab===0">
              <view class="primary-button__text button" @click="handleSeeProject(project, 'project')">查看</view>
              <view class="primary-button__text button" @click="handleEditProject(project, 'project')">编辑</view>
              <view class="error-button__text button" @click="handleDeleteProject(project, 'project')">删除</view>
            </template>
            <template v-if="activeTab===1">
              <view class="primary-button__text button" @click="handleEditProject(project, 'draft')">编辑</view>
              <view class="error-button__text button" @click="handleDeleteProject(project, 'draft')">删除</view>
            </template>
            <template v-if="activeTab===2">
              <view v-if="project.applicationStatus=='6'" class="primary-button__text button" @click="handleExamineProject(project, 'check')">审批</view>
              <view v-if="project.applicationStatus=='2' || project.applicationStatus=='3'" class="primary-button__text button" @click="handleExamineSeeProject(project, 'check')">查看</view>
              <view class="error-button__text button" @click="handleDeleteProject(project, 'check')">删除</view>
            </template>
          </view>
        </view>
      </view>
      <no-data-view v-if="projects.length === 0" />
      <uni-load-more v-if="queryParams.pageNum == pages" status="no-more"></uni-load-more>
    </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>

    <!-- 提示窗示例 -->
    <uni-popup ref="delectDialog" type="dialog">
      <uni-popup-dialog type="error" cancelText="取消" confirmText="确认" title="警告" content="是否确认删除该数据" @confirm="handleDeleteDialogConfirm"></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
import { getProjectListApi, projectApplyListApi } from '@/api/system/project'
import { listDraft } from '@/api/system/project/draft'
import { addressList } from '@/uni_modules/piaoyi-cityPicker/components/piaoyi-cityPicker/cityData.js'
import NoDataView from '@/components/no-data-view/no-data-view.vue'
import RegionPicker from '@/components/region-picker/region-picker.vue'
import ProjectTypePicker from '@/components/project-type-picker/project-type-picker.vue'
import { delInfo } from '@/api/system/project/projectInfo'
import { delProInfoApply } from '@/api/system/project/proInfoApply'
import { delDraft } from '@/api/system/project/draft'
export default {
  components: {
    NoDataView,
    RegionPicker,
    ProjectTypePicker
  },
  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: {
          projectName: '',
          adcd: '',
          applicationStatus: ''
        }
      },
      pages: 0,
      // 省市区数据
      addressTreeList: addressList,
      addressList: [],
      // 重大项目字典
      zd_projectTypeOptions: [],
      // 面上项目字典
      ms_projectTypeOptions: [],
      reviewStatus:[],
      checkStatusName: '审核状态',
      isClearSelect: false,
      deleteProjectId: ''
    };
  },
  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
      this.checkStatusOption = this.reviewStatus.map(item => item.dictLabel)
    })
  },
  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('again')
    },

    // 初始化列表参数
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        params: {orderBy: "create_time", sortBy: "desc"},
        data: {
          projectName: '',
          adcd: '',
          applicationStatus: ''
        }
      }
      this.checkStatusName = '审核状态'
      this.isClearSelect = true
    },

    // 处理区划请求
    handleRegionParams(adcd) {
      this.queryParams.pageNum = 1
      this.queryParams.data.adcd = adcd
      this.isClearSelect = false
      this.judgeGetList('again')
    },

    // 处理项目类型
    handleProjectTypeParams(params) {
      this.queryParams.pageNum = 1
      this.queryParams.data.projectType = params.projectType
      this.queryParams.data.isMajor = params.isMajor
      this.isClearSelect = false
      this.judgeGetList('again')
    },

    // 检索项目
    handleSearchProjectList() {
      this.queryParams.pageNum = 1
      this.judgeGetList('again')
    },

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

    // 获取项目列表
    getProjectList(mode) {
      uni.showLoading({
        title: '加载中...',
        mask: true
      })
      getProjectListApi(this.queryParams).then(res => {
        if (mode === 'again') {
          this.projects = []
          uni.pageScrollTo({
              scrollTop: 0, // 设置滚动到顶部
              duration: 300 // 滚动动画持续时间，单位为毫秒
          })
        }
        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(mode) {
      uni.showLoading({
        title: '加载中...',
        mask: true
      })
      listDraft(this.queryParams).then(res => {
        if (mode === 'again') {
          this.projects = []
          uni.pageScrollTo({
              scrollTop: 0, // 设置滚动到顶部
              duration: 300 // 滚动动画持续时间，单位为毫秒
          })
        }
        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(mode) {
      uni.showLoading({
        title: '加载中...',
        mask: true
      })
      projectApplyListApi(this.queryParams).then(res => {
        if (mode === 'again') {
          this.projects = []
          uni.pageScrollTo({
              scrollTop: 0, // 设置滚动到顶部
              duration: 300 // 滚动动画持续时间，单位为毫秒
          })
        }
        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
    },
    // 监听审核状态
    onCheckStatusPickerChange(event) {
      this.queryParams.data.applicationStatus = this.reviewStatus[event.detail.value].dictValue
      this.checkStatusName = this.reviewStatus[event.detail.value].dictLabel
      this.judgeGetList('again')
    },
    handleSeeProject(projectItem, pageType) {
      // 跳转到编辑项目页面
      uni.navigateTo({
        url: `/pages/project/edit/index?pageType=${pageType}&operateType=view&id=${projectItem.id}`
      });
    },
    handleAddProject() {
      // 跳转到新增项目页面
      uni.navigateTo({
        url: `/pages/project/edit/index?operateType=add`
      });
    },
    handleEditProject(projectItem, pageType) {
      // 跳转到编辑项目页面
      uni.navigateTo({
        url: `/pages/project/edit/index?pageType=${pageType}&operateType=edit&id=${projectItem.id}`
      });
    },
    handleExamineProject(projectItem, pageType) {
      // 跳转到编辑项目页面
      uni.navigateTo({
        url: `/pages/project/edit/index?pageType=${pageType}&operateType=examine&id=${projectItem.id}`
      });
    },
    handleExamineSeeProject(projectItem, pageType) {
      // 跳转到编辑项目页面
      uni.navigateTo({
        url: `/pages/project/edit/index?pageType=${pageType}&operateType=examineSee&id=${projectItem.id}`
      });
    },
    handleDeleteProject(projectItem, pegeType) {
      this.deleteProjectId = projectItem.id
      this.$refs.delectDialog.open()
    },

    // 处理删除
    handleDeleteDialogConfirm() {
      if (this.activeTab === 0) {
        this.handleDeleteProjectRequest()
      } else if (this.activeTab === 1) {
        this.handleDeleteProjectDraftRequest()
      } else {
        this.handleDeleteProjectApplyRequest()
      }
    },
    handleDeleteProjectRequest() {
      delInfo(this.deleteProjectId).then(res => {
        uni.showToast({
          title: `删除项目成功`,
          icon: 'none'
        })
        this.judgeGetList('again')
      })
    },
    handleDeleteProjectDraftRequest() {
      delDraft(this.deleteProjectId).then(res => {
        uni.showToast({
          title: `删除项目成功`,
          icon: 'none'
        })
        this.judgeGetList('again')
      })
    },
    handleDeleteProjectApplyRequest() {
      delProInfoApply(this.deleteProjectId).then(res => {
        uni.showToast({
          title: `删除项目成功`,
          icon: 'none'
        })
        this.judgeGetList('again')
      })
    }
  }
};
</script>

<style lang="scss" scoped>
.project {
  .cc-project-list {
    padding-top: 162px;
  }
}
</style>