<template>
  <div class="h5-container">
    <van-nav-bar title="项目台账" left-text="返回" left-arrow @click-left="onClickLeft"
                 @click-right="handAdd">
      <template #left>
        <svg t="1749540528155" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4132" width="6vw" height="6vh"><path d="M801.630938 934.023203m-36.203868 36.203867l0 0q-36.203867 36.203867-72.407734 0l-434.446406-434.446406q-36.203867-36.203867 0-72.407734l0 0q36.203867-36.203867 72.407734 0l434.446406 434.446406q36.203867 36.203867 0 72.407734Z" fill="#000000" p-id="4133"></path><path d="M729.223203-8.030938m36.203867 36.203868l0 0q36.203867 36.203867 0 72.407734l-434.446406 434.446406q-36.203867 36.203867-72.407734 0l0 0q-36.203867-36.203867 0-72.407734l434.446406-434.446406q36.203867-36.203867 72.407734 0Z" fill="#000000" p-id="4134"></path></svg>
      </template>
      <template #right>
<!--        <van-icon name="search" size="18" />-->
<!--        <van-icon name="add" size="25" color="#000" />-->
      </template>
    </van-nav-bar>
    <!-- 搜索功能 -->
<!--    <van-search v-if="searchShow"-->
    <van-search
      v-model="query.projectName"
      placeholder="请输入项目名称"
      @search="handleSearch"
      @clear="handdelect"
    />

    <!-- 项目列表 -->
    <van-pull-refresh v-model="isRefreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="isLoading"
        :finished="isFinished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-cell-group>
          <van-swipe-cell v-for="(item, index) in tableData" :key="item.id">
            <van-cell
              :title="`${item.projectName}`"
              :label="`项目经理: ${item.projectLeader}, 联系电话: ${item.phone}`"
              @click="handleDetailLook(item)"
            />
            <template #right>
              <van-button square type="danger" text="删除" @click="handleDelete(item)" />
            </template>
          </van-swipe-cell>
        </van-cell-group>
      </van-list>
    </van-pull-refresh>

    <!-- 项目详情弹窗 -->
    <van-dialog
      v-model:show="dialogVisibleLook"
      title="项目详情"
      show-cancel-button
      @confirm="qvxiao"
    >
      <van-cell-group>
        <van-field v-model="form.projectName" readonly label="项目名称" />
        <van-field v-model="form.projectLeader" readonly label="项目经理" />
        <van-field v-model="form.phone" readonly label="联系电话" />
        <van-field v-model="form.dept" readonly label="责任部门" />
      </van-cell-group>
    </van-dialog>

    <!-- 删除确认弹窗 -->
    <van-dialog
      v-model:show="deleteDialogVisible"
      title="删除确认"
      show-cancel-button
      @confirm="confirmDelete"
    >
      <div>确定要删除该项目吗？</div>
    </van-dialog>

    <!-- 新增项目工程弹窗 -->
    <van-dialog
      v-model:show="dialogVisible"
      title="新增项目工程"
      show-cancel-button
      @confirm="baocun"
    >
      <van-form @submit="baocun">
        <van-field v-model="form.projectName" label="项目名称" required />
        <van-field v-model="form.projectLeader" label="项目经理" required />
        <van-field v-model="form.phone" label="联系电话" required />
        <van-field v-model="form.dept" label="责任部门" readonly required>
          <template #button>
            <van-button size="small" type="primary" @click="bm('form')">选择</van-button>
          </template>
        </van-field>
      </van-form>
    </van-dialog>

    <!-- 文件列表弹窗 -->
    <van-dialog
      v-model:show="dialogVisibleFile"
      title="文件列表"
      show-cancel-button
      @confirm="qvxiao"
    >
      <van-cell-group>
        <van-cell title="甲方安全协议" is-link />
        <van-cell title="施工方案" is-link />
      </van-cell-group>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance, nextTick } from 'vue';
import { Dialog, showToast } from 'vant';

const { proxy } = getCurrentInstance();

const onClickLeft = () =>{
  history.back();
}

// const onClickRight = () =>{
//   searchShow.value = !searchShow.value;
// }

const searchShow = ref(false);
const query = ref({
  projectName: '',
});

