<template>
    <!-- 寻源需求 -->
    <el-form
        :inline="true"
        size="default"
        label-width="0"
        ref="searchFormRef"
        :model="searchParams"
    >
        <el-row>
            <el-col :span="4">
                <el-form-item prop="leaseName">
                    <el-input
                        style="width: 100%"
                        placeholder="请输入需求名称"
                        v-model="searchParams.leaseName"
                        clearable
                    />
                </el-form-item>
            </el-col>
            <el-col :span="4">
                <el-form-item prop="leaseCode">
                    <el-input
                        style="width: 100%"
                        placeholder="请输入需求编号"
                        v-model="searchParams.leaseCode"
                        clearable
                    />
                </el-form-item>
            </el-col>
            <el-col :span="4">
                <el-form-item prop="leaseStatus">
                    <el-select
                        clearable
                        style="width: 100%"
                        placeholder="选择需求状态"
                        v-model="searchParams.leaseStatus"
                    >
                        <el-option label="待接单" :value="0" />
                        <el-option label="已接单" :value="1" />
                        <el-option label="已到期" :value="2" />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item>
                    <el-date-picker
                        style="width: 100%"
                        v-model="endTime"
                        type="daterange"
                        range-separator="-"
                        value-format="YYYY-MM-DD"
                        start-placeholder="截止开始日期"
                        end-placeholder="截止结束日期"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item>
                    <el-date-picker
                        v-model="releaseTime"
                        style="width: 100%"
                        type="daterange"
                        range-separator="-"
                        value-format="YYYY-MM-DD"
                        start-placeholder="发布开始日期"
                        end-placeholder="发布结束日期"
                    />
                </el-form-item>
            </el-col>
        </el-row>

        <el-form-item>
            <el-button @click="getLeaseListData" type="primary">查询</el-button>
            <el-button @click="onReset">重置</el-button>
            <el-button
                @click="
                    () => {
                        addOrEditDialogVisible = true
                        isRepublish = true
                    }
                "
                style="background-color: #17907f; color: #fff"
            >
                需求新建
            </el-button>
        </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table
        :data="leaseList"
        show-overflow-tooltip
        :header-cell-style="{
            background: '#17907f',
            color: '#fff',
        }"
    >
        <el-table-column align="center" label="序号" type="index" width="80" />
        <el-table-column align="center" prop="leaseCode" label="需求编号" />
        <el-table-column align="center" prop="leaseName" label="需求名称" />
        <el-table-column align="center" prop="operateAddress" label="需求所在地" />
        <el-table-column align="center" prop="publishUser" label="发布人" />
        <el-table-column align="center" prop="endTime" label="需求截止日期" />
        <el-table-column align="center" prop="startTime" label="发布时间" />
        <el-table-column align="center" prop="leaseStatusName" label="需求状态" />
        <el-table-column align="center" label="操作" :width="220">
            <template #default="{ row }">
                <el-button
                    text
                    size="small"
                    type="primary"
                    v-if="row.leaseStatus === 2"
                    @click="onRepublish(row.id, false)"
                >
                    重新发布
                </el-button>
                <el-button
                    text
                    size="small"
                    type="primary"
                    v-if="row.leaseStatus === 2"
                    @click="onRepublish(row.id, true)"
                >
                    编辑
                </el-button>
                <el-popconfirm
                    width="220"
                    :icon="InfoFilled"
                    icon-color="#626AEF"
                    title="确定删除该项需求吗？"
                    @confirm="onDelete(row.id)"
                >
                    <template #reference>
                        <el-button size="small" text type="danger"> 删除 </el-button>
                    </template>
                    <template #actions="{ confirm }">
                        <el-button size="small">取消</el-button>
                        <el-button type="danger" size="small" @click="confirm()"> 确定 </el-button>
                    </template>
                </el-popconfirm>
            </template>
        </el-table-column>
    </el-table>

    <!-- <el-pagination
        size="small"
        background
        layout="prev, pager, next"
        :page-size="searchParams.pageSize"
        :total="total"
        class="mt-4"
        @current-change="onCurrentChange"
        v-if="total > 0"
    /> -->

    <el-pagination
        style="text-align: right"
        background
        size="small"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        v-model:page-size="searchParams.pageSize"
        v-model:current-page="searchParams.pageNum"
        layout="total, prev, pager, next,sizes"
        @size-change="getLeaseListData"
        @current-change="getLeaseListData"
    />

    <!-- 新增修改对话框 -->
    <el-dialog
        title="新增"
        width="60%"
        align-center
        destroy-on-close
        v-model="addOrEditDialogVisible"
    >
        <el-form
            label-width="auto"
            label-position="right"
            ref="addOrEditFormRef"
            :model="addOrEditForm"
            :rules="addOrEditFormRules"
        >
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="需求名称" prop="leaseName">
                        <el-input v-model="addOrEditForm.leaseName" placeholder="请输入需求名称" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="装备类目" prop="typeIds">
                        <el-cascader
                            clearable
                            style="width: 100%"
                            :options="classOptions"
                            :show-all-levels="false"
                            placeholder="请选择装备类目"
                            v-model="addOrEditForm.typeIds"
                            :props="{ value: 'id', label: 'name' }"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="租赁公司" prop="companyId">
                        <el-select
                            clearable
                            style="width: 100%"
                            placeholder="请选择租赁公司"
                            v-model="addOrEditForm.companyId"
                        >
                            <el-option
                                v-for="item in companyOptions"
                                :key="item.companyId"
                                :label="item.companyName"
                                :value="item.companyId"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="联系人" prop="person">
                        <el-input
                            clearable
                            placeholder="请输入联系人"
                            v-model="addOrEditForm.person"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="联系电话" prop="personPhone">
                        <el-input
                            clearable
                            placeholder="请输入联系电话"
                            v-model="addOrEditForm.personPhone"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="预估租期(天)" prop="leaseDay">
                        <el-input-number
                            :min="1"
                            clearable
                            :max="9999"
                            style="width: 100%"
                            v-model="addOrEditForm.leaseDay"
                            placeholder="请输入预估租期"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="预估数量" prop="leaseNum">
                        <el-input-number
                            clearable
                            :min="1"
                            :max="9999"
                            style="width: 100%"
                            v-model="addOrEditForm.leaseNum"
                            placeholder="请输入预估数量"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="需求截止日期" prop="endTime">
                        <el-date-picker
                            clearable
                            type="date"
                            style="width: 100%"
                            value-format="YYYY-MM-DD"
                            v-model="addOrEditForm.endTime"
                            placeholder="请选择需求截止日期"
                            :disabled-date="disabledDate"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="1" style="margin-bottom: 0" class="upload-tip">
                        支持格式：.jpg、.png 单个文件大小不能超过2M，最多可上传4张
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="参考图片/样式">
                        <UploadComponentNew
                            :maxSize="2"
                            :maxLimit="4"
                            width="120px"
                            height="120px"
                            :autoUpload="true"
                            :multiple="true"
                            listType="picture-card"
                            :acceptTypeList="['.jpg', '.png']"
                            :actionUrl="uploadUrl"
                            :successResultCallBack="successResultCallBackFnDevicePic"
                        >
                            <template v-slot:default>
                                <el-icon size="48" color="#aaa"><Plus /></el-icon>
                            </template>
                        </UploadComponentNew>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="需求描述" prop="description">
                        <el-input
                            clearable
                            type="textarea"
                            placeholder="请输入需求描述"
                            v-model="addOrEditForm.description"
                            :autosize="{ minRows: 6, maxRows: 10 }"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="onCancel">取消</el-button>
                <el-button type="primary" @click="onSubmit(false)" v-if="isSave"> 保存 </el-button>
                <el-button type="primary" @click="onSubmit(true)"> 提交 </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import UploadComponentNew from 'components/uploadComponentNew/index.vue'
