<template>
  <div>
    <el-row style="height: 800px">
      <el-col :span="10">
        <el-card
          style="height: 100%"
        >
          <template #header>
            <el-row align="middle">
              <el-col :span="6">
                <el-text size="large">项目基本信息</el-text>
              </el-col>
              <el-col
                :span="4"
                :offset="14"
              >
                <el-button
                  v-show="ifUpdate"
                  type="primary"
                  :icon="Edit"
                  @click="basicEditShow"
                >信息编辑
                </el-button>
              </el-col>
            </el-row>
          </template>
          <el-tabs
            v-model="activeName"
            class="demo-tabs"
            type="border-card"
            @tab-click="handleClick"
          >
            <el-tab-pane
              label="甲方信息"
              name="first"
            >
              <el-row class="mt-2">
                <el-text
                  size="large"
                  :line-clamp="1"
                >
                  <b>项目名称：</b>{{ information.name }}
                </el-text>
              </el-row>
              <el-row class="mt-10">
                <el-text
                  size="large"
                  :line-clamp="1"
                >
                  <b>项目地址：</b>{{ information.address }}
                </el-text>
              </el-row>
              <el-row class="mt-10">
                <el-text
                  size="large"
                  :line-clamp="1"
                >
                  <b>甲方负责人：</b>{{ information.firstPrincipal }}
                </el-text>
              </el-row>
              <el-row class="mt-10">
                <el-text
                  size="large"
                  :line-clamp="1"
                >
                  <b>甲方负责人电话：</b>{{ encryptPhone(information.firstPhone) }}
                </el-text>
              </el-row>
            </el-tab-pane>
            <el-tab-pane
              label="乙方信息"
              name="second"
            >
              <el-row class="mt-2">
                <el-text
                  size="large"
                  :line-clamp="1"
                >
                  <b>乙方负责人：</b>{{ information.secondPrincipalName }}
                </el-text>
              </el-row>
              <el-row class="mt-10">
                <el-text
                  size="large"
                  :line-clamp="1"
                >
                  <b>合同金额：</b>{{ information.projectPrice }}元
                </el-text>
              </el-row>
              <el-row class="mt-10">
                <el-text
                  size="large"
                >
                  <b>合同签订时间：</b>{{ information.signTime }}
                </el-text>
              </el-row>
              <el-row class="mt-10">
                <el-text
                  size="large"
                >
                  <b>进场施工时间：</b>{{ information.intoConstructionTime }}
                </el-text>
              </el-row>
              <el-row class="mt-10">
                <el-text
                  size="large"
                >
                  <b>竣工时间：</b>{{ information.completedTime }}
                </el-text>
              </el-row>
              <el-row class="mt-10">
                <el-text
                  size="large"
                >
                  <b>项目状态：</b>{{ currentState }}
                </el-text>
              </el-row>
              <el-row class="mt-10">
                <el-col :span="3">
                  <el-text
                    size="large"
                  >
                    <b>项目说明:</b>
                  </el-text>
                </el-col>
                <el-col :span="20">
                  <el-text
                    size="large"
                    :line-clamp="4"
                  >
                    {{ information.illustrate }}
                  </el-text>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane
              label="丙方信息"
              name="third"
            >
              <el-row class="mt-2">
                <el-text
                  size="large"
                  :line-clamp="1"
                >
                  <b>监理人姓名：</b>{{ information.supervisorName }}
                </el-text>
              </el-row>
              <el-row class="mt-10">
                <el-text
                  size="large"
                >
                  <b>监理单位：</b>{{ information.supervisorUint }}
                </el-text>
              </el-row>
              <el-row class="mt-10">
                <el-text
                  size="large"
                >
                  <b>监理人电话：</b>{{ information.supervisorPhone }}
                </el-text>
              </el-row>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
      <el-col
        :span="13"
        class="ml-5"
      >
        <el-card
          style="height: 100%"
        >
          <template #header>
            <el-row align="middle">
              <el-col :span="10">
                <el-text size="large">项目文件列表</el-text>
                <el-button
                  style="margin-left: 40px"
                  @click="changeFilePrompt"
                >所需文件提示</el-button>
              </el-col>
              <el-col
                :span="6"
                :offset="8"
              >
                <el-button
                  type="primary"
                  :icon="Edit"
                  @click="openOptionEdit"
                >项目状态和文件类型编辑
                </el-button>
              </el-col>
            </el-row>
          </template>
          <el-row>
            <el-col :span="6">
              <el-input
                v-model="fileCondition.name"
                placeholder="请输入文件名称"
                clearable
              />
            </el-col>
            <el-col
              :span="4"
              :offset="1"
            >
              <el-select
                v-model="fileType"
                clearable
                placeholder="文件类型"
                @change="changeFileType"
              >
                <el-option
                  v-for="item in editor.typeList"
                  :key="item.ID"
                  :label="item.name"
                  :value="item.ID"
                />
              </el-select>
            </el-col>
            <el-col
              :span="3"
              :offset="1"
            >
              <el-button
                type="primary"
                :icon="Search"
                @click="queryFile"
              >查询
              </el-button>
            </el-col>
            <el-col
              :span="3"
            >
              <el-button
                type="primary"
                :icon="RefreshLeft"
                @click="resetData"
              >
                重置
              </el-button>
            </el-col>
            <el-col
              :span="3"
            >
              <el-dropdown
                split-button
                type="primary"
              >
                菜单
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item>
                      <el-button
                        type="primary"
                        :icon="Upload"
                        @click="fileDialog = true"
                      >
                        上传
                      </el-button>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-button
                        type="primary"
                        :icon="Download"
                        @click="downloadTips"
                      >
                        下载
                      </el-button>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-button
                        type="primary"
                        :icon="Delete"
                        @click="projectDeletes"
                      >
                        删除
                      </el-button>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-col>
          </el-row>
          <el-row style="margin-top: 20px">
            <el-col :span="24">
              <el-table
                :data="fileList"
                row-class-name="row-class"
                border
                height="562px"
                stripe
              >
                <el-table-column
                  prop="ID"
                  align="center"
                  label="ID"
                  width="180"
                />
                <el-table-column
                  prop="name"
                  label="文件名称"
                  align="center"
                  width="350"
                />
                <el-table-column
                  label="项目操作"
                  align="center"
                  fixed="right"
                >
                  <template #default="scope">
                    <el-button
                      text
                      type="primary"
                      :icon="Download"
                      size="large"
                      @click="oneDownload(scope.row)"
                    >
                      下载
                    </el-button>
                    <el-button
                      text
                      type="primary"
                      :icon="Delete"
                      size="large"
                      @click="projectDelete(scope.row)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <el-row justify="end">
            <el-pagination
              :page-size="9"
              background
              layout="prev, pager, next"
              :total="fileTotal"
              @change="changeFilePage"
            />
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
      v-model="fileDialog"
      title="上传文件"
      width="40%"
      :before-close="fileDialogClose"
      :align-center="true"
    >
      <el-form>
        <el-row style="margin-top: 20px">
          <el-col :span="8">
            <el-form-item label="文件类型：">
              <el-select
                v-model="uploadFileType"
                clearable
                placeholder="请选择上传文件的类型"
                @change="changeUploadFileType"
              >
                <el-option
                  v-for="item in editor.typeList"
                  :key="item.ID"
                  :label="item.name"
                  :value="item.ID"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row style="margin-top: 20px">
        <el-col :span="24">
          <el-upload
            class="upload-demo"
            drag
            multiple
            :auto-upload="false"
            :file-list="uploadFileData"
            :on-change="changeFileData"
            :on-remove="removeFileData"
          >
            <el-icon class="el-icon--upload">
              <upload-filled />
            </el-icon>
            <div class="el-upload__text">
              请选择需要上传的文件
            </div>
            <template #tip>
              <div class="el-upload__tip">
                选择的文件不要超过500MB
              </div>
            </template>
          </el-upload>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="fileDialog = false">取消</el-button>
          <el-button
            type="primary"
            @click="supplementFile"
          >
            上传
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="stateTypeShow"
      title="状态和类型编辑"
      width="40%"
    >
      <option-edit />
    </el-dialog>
    <el-drawer
      v-model="basicEditDisplay"
      title="项目基本信息编辑"
    >
      <el-form
        size="large"
        style="margin-top: 10px"
        label-position="left"
        label-width="110"
      >
        <el-tabs v-model="editItem">
          <el-tab-pane
            label="甲方信息"
            name="first"
          >
            <el-form-item
              label="项目名称："
            >
              <el-input
                v-model="editData.name"
                placeholder="请输入项目名称"
              />
            </el-form-item>
            <el-form-item
              label="项目地址："
            >
              <el-input
                v-model="editData.address"
                placeholder="请输入项目名称"
              />
            </el-form-item>
            <el-form-item
              label="甲方负责人："
            >
              <el-input
                v-model="editData.firstPrincipal"
                placeholder="请输入甲方负责人"
              />
            </el-form-item>
            <el-form-item
              label="负责人电话："
            >
              <el-input
                v-model="editData.firstPhone"
                placeholder="请输入甲方负责人电话"
              />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane
            label="乙方信息"
            name="second"
          >
            <el-form-item label="乙方负责人：">
              <el-select
                v-model="editData.secondPrincipal"
                placeholder="请选择乙方负责人姓名"
                filterable
              >
                <el-option
                  v-for="item in userList"
                  :key="item.ID"
                  :label="item.nickName"
                  :value="item.ID"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="合同金额：">
              <el-input-number v-model="editData.projectPrice" />
            </el-form-item>
            <el-form-item label="合同签订日期：">
              <el-date-picker
                v-model="editData.signTime"
                type="date"
                placeholder="请选择合同签订时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                clearable
                @clear="editData.signTime = ''"
              />
            </el-form-item>
            <el-form-item label="进场施工时间：">
              <el-date-picker
                v-model="editData.intoConstructionTime"
                type="date"
                placeholder="请选择进场施工时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                clearable
                @clear="editData.intoConstructionTime = ''"
              />
            </el-form-item>
            <el-form-item label="竣工时间：">
              <el-date-picker
                v-model="editData.completedTime"
                type="date"
                placeholder="请选择竣工时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                clearable
                @clear="editData.completedTime = ''"
              />
            </el-form-item>
            <el-form-item label="项目状态：">
              <el-select
                v-model="editData.state"
              >
                <el-option
                  v-for="item in editor.stateList"
                  :key="item.ID"
                  :label="item.name"
                  :value="item.ID"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="项目说明：">
              <el-input
                v-model="editData.illustrate"
                :rows="5"
                type="textarea"
                placeholder="请输入项目说明"
              />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane
            label="丙方信息"
            name="third"
          >
            <el-form-item label="监理人姓名：">
              <el-input
                v-model="editData.supervisorName"
                placeholder="请输入监理人姓名"
              />
            </el-form-item>
            <el-form-item label="监理单位：">
              <el-input
                v-model="editData.supervisorUint"
                placeholder="请输入监理单位"
              />
            </el-form-item>
            <el-form-item label="监理电话：">
              <el-input
                v-model="editData.supervisorPhone"
                placeholder="请输入监理电话"
              />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            size="large"
            @click="basicEditDisplay = false"
          >
            取消
          </el-button>
          <el-button
            type="primary"
            size="large"
            @click="basicDataEdit"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-drawer>
    <el-dialog
      v-model="filePrompt"
      title="项目所需文件提示"
    >
      <el-row style="margin-top: 20px">
        <el-alert
          title="项目前期资料："
          description="报价单、施工图、合同、项目立项书、工程清单、财评中心审计后清单表、图审报告"
          type="info"
          show-icon
          :closable="false"
        />
      </el-row>
      <el-row style="margin-top: 20px">
        <el-alert
          title="项目施工期资料："
          description="施工图片、签证单、工程变更单、草签证明、工程进度款单证"
          type="warning"
          show-icon
          :closable="false"
        />
      </el-row>
      <el-row style="margin-top: 20px">
        <el-alert
          title="项目结算期资料："
          description="竣工图、结算书、工程单证单、付款申请单、发票"
          type="success"
          show-icon
          :closable="false"
        />
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup>
import { getProjectMessage, editProject } from '@/api/project'
import { onMounted, reactive, ref } from 'vue'
import { getAllUsers } from '@/api/user'
import { queryFileList, createProjectFile, downloadProjectFile, deleteProjectFile, deleteProjectFiles } from '@/api/file'
import { Download, Upload, Delete, Search, RefreshLeft, Edit } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import OptionEdit from './components/optionEdit.vue'
import { editorData } from '@/pinia/project/project'
import { fileDownload } from '@/api/dailyFile'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/pinia/modules/user'
// eslint-disable-next-line no-unused-vars
const router = useRouter()
const route = useRoute()
const currentUser = useUserStore()
defineOptions({
  name: 'ProjectDetails'
})
// 文件提示显示
const filePrompt = ref(false)
const changeFilePrompt = () => {
  filePrompt.value = true
}
// ......................................
// 基本信息编辑
const activeName = ref('first')
const handleClick = () => {}
const basicEditDisplay = ref(false)
const basicEditShow = () => {
  basicEditDisplay.value = true
  Object.assign(editData, information)
}
const editItem = ref('first')
const basicDataEdit = () => {
  const edit = {
    id: editData.ID,
    code: route.query.code, // 项目编号
    name: editData.name, // 项目名称
    address: editData.address, // 项目地址
    firstPrincipal: editData.firstPrincipal, // 甲方负责人
    firstPhone: editData.firstPhone, // 甲方电话
    projectPrice: editData.projectPrice, // 合同金额
    secondPrincipal: editData.secondPrincipal, // 乙方负责人
    signTime: editData.signTime, // 合同签订日期
    intoConstructionTime: editData.intoConstructionTime, // 进场施工时间
    completedTime: editData.completedTime, // 竣工时间
    supervisorUint: editData.supervisorUint, // 监理单位
    supervisorName: editData.supervisorName, // 监理姓名
    supervisorPhone: editData.supervisorPhone, // 监理电话
    illustrate: editData.illustrate, // 说明
    state: editData.state // 状态
  }
  for (const i in edit) {
    if (edit[i] === '' || edit[i] === 0 || edit[i] === null) {
      ElMessage.error('请将甲乙丙三方的信息填写完整')
      return
    }
  }
  editProject(edit).then(res => {
    if (res.code === 0) {
      ElMessage({
        message: '编辑成功',
        type: 'success',
        showClose: true,
        duration: 2000
      })
      basicEditDisplay.value = false
      projectMessage(route.query.code)
    }
  })
}
// 数据
const editor = editorData()
const fileCondition = reactive({
  code: route.query.code,
  name: '',
  genre: 0,
  pageInfo: {
    page: 1,
    pageSize: 9
  }
})