function formatDate(date, format) {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hours = date.getHours();
  const minutes = date.getMinutes();
  const seconds = date.getSeconds();

  return format
    .replace('yyyy', year)
    .replace('MM', month.toString().padStart(2, '0'))
    .replace('dd', day.toString().padStart(2, '0'))
    .replace('HH', hours.toString().padStart(2, '0'))
    .replace('mm', minutes.toString().padStart(2, '0'))
    .replace('ss', seconds.toString().padStart(2, '0'));
}
const tableData = ref([]);
const selectedRows = ref([]);
const dialogVisibleLook = ref(false);
const deleteDialogVisible = ref(false);
const currentDeleteItem = ref(null);
const dialogVisible = ref(false);
const dialogVisibleFile = ref(false);
const date = ref(null)
const AttachmentRefManual1 = ref(null)
const AttachmentRefManual2 = ref(null)
const AttachmentRefManual3 = ref(null)
const AttachmentRefManual4 = ref(null)
const AttachmentRefManual5 = ref(null)
const AttachmentRefManual6 = ref(null)
const AttachmentRefManual7 = ref(null)
const AttachmentRefManual8 = ref(null)
const AttachmentRefManual9 = ref(null)
const AttachmentRefManual0 = ref(null)
const file1 = 'jfaqxy'
const file2 = 'sgfa'
const file3 = 'aqjypxjl'
const file4 = 'aqjd'
const file5 = 'ryxx'
const file6 = 'xgfdwzzshcl'
const file7 = 'xgfaqxy'
const file8 = 'rybx'
const file9 = 'tjbg'
const file0 = 'qtfj'
const handAdd = () => {
  dialogVisible.value = true
  resetForma()
  setTimeout(() => {
    date.value = formatDate(new Date(), 'yyyyMMddHHmmss')
    console.log(date.value)
  },1000)
  form.value.ownerAgreement = date.value+file1
  form.value.constructionPlan = date.value+file2
  form.value.studyRecord = date.value+file3
  form.value.safetyDisclose = date.value+file4
  form.value.personInformation = date.value+file5
  form.value.contractor = date.value+file6
  form.value.contractorAgreement = date.value+file7
  form.value.personInsurance = date.value+file8
  form.value.testReport = date.value+file9
  form.value.otherFile = date.value+file0
}
// 定义表单数据
const form = ref({
  projectName:'',
  projectLeader:'',
  projectLeaderCode:'',
  phone:'',
  dept:'',
  deptCode:'',
  companyYon:'否',
  contractorName:'',
  contractorCode:'',
  contractorPerson:'',
  contractorPersonCode:'',
  contractorPhone:'',

  ownerAgreement:'',
  constructionPlan:'',
  studyRecord:'',
  safetyDisclose:'',
  personInformation:'',
  contractor:'',
  contractorAgreement:'',
  personInsurance:'',
  testReport:'',
  otherFile:'',
});
const resetForma = async () => {
  form.value = {
    projectName:'',
    projectLeader:'',
    projectLeaderCode:'',
    phone:'',
    dept:'',
    deptCode:'',
    companyYon:'否',
    contractorName:'',
    contractorCode:'',
    contractorPerson:'',
    contractorPersonCode:'',
    contractorPhone:'',

    ownerAgreement:'',
    constructionPlan:'',
    studyRecord:'',
    safetyDisclose:'',
    personInformation:'',
    contractor:'',
    contractorAgreement:'',
    personInsurance:'',
    testReport:'',
    otherFile:'',
  }
  // await nextTick();
  // ruleFormRef.value?.clearValidate()
}

const isRefreshing = ref(false);
const isLoading = ref(false);
const isFinished = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const totalRows = ref(0);

const getTableData = () => {
  const url = 'sgsafe/Project/query';
  const param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(query.value),
  };
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code === 0) {
      if (isRefreshing.value) {
        tableData.value = response.data.data.records;
        isRefreshing.value = false;
      } else {
        tableData.value = tableData.value.concat(response.data.data.records);
      }
      totalRows.value = response.data.data.total;
      isLoading.value = false;
      if (tableData.value.length >= totalRows.value) {
        isFinished.value = true;
      }
    } else {
      showToast('操作失败！' + response.data.msg);
    }
  });
};

const onRefresh = () => {
  currentPage.value = 1;
  isFinished.value = false;
  tableData.value = [];
  getTableData();
};

const onLoad = () => {
  if (!isFinished.value) {
    currentPage.value += 1;
    getTableData();
  }
};

onMounted(() => {
  handleSearch();
});

const handleSearch = () => {
  currentPage.value = 1;
  isFinished.value = false;
  tableData.value = [];
  getTableData();
};

const handdelect = () => {
  query.value.projectName = '';
};

const handleDetailLook = (row) => {
  form.value = { ...row };
  proxy.$router.push({
    name: 'taiZhang_detail',
    query: {
      id: form.value.id,
    },
  })
  // dialogVisibleLook.value = true;
};

const handleDelete = (item) => {
  currentDeleteItem.value = item;
  deleteDialogVisible.value = true;
};

const confirmDelete = () => {
  const url = 'sgsafe/Project/remove';
  const param = {
    id: currentDeleteItem.value.id,
  };
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code === 0) {
      showToast({
        message: '删除成功',
        type: 'success',
      });
      handleSearch();
    } else {
      showToast({
        message: '删除失败！' + response.data.msg,
        type: 'fail',
      });
    }
  });
};

const qvxiao = () => {
  dialogVisibleLook.value = false;
  dialogVisibleFile.value = false;
};

const handleAdd = () => {
  dialogVisible.value = true;
  resetForm();
};

const resetForm = () => {
  form.value = {
    projectName: '',
    projectLeader: '',
    phone: '',
    dept: '',
  };
};

const baocun = () => {
  const url = 'sgsafe/Project/save';
  const param = {
    json: JSON.stringify(form.value),
  };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code === 0) {
      showToast({
        message: '保存成功',
        type: 'success',
      }).then(() => {
        resetForm();
        handleSearch();
      });
    } else {
      showToast({
        message: '操作失败！' + response.data.msg,
        type: 'fail',
      });
    }
  });
};

const reback = () => {
  // 返回逻辑
};

const deleteRow = (row) => {
  selectedRows.value = [row];
  handleDelete(row);
};

const deleteRowa = (row) => {
  deleteRow(row);
};

const bm = (val) => {
  // 部门选择逻辑
};
</script>

<style scoped>
.h5-container {
  width: 100%;
  padding: 5px;
  box-sizing: border-box;
}

.van-cell {
  padding: 10px 0;
}

.van-field {
  margin-bottom: 10px;
}
</style>