<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() : '0'
          }}</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="新增"
          v-if="
            dataType === 'project' &&
            permissions.vaildPermission('project_new_create')
          "
          @click="showAdd = true"
        />
        <base-button
          class="ml-20 mt-20"
          icon="el-icon-upload"
          title="数据导入"
          v-if="dataType === 'project'"
          @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"
        />
        <base-button
          class="ml-20 mt-20"
          type="0"
          icon="el-icon-coordinate"
          title="项目结转"
          @click="projectCarry"
        />
      </div>
    </div>
    <avue-crud
      ref="crud"
      v-model="form"
      v-model:page="page"
      :before-open="beforeOpen"
      :permission="permissions"
      :data="data"
      :option="option"
      :table-loading="loading"
      class="curd"
      @row-del="rowDel"
      @tree-load="treeLoad"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @selection-change="selectionChange"
      @on-load="onLoad"
    >
      <template #menu="{ row }">
        <el-button
          v-if="
            dataType === 'asset' && row.project_stage !== 7 && row.can_update
          "
          icon="Upload"
          type="primary"
          text
          @click="report(row)"
        >
          {{ row.is_report === 1 ? '项目已上报' : '项目上报' }}
        </el-button>
        <el-button
          v-if="
            (row.report_type === 0 ||
              row.report_type === 1 ||
              row.report_type === 4) &&
            row.can_update
          "
          text
          type="primary"
          icon="el-icon-upload"
          @click="projectReport(row)"
          >上报审核
        </el-button>
        <el-button
          text
          v-if="
            permissions.vaildPermission('projectApprovalBtn') &&
            row.report_type === 2
          "
          type="primary"
          icon="el-icon-bell"
          @click="rowClick(row, 1)"
          >审核
        </el-button>
        <el-button
          v-if="
            row.hasOwnProperty('report_type') &&
            row.report_type === 3 &&
            row.can_update
          "
          text
          type="primary"
          icon="el-icon-upload"
          @click="projectReportFormal(row)"
          >上报固定资产
        </el-button>
        <el-button
          text
          type="primary"
          icon="el-icon-folder-remove"
          @click="projectCancel(row)"
          v-if="row.project_stage !== 7 && row.can_update"
          >退库
        </el-button>
        <el-button
          text
          type="primary"
          icon="el-icon-delete"
          @click="rowDel(row)"
          v-if="row.can_update"
          >删除
        </el-button>
      </template>
      <template #plan_storage_time-header="{ column }">
        <div class="flex flex-center">
          <div class="mr-5">{{ (column || {}).label }}</div>
          <el-tooltip content="红色为计划开工时间,蓝色为实际开工时间">
            <el-icon>
              <InfoFilled />
            </el-icon>
          </el-tooltip>
        </div>
      </template>
      <template #plan_storage_time="{ row }">
        <div class="flex flex-center">
          <div
            class="mr-5 red"
            v-if="row.plan_storage_time !== undefined && row.is_storage === 0"
          >
            {{ row.plan_storage_time.substring(0, 10) }}
          </div>
          <div class="mr-5 blue" v-else>
            {{ row.storage_time ? row.storage_time.substring(0, 10) : '' }}
          </div>
        </div>
      </template>

      <template #plan_commencement_time-header="{ column }">
        <div class="flex flex-center">
          <div class="mr-5">{{ (column || {}).label }}</div>
          <el-tooltip content="红色为计划开工时间,蓝色为实际开工时间">
            <el-icon>
              <InfoFilled />
            </el-icon>
          </el-tooltip>
        </div>
      </template>
      <template #plan_commencement_time="{ row }">
        <div class="flex flex-center">
          <div
            class="mr-5 red"
            v-if="
              row.plan_commencement_time !== undefined &&
              (row.is_start === undefined || row.is_start === 0)
            "
          >
            {{ row.plan_commencement_time.substring(0, 10) }}
          </div>
          <div class="mr-5 blue" v-else>
            {{ row.start_time ? row.start_time.substring(0, 10) : '' }}
          </div>
        </div>
      </template>
      <template #project_stage="{ row }">
        <div class="flex flex-center">
          <div>{{ row['$project_stage'] }}</div>
          <el-tooltip :content="row.exit_msg" v-if="row.project_stage === 7">
            <el-icon @click="showReceipt(row.exit_msg)">
              <InfoFilled />
            </el-icon>
          </el-tooltip>
        </div>
      </template>
      <template #report_type="{ row }">
        <div class="flex flex-center">
          <el-tag>{{ row.report_type_name }}</el-tag>
          <el-tooltip :content="row.receipt_msg">
            <el-icon
              v-if="row.report_type === 4"
              class="ml-10"
              @click="showReceipt(row.receipt_msg)"
            >
              <WarningFilled />
            </el-icon>
          </el-tooltip>
        </div>
      </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="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="formDialogClose"
      @export="exportExcel"
      :ids="selectList"
      :year="owerQuery.projectYear"
    />
    <summary-dialog
      :dialogType="diaType"
      @close="diaType = -1"
      :select-num="selectList.length === 0 ? page.total : selectList.length"
      @export="exportExcelTotal"
    />
    <el-dialog v-model="reportShow" width="500px" title="请选择上报时间">
      <div v-if="currentReport">
        <el-date-picker
          v-model="currentReport.report_time"
          format="YYYY-MM-DD"
          class="mb-20"
          placeholder="选择上报时间"
          style="width: 100%"
          value-format="YYYY-MM-DD"
        />
      </div>
      <div class="flex flex-center full-width flex-justify-end">
        <el-button @click="reportShow = false">取 消</el-button>
        <el-button @click="track(currentReport)">确 定</el-button>
      </div>
    </el-dialog>
    <!--    项目审批-->
    <el-dialog v-model="showApproval" title="审核" width="500px">
      <div class="flex flex-justify-start flex-col">
        <div class="full-width flex flex-justify-start flex-align-center mb-20">
          <span>审核状态：</span>
          <el-radio-group v-model="approvalStatus">
            <el-radio :label="3">通过</el-radio>
            <el-radio :label="4">不通过</el-radio>
          </el-radio-group>
        </div>
        <el-input
          class="mt-20"
          type="textarea"
          :rows="5"
          v-model="approvalMsg"
          placeholder="请填写审批意见"
        />
        <div class="full-width flex flex-justify-end mt-20">
          <el-button plain type="primary" @click="showApproval = false"
            >取消
          </el-button>
          <el-button type="primary" @click="projectApproval">确定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import BaseButton from '../../../components/base-button.vue'