const information = reactive({})

// 用于编辑的数据
const editData = reactive({})
// 项目用户列表
const userList = reactive([])
// 项目文件列表
const fileList = reactive([])

const fileTotal = ref(0)
// 项目文件类型列表
const fileTypeList = reactive([])
// 项目文件类型
const fileType = ref('')
// 上传文件弹窗
const fileDialog = ref(false)

const uploadFileType = ref('')

const uploadFileData = ref([])

const stateTypeShow = ref(false)

const currentState = ref('')
// 允许查看手机号的id数组
const allowId = reactive([1, 6, 7])
// 当前用户id
const currentUserId = ref(0)
// 方法
onMounted(() => {
  currentUserId.value = currentUser.userInfo.ID
  projectMessage(route.query.code)
  queryFile()
  editor.getStateList()
  editor.getTypeList()
  getAllUsers().then(res => {
    if (res.code === 0) {
      userList.push(...res.data)
    }
  })
})

// 初始化项目数据
const projectMessage = (code) => {
  getProjectMessage(code).then(res => {
    if (res.code === 0) {
      const data = res.data
      data.CreatedAt = formatDate(data.CreatedAt)
      data.UpdatedAt = formatDate(data.UpdatedAt)
      allowId.push(res.data.secondPrincipal)
      // console.log(data)
      // const firstPhone = data.firstPhone
      // const supervisorPhone = data.supervisorPhone
      // let isPower = false
      // allowId.forEach(item => {
      //   if (item === currentUserId.value) {
      //     isPower = true
      //   }
      // })
      // if (!isPower) {
      //   data.firstPhone = firstPhone.substring(0, 3) + '********'
      //   data.supervisorPhone = supervisorPhone.substring(0, 3) + '********'
      // }
      Object.keys(data).forEach(key => {
        information[key] = data[key]
        editData[key] = data[key]
      })
      currentState.value = information.projectState.name
    }
  })
}
// 加密
const ifUpdate = ref(false)
const encryptPhone = (phone) => {
  if (!phone) {
    return ''
  }
  console.log(information.secondPrincipal === currentUserId.value, phone)
  if (information.secondPrincipal === currentUserId.value || currentUserId.value === 6 || currentUserId.value === 7) {
    ifUpdate.value = true
    return phone
  }
  return phone.substring(0, 3) + '********'
}

