<template>
  <div class="financing-applications">
    <!-- 搜索板块 -->
    <el-row :gutter="20">
      <el-col style="display:flex" :span="20" :xs="24">
        <el-form :model="searchCondition" :inline="true">
          <el-form-item label="联系人" prop="contactPerson">
            <el-input
                v-model="searchCondition.contactPerson"
                style="max-width: 600px"
                placeholder="请输入联系人"
                class="input-with-select"
                :clearable="true"
                @change="handleSearch"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="描述" prop="demandDescription">
            <el-input
                v-model="searchCondition.demandDescription"
                style="max-width: 600px"
                placeholder="请输入描述"
                class="input-with-select"
                :clearable="true"
                @change="handleSearch"
            >
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
            <el-button icon="Refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-button
        type="primary"
        icon="Plus"
        @click="showApplicationLoanDialog"
        plain
        style="margin-bottom: 20px"
    >
      申&nbsp;&nbsp;请
    </el-button>
    <div style="margin: auto">
      <el-empty v-if="!applications.length" description="暂无数据" :image-size="100"/>
    </div>
    <el-row :gutter="20" v-loading="loading">
      <el-col :span="8" v-for="(application, index) in applications" :key="index" >
        <el-card class="financing-card" shadow="hover">
          <div class="card-header">
            <h3>{{ application.enterpriseName }}</h3>
            <div class="actions">
              <el-button size="small" type="primary" @click="handleEdit(application.id)">编辑</el-button>

              <el-popconfirm
                  confirm-button-text="发布"
                  cancel-button-text="再改改"
                  :icon="InfoFilled"
                  icon-color="#626AEF"
                  title="确定发布?发布后将不可修改"
                  @confirm="handleRelease(application.id)"
              >
                <template #reference>
                  <el-button size="small" type="danger">发布</el-button>
                </template>
              </el-popconfirm>
            </div>
          </div>
          <div class="card-content">
            <div class="card-item">
              <span class="label">企业统一社会信用编码:</span>
              <span class="value">{{ application.unifiedSocialCreditCode }}</span>
            </div>
            <div class="card-item">
              <span class="label">企业名称:</span>
              <span class="value">{{ application.enterpriseName }}</span>
            </div>
            <div class="card-item">
              <span class="label">联系人:</span>
              <span class="value">{{ application.contactPerson }}</span>
            </div>
            <div class="card-item">
              <span class="label">联系方式:</span>
              <span class="value">{{ application.contactMethod }}</span>
            </div>
            <div class="card-item">
              <span class="label">需求金额:</span>
              <span class="value">{{ application.requiredAmount }}</span>
            </div>
            <div class="card-item">
              <span class="label">状态:</span>
              <el-tag :type="getStatusType(application.status)">
                {{ formatStatus(application.status) }}
              </el-tag>
            </div>
            <div class="card-item">
              <span class="label">需求描述:</span>
              <span class="value" style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{{ application.demandDescription }}</span>
            </div>
            <div class="card-item">
              <span class="label">创建时间:</span>
              <span class="value">{{ application.createTime ? formatDateTime(application.createTime) : '-' }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog
        v-model="loanDialogVisible"
        :title="loanTitle"
        align-center
    >
      <template #default>
        <el-form ref="loanFormRef" :model="loanForm" label-width="150px" :rules="loanRules">
          <el-form-item label="企业统一社会信用编码" prop="unifiedSocialCreditCode">
            <el-input v-model="loanForm.unifiedSocialCreditCode" disabled></el-input>
          </el-form-item>
          <el-form-item label="企业名称" prop="enterpriseName">
            <el-input v-model="loanForm.enterpriseName" disabled></el-input>
          </el-form-item>
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="loanForm.contactPerson"></el-input>
          </el-form-item>
          <el-form-item label="联系方式" prop="contactMethod">
            <el-input v-model="loanForm.contactMethod"></el-input>
          </el-form-item>
          <el-form-item label="需求金额" prop="requiredAmount">
            <el-input-number v-model.number="loanForm.requiredAmount" :step="10000" :min="10000" :max="5000000"></el-input-number>
          </el-form-item>
          <el-form-item label="需求描述" prop="demandDescription">
            <el-input type="textarea" v-model="loanForm.demandDescription"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="loanDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitLoanForm">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <div>
      <el-pagination
          background
          layout="prev, pager, next, ->,total"
          :total="total"
          v-model:page-size="pageSize"
          v-model:current-page="currentPage"
          @current-change="list"
      ></el-pagination>
    </div>
  </div>
</template>

<script setup>
import {reactive, ref} from 'vue';
import { ElMessage } from 'element-plus';
import {addOrUpdateLoanApplication, getLoanById, listByPage, releaseApplicationById} from "@/api/xyrz/rzsq";
import {useStore} from "vuex";
import {InfoFilled} from "@element-plus/icons-vue";

const loading = ref(false);
const store = useStore();
const loanDialogVisible = ref(false);
const loanFormRef = ref(null);
const loanTitle = ref('');
const applications = ref([]);
const total = ref(0);
const pageSize = ref(3);
const currentPage = ref(1);
const showApplicationLoanDialog = ()=>{
  loanTitle.value = '提交贷款申请'
  loanForm.contactMethod = ''
  loanForm.contactPerson = ''
  loanForm.demandDescription = ''
  loanForm.requiredAmount = ''
  loanForm.id = null;
  loanForm.enterpriseName = store.getters.userInfo.nickName
  loanForm.unifiedSocialCreditCode = store.getters.userInfo.userName
  loanDialogVisible.value = true;
  loanFormRef.resetFields();
}
const searchCondition = ref({
  contactPerson: undefined,
  demandDescription: undefined,
})
const handleSearch = () => {
  list()
}
const handleReset = () => {
  searchCondition.value = {}
  list()
}
const initLoanForm = {
  unifiedSocialCreditCode: '',
  enterpriseName: '',
  contactPerson: '',
  contactMethod: '',
  requiredAmount: '',
  demandDescription: '',
}
const loanForm = reactive(initLoanForm);

const loanRules = reactive({
  unifiedSocialCreditCode: [{ required: true, message: '请输入企业统一社会信用编码', trigger: 'blur' }],
  enterpriseName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
  contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  contactMethod: [
      { required: true, message: '请输入联系方式', trigger: 'blur' },
      {
        pattern: /^1[3456789]\d{9}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur'
      }
  ],
  requiredAmount: [{ required: true, message: '请输入需求金额', trigger: 'blur' }],
  demandDescription: [{ required: true, message: '请输入需求描述', trigger: 'blur' }],
});

const submitLoanForm = () => {
  loanFormRef.value.validate(async (valid) => {
    if (valid) {
      // 提交表单逻辑
      const res = await addOrUpdateLoanApplication(loanForm);
      if(res.code != 200){
        ElMessage.error(res.msg);
        return false;
      }
      ElMessage.success(res.msg);
      list()
      loanDialogVisible.value = false;
      loanFormRef.resetFields();
    } else {
      return false;
    }
    list();
  });
};

const handleEdit = async (id) => {
  loanTitle.value = '编辑贷款申请'
  const res = await getLoanById(id);
  if(res.code == 200){
    loanForm.unifiedSocialCreditCode = res.data.unifiedSocialCreditCode;
    loanForm.enterpriseName = res.data.enterpriseName;
    loanForm.contactPerson = res.data.contactPerson;
    loanForm.contactMethod = res.data.contactMethod;
    loanForm.requiredAmount = res.data.requiredAmount;
    loanForm.demandDescription = res.data.demandDescription;
    loanForm.id = res.data.id;
    loanDialogVisible.value = true;
  }
  // 这里可以添加编辑逻辑
};

const handleRelease = async (id) => {
  const res = await releaseApplicationById(id);
  if(res.code != 200){
    ElMessage.error(res.msg);
  }
  ElMessage.success(res.msg);
  list()
};


const formatStatus = (status) => {
  switch (status) {
    case 0:
      return '待发布';
    case 1:
      return '待审核';
    case 2:
      return '已放款';
    case 3:
      return '未放款';
    case 4:
      return '已撤销';
    default:
      return '未知状态';
  }
};

const getStatusType = (status) => {
  switch (status) {
    case 0:
      return 'warning';
    case 1:
      return 'warning';
    case 2:
      return 'success';
    case 3:
      return 'danger';
    case 4:
      return 'info';
    default:
      return 'default';
  }
};
// 格式化日期时间
function formatDateTime(dateTime) {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
}

const list =async ()=>{
  const conditionJsonArr = [];
  conditionJsonArr.push(
      {
        column:"unified_social_credit_code",
        type:'eq',
        value:store.getters.userInfo.userName,
      },
      {
        column:"create_time",
        type:'orderByDesc'
      },
      {
        column:"status",
        type:'eq',
        value:0
      }
  )
  searchCondition.value.contactPerson && conditionJsonArr.push({
    column: "contact_person",
    type: 'like',
    value: searchCondition.value.contactPerson
  })
  searchCondition.value.demandDescription && conditionJsonArr.push({
    column: "demand_description",
    type: 'like',
    value: searchCondition.value.demandDescription
  })
  loading.value = true;
  const res = await listByPage(currentPage.value,pageSize.value,conditionJsonArr);
  if(res.code != 200){
    ElMessage.error(res.msg);
  }
  applications.value = res.data.records;
  total.value = res.data.total
  loading.value = false;
}
list()
</script>

<style scoped>
.financing-applications {
  margin: 20px;
}

.financing-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.label {
  font-weight: bold;
  width: 40%;
}

.value {
  width: 60%;
}
</style>