import permissionStore from '@/store/permission.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'
import { useStore } from '@/store/user.js'
import confing from '@/config/website'
import { ElMessageBox } from 'element-plus'

export default {
  name: 'dash',
  components: { BaseButton, formDialog, summaryDialog },
  setup() {
    const permissions = permissionStore()
    const user = useStore()
    return { permissions, user }
  },
  data() {
    return {
      showApproval: false,
      approvalMsg: '',
      approvalStatus: 3,
      reportTime: '',
      currentReport: null,
      reportShow: false,
      dialogLoading: false,
      disable: false,
      showAdd: false,
      active: 0,
      loading: false,
      addLoading: false,
      data: [],
      form: {},
      option: {
        menuBtnTitle: '操作',
        refreshBtn: false,
        tip: false,
        lazy: true,
        columnBtn: false,
        searchShow: true,
        selection: true,
        editBtn: true,
        editBtnText: '资料管理',
        editBtnIcon: 'Document',
        addBtn: false,
        delBtn: false,
        border: true,
        reserveSelection: true,
        align: 'center',
        viewBtn: true,
        viewBtnText: '详情',
        dialogClickModal: false,
        column: [
          {
            label: '项目名称',
            prop: 'name',
            addDisplay: false,
            editDisplay: false,
            fixed: true,
            minWidth: 200
          },
          {
            label: '项目情况',
            prop: 'project_stage',
            type: 'select',
            slot: true,
            width: 140,
            dicUrl:
              '/api/blade-system/dict-biz/dictionary?code=project-situation',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '项目总投资（万元）',
            prop: 'total_amount',
            width: 120,
            type: 'number',
            precision: 2,
            formatter: (val, value, label) => {
              return val.total_amount.toLocaleString()
            }
          },
          {
            label: '责任单位',
            prop: 'responsible_unit'
          },
          {
            label: '子项目数量',
            prop: 'lot',
            width: 120,
            hide: true
          },
          {
            label: '是否入库',
            prop: 'is_storage',
            width: 120,
            dicData: [
              {
                label: '否',
                value: 0
              },
              {
                label: '是',
                value: 1
              }
            ]
          },
          {
            label: '计划(实际)入库时间',
            prop: 'plan_storage_time',
            width: 120,
            formatter: (val, value, label) => {
              return value.substring(0, 10)
            }
          },
          {
            label: '是否开工',
            prop: 'is_start',
            width: 120,
            dicData: [
              {
                label: '否',
                value: 0
              },
              {
                label: '是',
                value: 1
              }
            ]
          },
          {
            label: '计划(实际)开工时间',
            prop: 'plan_commencement_time',
            width: 120,
            formatter: (val, value, label) => {
              return value.substring(0, 10)
            }
          },
          {
            label: '上报时间',
            prop: 'report_time',
            width: 120
          },
          {
            label: '认定时间',
            prop: 'year',
            width: 120
          },
          {
            label: '预警提示',
            prop: 'tips',
            width: 100
          },
          {
            label: '项目状态',
            prop: 'report_type',
            width: 170,
            slot: true
          }
        ]
      },
      page: {
        size: 10,
        current: 1,
        total: 0
      },
      stage: [],
      numList: [],
      typeList: [],
      tagsList: [],
      num: '',
      projectForm: {
        name: '',
        totalAmount: '',
        projectType: '1589613582090166274',
        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,
      owerQuery: {},
      projectStageQuery: {},
      selectList: [],
      dev: false,
      dataType: 'project'
    }
  },
  created() {
    this.dev = sessionStorage.getItem('dev') === 'true'
    const index = this.option.column.findIndex(sub => sub.prop === 'lot')
    const indexLabel = this.option.column.findIndex(
      sub => sub.prop === 'responsible_unit'
    )
    this.dataType = localStorage.getItem('data-type')
    if (this.user.info.viewStage === 1) {
      // 发改
      this.option.column[index].hide = true
      this.option.column[indexLabel].label = '责任单位'
    } else {
      this.option.column[index].hide = false
      this.option.column[indexLabel].label = '责任股（科）室'
    }
    this.$bus.on('serach', (res, type) => {
      this.owerQuery = res
      if (res.type === false) {
        this.projectStageQuery.projectStage = ''
        this.active = 0
      }
      this.onLoad(Object.assign(this.owerQuery, this.projectStageQuery))
      this.getNumList(Object.assign(this.owerQuery, this.projectStageQuery))
    })
    this.getTypeList()
    this.getNumList()
  },
  unmounted() {
    sessionStorage.removeItem('selectList')
  },
  methods: {
    switchTab(item, index) {
      this.active = index
      this.num = this.numList[index].totalAmount
      this.projectStageQuery = { projectStage: item.dictKey }
      this.onLoad(Object.assign(this.owerQuery, this.projectStageQuery))
    },
    onLoad(query = {}) {
      this.loading = true
      if (!Object.hasOwn(this.owerQuery, 'projectYear')) {
        this.owerQuery.projectYear = new Date().getFullYear()
      }
      console.log(this.owerQuery)
      const data = { ...this.owerQuery, parentId: this.parentId }
      this.queryData = data
      console.log(this.queryData)
      this.$api.project
        .projectList(this.page.currentPage, this.page.pageSize, this.queryData)
        .then(res => {
          this.loading = false
          if (res.code === 200) {
            this.data = res.data.records.map(e => {
              e.projectStage = e.projectStage + ''
              e.selected = true
              const xian = e.name.indexOf('县')
              e.name = this.dev ? e.name.substring(xian + 1) : e.name
              const status = confing.reportTypes.find(
                ele => ele.value === e.report_type
              )
              if (status) {
                e.report_type_name = status.label
              }
              return e
            })
            this.page.total = res.data.total
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    selectionChange(list) {
      this.selectList = list.map(sub => sub.id)
    },
    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.$router.push({
          path: '/home/pro_detail',
          query: { id: this.form.id, projectStage: this.form.project_stage }
        })
      }
    },
    currentChange(currentPage) {
      this.page.current = currentPage
    },
    sizeChange(pageSize) {
      this.page.size = pageSize
    },
    refreshChange() {
      this.getNumList()
      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.project_stage = e.project_stage.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(data) {
      this.$api.project.userNunList(data).then(res => {
        if (res.code === 200) {
          this.numList = res.data.projectStage
          this.num = res.data.projectStage[0].totalAmount
        }
      })
    },
    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
        }
      })
    },
    report(res) {
      if (res.is_report === 1) {
        this.$message.error('该项目已经上报')
        return
      }
      this.currentReport = res
      this.reportShow = true
    },
    /**
     * 股室上报项目到管理员
     * @param res
     */
    projectReport(res) {
      this.$confirm('确认上报至管理员进行审核？').then(ele => {
        if (ele === 'confirm') {
          this.$api.project.upReportType({ id: res.id }).then(res => {
            if (res.code === 200) {
              this.$message.success(res.msg)
              this.refreshChange()
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    rowClick(item, type) {
      this.form = item
      if (type === 1) {
        this.showApproval = true
      }
    },
    /**
     * 管理员审批项目
     * approvalStatus === 4 审核不通过，需要填写原因
     */
    projectApproval() {
      if (this.approvalStatus === 4 && this.approvalMsg.length === 0) {
        this.$message.error('请填写审核意见')
        return
      }
      this.showApproval = false
      this.$api.project
        .approvalProject({
          id: this.form.id,
          reportType: this.approvalStatus,
          receiptMsg: this.approvalMsg
        })
        .then(res => {
          if (res.code === 200) {
            this.$message.success(res.msg)
            this.approvalStatus = 3
            this.approvalMsg = ''
            this.refreshChange()
          } else {
            this.$message.error(res.msg)
          }
        })
    },
    /**
     * 管理员已经审核通过的项目，上报到固定资产
     * @param res
     */
    projectReportFormal(item) {
      this.$confirm('确定上报到固定资产？').then(res => {
        if (res === 'confirm') {
          this.$api.project.reportToAssets({ ids: item.id }).then(res => {
            if (res.code === 200) {
              this.$message.success(res.msg)
              this.refreshChange()
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    /**
     * 项目结转
     */
    projectCarry() {
      if (this.selectList.length === 0) {
        this.$message.error('请先选择要结转的项目')
        return
      }
      this.$api.project
        .projectCarry({ ids: this.selectList.join(',') })
        .then(res => {
          if (res.code === 200) {
            this.$message.success(res.msg)
            this.refreshChange()
          } else {
            this.$message.error(res.msg)
          }
        })
    },
    /**
     * 项目退库
     */
    projectCancel(res) {
      ElMessageBox.prompt('请输入退库原因', '提示', {}).then(({ value }) => {
        console.log(value)
        if (value === null || value.length === 0) {
          this.$message.error('请输入退库原因')
          return
        }
        this.$api.project
          .projectCancel({ id: res.id, exitMsg: value })
          .then(res => {
            if (res.code === 200) {
              this.$message.success(res.msg)
              this.refreshChange()
            } else {
              this.$message.error(res.msg)
            }
          })
      })
    },
    track(res) {
      const data = {
        id: res.id,
        is_report: 1,
        report_time: res.report_time
      }
      this.$api.project.proUpdate(data).then(res => {
        this.reportShow = false
        if (res.code === 200) {
          this.onLoad()
          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.projectForm = {
                name: '',
                totalAmount: '',
                projectType: '1589613582090166274',
                tags: '',
                introduction: ''
              }
              this.onLoad()
            } else {
              this.showAdd = false
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    formDialogClose() {
      if (this.diaType === 0) {
        this.onLoad()
      }
      this.diaType = -1
    },
    exportExcel(res, year) {
      const data = Object.assign(
        { ...this.queryData },
        {
          columnName: res,
          projectIds: this.selectList.join(','),
          previewType: 1,
          projectYear: year
        }
      )
      this.$router.push({ query: data, path: '/home/excel' })
    },
    showReceipt(msg) {
      this.$confirm(msg, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
    },
    exportExcelTotal(item) {
      const dataIds = {
        ...this.queryData,
        ...item,
        projectIds: this.selectList.join(','),
        previewType: 2
      }
      this.$router.push({ query: dataIds, path: '/home/excel' })
    }
  }
}
</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>