import { getCompanyListApi, getGoodsClassListApi } from 'http/api/home'
import {
    addLeaseInfoApi,
    getLeaseListApi,
    editLeaseInfoApi,
    deleteLeaseInfoApi,
    getLeaseDetailsByIdApi,
} from 'http/api/sourcing/index'
import { InfoFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
const uploadUrl = import.meta.env.VITE_API_URL + '/file/upload'
const addOrEditDialogVisible = ref(false)
const companyOptions = ref<any>([])
const classOptions = ref<any>([])
const addOrEditFormRef = ref<any>(null)
const searchFormRef = ref<any>(null)
const leaseList = ref<any>([])
const isRepublish = ref(true)
const isSave = ref(false)
const total = ref(0)
const endTime = ref([])
const releaseTime = ref([])
const searchParams = reactive({
    leaseName: '',
    leaseCode: '',
    leaseStatus: '',
    finishStartTime: '',
    finishEndTime: '',
    publishStartTime: '',
    publishEndTime: '',
    pageSize: 10,
    pageNum: 1,
})
const addOrEditForm = reactive<any>({
    leaseName: '',
    typeId: '',
    typeIds: [],
    companyId: '',
    person: '',
    personPhone: '',
    leaseDay: 1,
    leaseNum: 1,
    endTime: '',
    description: '',
    isSubmit: '',
    fileInfoList: [],
})

const addOrEditFormRules = reactive({
    leaseName: [{ required: true, message: '请输入需求名称', trigger: 'blur' }],
    typeIds: [{ required: true, message: '请选择装备类目', trigger: 'change' }],
    companyId: [{ required: true, message: '请选择租赁公司', trigger: 'change' }],
    person: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
    personPhone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        {
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的联系电话',
            trigger: 'blur',
        },
    ],
    leaseDay: [{ required: true, message: '请输入预估租期', trigger: 'blur' }],
    leaseNum: [{ required: true, message: '请输入预估数量', trigger: 'blur' }],
    endTime: [{ required: true, message: '请选择需求截止日期', trigger: 'change' }],
    fileInfoList: [{ required: true, message: '请上传参考图片', trigger: 'blur' }],
})

