<template>
  <div class="full-height full-width flex flex-col">
    <div class="flex flex-col padding white-bg">
      <div class="flex flex-align-center tip">
        <el-icon class="ml-20" color="#BC002D">
          <WarningFilled/>
        </el-icon>
        <span class="ml-5">项目总投资额<span
            class="main-color bold">{{ num ? Number.parseFloat(num).toLocaleString() : '-' }}</span>万元</span>
      </div>
      <div class="flex ml-20 hide-scrollbar" style="overflow-x: scroll;width: 86vw;"
           v-show='numList && numList.length > 0'>
        <div v-for="(item,index) in numList" :key='item.id' :class="active === index ? 'total-s' : 'total'"
             class="flex flex-center flex-justify-between mt-20 bold font-16 pointer" @click='switchTab(item,index)'
        >
          <span class=" sp">{{ item.name }}</span>
          <span class=" sp1 ">{{ item.number }}<span class="grey font-13">个</span></span>
        </div>
      </div>
      <div class='flex flex-center flex-justify-start'>
        <base-button class="ml-20 mt-20" icon="Plus" title="新增"
                     @click="showAdd = true"/>
        <base-button class="ml-20 mt-20" icon="el-icon-upload" title="数据导入"
                     @click="diaType = 0"/>
        <base-button class="ml-20 mt-20" icon="el-icon-download" title="数据导出"
                     @click="diaType = 1"/>
        <base-button class="ml-20 mt-20" type="0" icon="el-icon-download" title="汇总数据导出"
                     @click="diaType = 2"/>
      </div>
    </div>
    <avue-crud ref="crud"
               v-model="form"
               v-model:page="page"
               :before-open="beforeOpen"
               :data="data"
               :option="option"
               :permission="permissionList"
               :table-loading="loading"
               class="curd"
               @row-del="rowDel"
               @tree-load="treeLoad"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template #menu="{row}">
        <el-button icon="Upload" type='primary' text @click="track(row)"> {{
            row.isReport === 1 ? "已经上报" : "项目上报"
          }}
        </el-button>
      </template>
    </avue-crud>
    <!--    新增-->
    <el-dialog v-model="showAdd"
               append-to-body
               center
               title="新增项目"
               width="35%">
      <div v-loading='addLoading'>
        <el-form ref='form' :model="projectForm" class="lab mt-20" label-width="100px" :rules="rules">
          <div class="flex flex-center flex-col mr-20">
            <el-form-item class="full-width" label="项目名称" prop='name'>
              <el-input
                  v-model="projectForm.name"
                  clearable
                  placeholder="输入项目名称"
              />
            </el-form-item>
            <el-form-item class="full-width" label="项目总投" prop='totalAmount'>
              <el-input
                  v-model="projectForm.totalAmount"
                  clearable
                  placeholder="输入项目总投(万元)"
              >
                <template #append>(万元)</template>
              </el-input>
            </el-form-item>
            <el-form-item class="full-width" label="项目类型" prop='projectType'>
              <el-select
                  v-model="projectForm.projectType"
                  clearable
                  placeholder="选择项目类型"
                  style="width: 100%"
              >
                <el-option
                    v-for="item in typeList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item class="full-width" label="项目标签" prop='tags'>
              <el-select
                  v-model="projectForm.tags"
                  clearable
                  placeholder="选择项目标签"
                  style="width: 100%"
              >
                <el-option
                    v-for="item in tagsList"
                    :key="item.dictKey"
                    :label="item.dictValue"
                    :value="item.dictKey"
                />
              </el-select>
            </el-form-item>
            <el-form-item class="full-width" label="建设内容">
              <el-input
                  v-model="projectForm.introduction"
                  :rows="6"
                  clearable
                  placeholder="输入项目建设内容"
                  type="textarea"
              />
            </el-form-item>
            <div class="flex flex-center mt-10">
              <base-button class="mr-20" icon="Close" title="取消" type="0" @click="showAdd = false"/>
              <base-button icon="Check" title="保存" @click="projectSave"/>
            </div>
          </div>
        </el-form>
      </div>
    </el-dialog>
    <form-dialog :dialogType="diaType" @close="diaType = -1" @export='exportExcel'/>
    <summary-dialog :dialogType="diaType" @close="diaType = -1"/>
  </div>