// 重置
const resetData = () => {
  fileCondition.code = route.query.code
  fileCondition.name = ''
  fileCondition.genre = 0
  fileCondition.pageInfo = {
    page: 1,
    pageSize: 9
  }
  queryFile()
}

const changeFileType = (value) => {
  if (typeof value === 'number') {
    fileTypeList.forEach(item => {
      if (item.ID === value) {
        fileType.value = item.name
      }
    })
    fileCondition.genre = value
  } else {
    fileCondition.genre = 0
  }
}
// 查询文件
const queryFile = () => {
  queryFileList(fileCondition).then(res => {
    if (res.code === 0) {
      fileTotal.value = res.data.total
      fileList.length = 0
      fileList.push(...res.data.list)
    }
  })
}
// 上传文件
const fileDialogClose = () => {
  fileDialog.value = false
}

const changeUploadFileType = (value) => {
  if (typeof value === 'number') {
    uploadFileType.value = value
  } else {
    uploadFileType.value = ''
  }
}

const changeFileData = (file, fileList) => {
  uploadFileData.value = fileList
}

const removeFileData = (file, fileList) => {
  uploadFileData.value = fileList
}

const supplementFile = () => {
  if (uploadFileType.value === '') {
    ElMessage.error('请选择文件类型')
  } else if (uploadFileData.value.length === 0) {
    ElMessage.error('暂未选择文件')
  } else {
    const formData = new FormData()
    uploadFileData.value.forEach(item => {
      formData.append('file', item.raw)
    })
    formData.append('genre', uploadFileType.value)
    formData.append('code', route.query.code)
    createProjectFile(formData).then(res => {
      if (res.code === 0) {
        fileDialog.value = false
        ElMessage.success(res.msg)
        uploadFileType.value = ''
        uploadFileData.value = []
        queryFile()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }
}

// 下载文件
const downloadTips = () => {
  ElMessageBox.confirm(
    '确定要下载列表中的所有文件吗?',
    '文件下载',
    {
      confirmButtonText: '下载',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const type = fileType.value === '' ? 0 : fileType.value
      const data = {
        code: route.query.code,
        genre: type,
        name: fileCondition.name
      }
      downloadProjectFile(data).then(res => {
        const link = document.createElement('a')
        const href = window.URL.createObjectURL(res) // 创建下载的链接
        link.href = href
        link.download = route.query.code + '.zip' // 下载后文件名
        document.body.appendChild(link)
        link.click() // 点击下载
        document.body.removeChild(link) // 下载完成移除元素
        window.URL.revokeObjectURL(href) // 释放掉blob对象
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消下载',
      })
    })
}

// 单文件下载
const oneDownload = async(val) => {
  await fileDownload(val).then(res => {
    const link = document.createElement('a')
    const href = window.URL.createObjectURL(res) // 创建下载的链接
    link.href = href
    link.download = val.name // 下载后文件名
    document.body.appendChild(link)
    link.click() // 点击下载
    document.body.removeChild(link) // 下载完成移除元素
    window.URL.revokeObjectURL(href) // 释放掉blob对象
  })
}

// 单文件删除
const projectDelete = async(val) => {
  ElMessageBox.confirm(
    '你确定进行删除操作吗?',
    '删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      await deleteProjectFile(val).then(res => {
        if (res.code === 0) {
          ElMessage.success('删除成功')
        }
      })
      queryFile()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 多文件删除
const projectDeletes = async() => {
  ElMessageBox.confirm(
    '你确定进行删除操作吗?',
    '删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      const type = fileType.value === '' ? 0 : fileType.value
      const data = {
        code: route.query.code,
        genre: type,
        name: fileCondition.name
      }
      await deleteProjectFiles(data).then(res => {
        if (res.code === 0) {
          ElMessage.success('删除成功')
        }
      })
      queryFile()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 日期格式化
const formatDate = (dateString, locale = 'en-US', timezone = 'Asia/Shanghai') => {
  // 使用 Date 构造函数解析日期字符串
  const date = new Date(dateString)

  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    throw new Error('Invalid date string')
  }

  // 使用 Date 对象的年份、月份和日期来构建新的日期字符串
  // 注意：JavaScript 中的月份是从 0 开始的，所以我们需要加 1

  return `${date.getFullYear()}-${('0' + (date.getMonth() + 1)).slice(-2)}-${('0' + date.getDate()).slice(-2)}`
}

const changeFilePage = (value) => {
  fileCondition.pageInfo.page = value
  queryFile()
}

const openOptionEdit = () => {
  stateTypeShow.value = true
}
</script>

<style scoped lang="scss">
@mixin basic {
  width: 50%;
  display: flex;
  align-items: center;
}

.basicInformation {
  height: 50px;
  background-color: #f8fafd;
  display: flex;

  .basicTitle {
    @include basic;
    padding-left: 40px;
  }

  .basicEdit {
    @include basic;
    justify-content: end;
    padding-right: 40px;
  }
}
</style>