const disabledDate = (date: any) => {
    const today = new Date()
    // 禁用今天之前的日期
    return date.getTime() < today.getTime()
}

const successResultCallBackFnDevicePic = (list: any) => {
    console.log(99999, list)
}

const getClassAndCompanyData = async () => {
    const classResult: any = await getGoodsClassListApi()
    const companyResult: any = await getCompanyListApi()

    classOptions.value = classResult.data
    companyOptions.value = companyResult.data
}

// 获取列表
const getLeaseListData = async () => {
    if (endTime.value.length > 0) {
        searchParams.finishStartTime = endTime.value[0]
        searchParams.finishEndTime = endTime.value[1]
    }
    if (releaseTime.value.length > 0) {
        searchParams.publishStartTime = releaseTime.value[0]
        searchParams.publishEndTime = releaseTime.value[1]
    }
    const { data: res }: any = await getLeaseListApi(searchParams)
    leaseList.value = res.rows
    total.value = res.total
}

// 重置
const onReset = () => {
    endTime.value = []
    releaseTime.value = []
    searchParams.finishStartTime = ''
    searchParams.finishEndTime = ''
    searchParams.publishStartTime = ''
    searchParams.publishEndTime = ''
    searchParams.pageNum = 1
    searchParams.pageSize = 10
    searchFormRef.value.resetFields()
    getLeaseListData()
}
// 删除
const onDelete = async (id: any) => {
    const res: any = await deleteLeaseInfoApi({ id })
    if (res.code === 200) {
        ElMessage({
            type: 'success',
            message: '删除成功',
        })
        getLeaseListData()
    }
}
// 重新发布
const onRepublish = async (id: any, type: any) => {
    isRepublish.value = false
    isSave.value = type
    const res: any = await getLeaseDetailsByIdApi({ id })
    const {
        leaseName,
        typeId,
        companyId,
        person,
        personPhone,
        leaseDay,
        leaseNum,
        endTime,
        description,
        typeIds,
    } = res.data

    Object.assign(addOrEditForm, {
        leaseName,
        typeId,
        companyId,
        person,
        personPhone,
        leaseDay,
        leaseNum,
        endTime,
        description,
        typeIds,
        id,
    })

    addOrEditForm.typeIds = addOrEditForm.typeIds.map((e: any) => {
        return (e *= 1)
    })

    addOrEditDialogVisible.value = true
}

// 提交
const onSubmit = (type: boolean) => {
    addOrEditFormRef.value.validate(async (valid: any) => {
        if (valid) {
            addOrEditForm.isSubmit = type
            addOrEditForm.typeId = addOrEditForm.typeIds[addOrEditForm.typeIds.length - 1]
            const SUBMIT_API = isRepublish.value ? addLeaseInfoApi : editLeaseInfoApi
            const res: any = await SUBMIT_API(addOrEditForm)
            if (res.code === 200) {
                ElMessage({
                    type: 'success',
                    message: '提交成功',
                })
                addOrEditFormRef.value.resetFields()
                addOrEditDialogVisible.value = false
                getLeaseListData()
            }
        }
    })
}

// 取消按钮
const onCancel = () => {
    addOrEditFormRef.value.resetFields()
    addOrEditDialogVisible.value = false
}

onMounted(() => {
    getClassAndCompanyData()
    getLeaseListData()
})
</script>

<style lang="scss" scoped>
:deep.upload-tip .el-form-item__label {
    color: transparent;
}
.el-pagination {
    justify-content: flex-end;
    padding: 5px 0;
}
// :deep.el-pagination.is-background .el-pager li.is-active {
//     background-color: #3cb4a6;
// }
</style>