</template>

<script>
import BaseButton from '../../../components/base-button.vue'
import permissionStore from '@/store/permission.js'
import {vaildData} from '@/utils/tools.js'
import formDialog from '@/views/home/component/form_dialog.vue'
import {getLazyList} from '@/api/project/index.js'
import summaryDialog from "@/views/home/component/summary_dialog.vue";

export default {
  name: 'dash',
  components: {BaseButton, formDialog, summaryDialog},
  setup() {
    const permissions = permissionStore()
    return {permissions}
  },
  data() {
    return {
      disable: false,
      showAdd: false,
      active: 0,
      loading: false,
      addLoading: false,
      data: [],
      form: {},
      option: {
        refreshBtn: false,
        tip: false,
        lazy: true,
        columnBtn: false,
        searchShow: true,
        selection: true,
        editBtn: true,
        editBtnText: '资料管理',
        editBtnIcon: 'Document',
        addBtn: false,
        delBtn: true,
        border: true,
        index: true,
        align: 'center',
        viewBtn: true,
        viewBtnText: '详情',
        menuWidth: 380,
        dialogClickModal: false,
        column: [
          {
            label: '项目名称',
            prop: 'name',
            addDisplay: false,
            editDisplay: false
          },
          {
            label: '项目情况',
            prop: 'projectStage',
            type: 'select',
            width: 180,
            dicUrl: '/api/blade-system/dict-biz/dictionary?code=project-situation',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '项目总投资（万元）',
            prop: 'totalAmount',
            width: 180,
            type: 'number',
            precision: 2,
            formatter: (val, value, label) => {
              return val.totalAmount.toLocaleString()
            }
          },
          {
            label: '股（科）室',
            prop: 'createDeptName',
            width: 180
          },
          {
            label: '子项目数量',
            prop: 'lot',
            width: 180
          },
          {
            label: '是否开工',
            prop: 'isStart',
            width: 180,
            dicData: [
              {
                label: '否',
                value: 0
              },
              {
                label: '是',
                value: 1
              }
            ]
          },
          {
            label: '项目类型',
            prop: 'projectTypeName',
            width: 180
          },
          {
            label: '创建时间',
            prop: 'createTime',
            width: 180
          }]
      },
      page: {
        size: 10,
        current: 1,
        total: 0
      },
      stage: [],
      numList: [],
      typeList: [],
      tagsList: [],
      num: '',
      projectForm: {
        name: '',
        totalAmount: '',
        projectType: '',
        tags: '',
        introduction: ''
      },
      rules: {
        name: [
          {required: true, message: '请输入项目名称', trigger: 'blur'}
        ],
        projectType: [
          {
            required: true,
            message: '请选择项目类型',
            trigger: 'change'
          }
        ],
        tags: [
          {
            required: true,
            message: '请选择项目标签',
            trigger: 'change'
          }
        ]
      },
      diaType: -1,
      parentId: 0,
      queryData: null
    }
  },
  created() {
    this.getTypeList()
    this.getNumList()
    this.$bus.on('serach', (res) => {
      if (res.dictKey === '') {
        this.active = 0
        this.onLoad(res)
      }
    })
  },
  computed: {
    permissionList() {
      return {
        delBtn: vaildData(this.permissions.permissions.home_del, false)
      }
    }
  },
  methods: {
    switchTab(item, index) {
      this.active = index
      this.onLoad({projectStage: item.dictKey})
    },
    onLoad(query = {}) {
      this.loading = true
      const data = {...query, parentId: this.parentId}
      this.queryData = data
      this.$api.project.projectList(this.page.currentPage, this.page.pageSize, data).then(res => {
        this.loading = false
        if (res.code === 200) {
          this.data = res.data.records.map(e => {
            e.projectStage = e.projectStage + ''
            return e
          })
          this.page.total = res.data.total
        }
      }).finally(() => {
        this.loading = false
      })
    },
    beforeOpen(done, type) {
      if (['edit'].includes(type)) {
        this.$router.push({
          path: '/home/details',
          query: {id: this.form.id, type: '0', ownerId: this.form.createUser}
        })
      } else if (type === 'view') {
        // this.$alert('功能建设中，尽情期待...', '消息提醒', {
        //   confirmButtonText: 'OK'
        // })
        this.$router.push({
          path: '/home/pro_detail',
          query: {id: this.form.id}
        })
      }
    },
    currentChange(currentPage) {
      this.page.current = currentPage
    },
    sizeChange(pageSize) {
      this.page.size = pageSize
    },
    refreshChange() {
      this.onLoad()
    },
    treeLoad(tree, treeNode, resolve) {
      this.loading = true
      getLazyList(tree.id).then(res => {
        this.loading = false
        resolve(res.data.data.childrenList.map(e => {
          e.projectStage = e.projectStage.toString()
          return e
        }))
      })
    },
    rowDel(row) {
      this.$confirm('确定删除选择的项目?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
          .then(() => {
            this.$api.project.projectRemove({ids: row.id}).then(res => {
              if (res.code === 200) {
                this.$message.success(res.msg)
                this.onLoad()
              } else {
                this.$message.error(res.msg)
              }
            })
          })
    },
    getNumList() {
      this.$api.project.userNunList().then(res => {
        if (res.code === 200) {
          this.numList = res.data.projectStage
          this.num = res.data.totalAmount
        }
      })
    },
    getTotalAmount(data) {
      this.$api.project.totalAmount(Object.assign(data, this.query)).then(res => {
        if (res.code === 200) {
          this.num = res.data
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    getTypeList() {
      this.$api.project.typeList({type: 1, size: 999, current: 1}).then(res => {
        this.typeList = res.data.records
      })
      this.$api.common.dicList({code: 'project-tags'}).then(res => {
        if (res.code === 200) {
          this.tagsList = res.data
        }
      })
    },
    track(res) {
      if (res.isReport === 1) {
        this.$message.error('该项目已经上报')
        return
      }
      this.$confirm('是否确定进行项目上报', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {id: res.id, isReport: 1}
        this.$api.project.proUpdate(data).then(res => {
          if (res.code === 200) {
            console.log(res)
            this.$message.success(res.msg)
          } else {
            this.$message.error(res.msg)
          }
        })
      })
    },
    projectSave() {
      if (this.disable) {
        this.$message.error('正在处理，请稍后...')
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.disable = true
          this.addLoading = true
          this.$api.project.projectAdd(this.projectForm).then(res => {
            this.disable = false
            this.addLoading = false
            if (res.code === 200) {
              this.showAdd = false
              this.$message.success(res.msg)
              this.onLoad()
            } else {
              this.showAdd = false
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    exportExcel(res) {
      const data = Object.assign(this.queryData, {columnName: res})
      this.$api.params.exportResult(data).then(res => {
        const url = window.URL.createObjectURL(new Blob([res], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}))
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        const excelName = new Date().getTime() + '.xlsx'
        link.setAttribute('download', excelName)
        document.body.appendChild(link)
        link.click()
        link.remove()
        this.diaType = -1
        this.$message.success('导出成功')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tip {
  width: 260px;
  height: 38px;
  background-color: #FBF6ED;
  font-weight: 500;
  flex-wrap: nowrap;
  margin-left: 20px;
}

.total-s {
  width: 200px;
  height: 50px;
  border: 1px solid #825618;
  border-radius: 10px;
  margin-right: 20px;
  box-shadow: 2px 2px 10px 2px rgba(113, 73, 39, 0.3);

  .sp {
    color: #ECAB56;
    white-space: nowrap;
    margin-left: 20px;
  }

  .sp1 {
    color: #ECAB56;
    margin-right: 20px;
  }
}

.total {
  width: 200px;
  height: 50px;
  border-radius: 10px;
  margin-right: 20px;
  background-color: #F0F2F7;

  .sp {
    color: #707070;
    white-space: nowrap;
    margin-left: 20px;
  }

  .sp1 {
    color: #825618;
    margin-right: 20px;
  }
}

.curd {
  :deep(.avue-crud__menu) {
    min-height: 10px;
  }
}
</style>
