<template>
  <div class="app-container">
    <el-card style="margin-bottom: 20px" shadow="never">
      <el-form
        v-show="showSearch"
        :model="queryParams"
        ref="queryForm"
        size="small"
        class="search-form"
        label-width="120px"
        @submit.native.prevent
      >
        <el-form-item  label="装备类目:" prop='modelId'>
            <el-select
                v-model='queryParams.modelId'
                placeholder='请选择装备类目'
                style='width: 100%'
                clearable
                filterable
            >
                <el-option
                    v-for='item in equipmentNameOptions'
                    :key='item.value'
                    :label='item.label'
                    :value='item.value'
                />
            </el-select>
        </el-form-item>
        <el-form-item label="装备名称:" prop='maName'>
            <el-input
                v-model.trim='queryParams.maName'
                style='width: 100%'
                clearable
                placeholder='请输入装备名称'
            />
        </el-form-item>

        <!-- 表单按钮 -->
        <el-form-item class="form-right">
          <el-button icon="el-icon-refresh" size="mini" @click="handleReset">重置</el-button>
          <el-button type="primary" size="mini" icon="el-icon-search" @click="handleQuery" style="background: #2CBAB2;">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="content-box">
      <el-row :gutter="10" class="mb8" style="display: flex; justify-content: flex-end">
        <el-col :span="1.5">
          <el-button type="primary" size="mini" @click="handleAdd" style="background: #2CBAB2;">新增装备</el-button> 
        </el-col>
        <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" /> -->
      </el-row>

      <el-table height="546"
        :data="tableList"
        highlight-current-row
        style="width: 100%"
        v-loading="isLoading"
        border stripe
      >
        <el-table-column
          type="index"
          width="55"
          label="序号"
          align="center"
          :index="(index) => (queryParams.pageNum - 1) * queryParams.pageSize + index + 1"
        />
        <el-table-column align='center' prop='modelName' label='装备类目' />
        <el-table-column align='center' prop='maName' label='装备名称' />
        <el-table-column align='center' prop='maNum' label='装备数量' />
        <el-table-column align='center' prop='proCode' label='所属项目' />
        <el-table-column align='center' prop='rentalCompany' label='出租公司' />
        <el-table-column align='center' prop='leaseTerm' label='租赁时间' />
        <el-table-column align='center' prop='returnTime' label='归还时间' />
        <el-table-column align='center' prop='actualNumber' label='实际使用台班数' />
        <el-table-column align='center' prop='rentalAmount' label='租赁金额' />
        <el-table-column align='center' prop='fileList' label='装备图'>
            <template v-slot="{ row }">
                <span
                    v-if="row.fileList && row.fileList.trim() !== ''"
                    class='link-text'
                    @click='previewTableImages(row.fileList)'
                    style='color:#2CBAB2;cursor:pointer;'
                >
                    已上传
                </span>
                <span v-else>
                    未上传
                </span>
            </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作" align="center" width="150">
          <template v-slot="{ row }">
            <el-button type="text" @click="handleAdd(row)" style="color: #2CBAB2;">
                编辑
            </el-button>
            <el-button  type="text" style="color: #FF5129"  @click="handleDelete(row)">
                删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 简化版新增/编辑对话框：完全保留原有代码 -->
    <el-dialog
      width="700px"
      @close="handleDialogClose"
      destroy-on-close
      :title="dialogTitle" top="2vh"
      :visible.sync="addOrEditDialogVisible"
    >
      <el-form
        label-width="150px"
        label-position="right"
        ref="addOrEditFormRef"
        :model="addOrEditForm"
        :rules="addOrEditFormRules"
      >
        <el-row :gutter='20'>
            <el-col :span='24'>
                <el-form-item label='装备类目：' prop='modelId'>
                    <el-select
                        v-model='addOrEditForm.modelId'
                        placeholder='请选择装备类目'
                        style='width: 100%'
                        clearable
                        filterable
                    >
                        <el-option
                            v-for='item in equipmentNameOptions'
                            :key='item.value'
                            :label='item.label'
                            :value='item.value'
                        />
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row :gutter='20'>
            <el-col :span='24'>
                <el-form-item label='装备名称：' prop='maName'>
                    <el-input
                        v-model='addOrEditForm.maName'
                        maxlength='50'
                        placeholder='请输入装备名称'
                        clearable
                        style='width: 100%'
                    />
                </el-form-item>
            </el-col>
        </el-row>
        <el-row :gutter='20'>
            <el-col :span='24'>
                <el-form-item label='装备数量：' prop='maNum'>
                    <el-input-number
                        v-model='addOrEditForm.maNum'
                        :min='1'
                        placeholder='请输入数量'
                        style='width: 100%'
                    />
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter='20'>
            <el-col :span='24'>
                <el-form-item prop='proCode' label='所属项目:'>
                    <el-select
                        v-model='addOrEditForm.proCode'
                        placeholder='请选择所属项目'
                        style='width: 100%;'
                    >
                        <el-option
                            v-for='item in projectOption'
                            :key='item.proCode'
                            :label='item.proName'
                            :value='item.proCode'
                        />
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter='20'>
            <el-col :span='24'>
                <el-form-item label='出租公司：' prop='rentalCompany'>
                    <el-input
                        v-model='addOrEditForm.rentalCompany'
                        maxlength='50'
                        placeholder='请输入出租公司'
                        clearable
                        style='width: 100%'
                    />
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter='20'>
            <el-col :span='24'>
                <el-form-item label='租赁时间' prop='leaseTerm'>
                    <el-date-picker
                        v-model='addOrEditForm.leaseTerm'
                        type='date'
                        placeholder='请选择租赁时间'
                        style='width: 100%'
                        format='yyyy-MM-dd'
                        value-format='yyyy-MM-dd'
                    >
                    </el-date-picker>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter='20'>
            <el-col :span='24'>
                <el-form-item label='归还时间' prop='returnTime'>
                    <el-date-picker
                        v-model='addOrEditForm.returnTime'
                        placeholder='请选择归还时间'
                        type='date'
                        style='width: 100%'
                        format='yyyy-MM-dd'
                        value-format='yyyy-MM-dd'
                    >
                    </el-date-picker>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter='20'>
            <el-col :span='24'>
                <el-form-item label='实际使用台班数：' prop='actualNumber'>
                    <el-input-number
                        v-model='addOrEditForm.actualNumber'
                        :min='1'
                        placeholder='请输入实际使用台班数'
                        style='width: 100%'
                    />
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter='20'>
            <el-col :span='24'>
                <el-form-item label='租赁金额：' prop='rentalAmount'>
                    <el-input-number
                        v-model='addOrEditForm.rentalAmount'
                        :min='1'
                        placeholder='请输入租赁金额'
                        style='width: 100%'
                    />
                </el-form-item>
            </el-col>
        </el-row>


        <!-- 图片一类的处理 --> 
        <el-row :gutter='20'>
            <el-col :span='24'>
                <el-form-item
                    style='font-weight: bold'
                    label='装备图：'
                    prop='fileList'
                >
                    <ImageUpload
                        v-model="addOrEditForm.fileList"
                        :value="addOrEditForm.fileList"
                        :limit="5"
                        @input="handleImageChange"
                    />
                </el-form-item>
            </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addOrEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">
          提交
        </el-button>
      </div>
    </el-dialog>

    <el-dialog 
        :visible.sync="dialogVisiblePreview"
        title="查看装备图片"
        width="60%" append-to-body
    >
        <div style="display:flex; flex-wrap:wrap; gap:10px;">
            <img
                v-for="(url, index) in previewImages"
                :key="index"
                :src="url"
                style="width:120px; height:120px; object-fit:cover; cursor:pointer;border: 2px solid #2CBAB2;border-radius: 4px;padding: 2px; "
                @click="handleFile(url)"
            />
        </div> 
        <template #footer>
            <el-button @click="dialogVisiblePreview = false">关闭</el-button>
        </template>
    </el-dialog>


  </div>
</template>

<script>
import { getCategoryListApi,getProListApi,getContractListApi,addContractApi, editContractApi, delContractApi  } from '@/api/rentEquipmentManager'
import ImageUpload from '@/components/ImageUpload'

export default {
  name: 'EntryApply',
  components: {  ImageUpload },
  data() {
    const validateLeaseTime = (rule, value, callback) => {
      const returnTime = this.addOrEditForm.returnTime
      if (!value || !returnTime) {
          callback()
      } else if (new Date(value) > new Date(returnTime)) {
          callback(new Error('租赁时间必须早于归还时间'))
      } else {
          callback()
      }
    }
    const validateReturnTime = (rule, value, callback) => {
      const leaseTerm = this.addOrEditForm.leaseTerm
      if (!value || !leaseTerm) {
          callback()
      } else if (new Date(value) < new Date(leaseTerm)) {
          callback(new Error('归还时间必须晚于租赁时间'))
      } else {
          callback()
      }
    }
    return {
      isLoading: false,
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // type: '1',
        modelId: '', // 关键字
        maName: '', // 开始时间
      },
      equipmentNameOptions:[],
      projectOption:[],
      total: 0, // 总条数 
      // 表格数据
      tableList: [],
      statusList: [
        { label: '草稿', value: '0' },
        { label: '待审批', value: '1' },
        // { label: '审批通过', value: '2' },
        { label: '驳回', value: '3' }
      ],
      selectedRowKeys: [],
      addOrEditDialogVisible: false,
      dialogTitle: '',
      submitLoading: false,
      // 表单数据
      addOrEditForm: {
        id: null,
        modelId: '',
        maType: '',
        maName: '',
        maNum: '',
        type: '1',
        mainFileTempList: [], // 临时存储新上传的文件
        proCode: '',
        rentalCompany: '',
        leaseTerm: null,
        returnTime: null,
        actualNumber: '',
        rentalAmount: '',
        fileList: '', 
      },
      // 表单校验规则（匹配表单字段）
      addOrEditFormRules: {
          modelId: [{ required: true, message: '请选择装备类目', trigger: 'change' }],
          maType: [{ required: true, message: '请输入装备分类', trigger: 'blur' }],
          maName: [{ required: true, message: '请输入装备名称', trigger: 'blur' }],
          maNum: [{ required: true, type: 'number', message: '请输入装备数量', trigger: 'blur' }],

          proCode: [{ required: true, message: '请选择所属项目', trigger: 'change' }],
          rentalCompany: [{ required: true, message: '请输入出租公司', trigger: 'blur' }],
          leaseTerm: [
              { required: true, message: '请选择租赁时间', trigger: 'change' },
              { validator: validateLeaseTime, trigger: 'change' },
          ],
          returnTime: [
              { required: true, message: '请选择归还时间', trigger: 'change' },
              { validator: validateReturnTime, trigger: 'change' },
          ],
          actualNumber: [{ required: true, type: 'number', message: '请输入实际使用台班数', trigger: 'blur' }],
          rentalAmount: [{ required: true, type: 'number', message: '请输入租赁金额', trigger: 'blur' }],
      },
      dialogVisiblePreview:false,
      previewImages:[]
    }
  },
  created() {
    this.getCategoryList()
    this.getProList()
    this.getList()
  },
  methods: {
    // 装备类目下拉框获取
    async getCategoryList() {
        const res = await getCategoryListApi({})
        if(res.code==200){
            this.equipmentNameOptions = res.data.map(item => ({
                label: item.equipmentName,
                value: item.typeId,
            }))
        }else{
            this.equipmentNameOptions = []
        } 
    },
    // 装备类目下拉框获取
    async getProList() {
        const res = await getProListApi({})
        if(res.code==200){
            this.projectOption = res.data
        }else{
            this.projectOption = []
        } 
    },

    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.$refs.queryForm.resetFields()
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.getList()
    },
    // 获取列表
    async getList() {
      console.log('列表-查询', this.queryParams)
      this.isLoading = true
      try {
        const params = {
          ...this.queryParams
        } 
        console.log('🚀 ~ getList ~ params:', params)
        const res = await getContractListApi(params)
        console.log('🚀 ~ 获取列表 ~ res:', res)
        this.tableList = res.data.rows || []
        this.total = res.data.total || 0
      } catch (error) {
        console.log('🚀 ~ 获取列表 ~ error:', error)
        this.tableList = []
        this.total = 0
      } finally {
        this.isLoading = false
      }
    },
    // 新增
    handleAdd(row) {
      // 1. 先清空旧表单（放在最前）
      this.$refs.addOrEditFormRef?.resetFields()

      // 2. 先判断是新增还是编辑，设置标题和标识
      if (row.id) { 
        this.dialogTitle = '外租装备编辑' // 用新的标题变量
        // 编辑：赋值表单（深拷贝避免修改原数据）
        this.addOrEditForm = {
          ...row,
        }
      } else { 
        this.dialogTitle = '外租装备新建' // 用新的标题变量
        // 新增：重置表单默认值
        this.addOrEditForm = {
            id: null,
            modelId: '',
            maType: '',
            maName: '',
            maNum: '',
            type: '1',
            mainFileTempList: [], // 临时存储新上传的文件
            proCode: '',
            rentalCompany: '',
            leaseTerm: null,
            returnTime: null,
            actualNumber: '',
            rentalAmount: '',
            fileList: '', 
        }
      } 
      // 3. 最后打开弹窗
      this.addOrEditDialogVisible = true
    },
    /** 提交按钮 */
    submitForm: function() {
      console.log(this.addOrEditForm, '提交参数---')
      this.$refs['addOrEditFormRef'].validate((valid) => {
        if (valid) {
          this.addOrEditForm.type = 1
          if (this.addOrEditForm.id) {
            editContractApi(this.addOrEditForm)  
              .then((response) => { 
                this.$modal.msgSuccess('修改成功')
                this.addOrEditDialogVisible = false
                this.getList() 
              })
              .catch(() => {

              })
          } else {
            addContractApi(this.addOrEditForm)
              .then((response) => { 
                this.$modal.msgSuccess('新增成功')
                this.addOrEditDialogVisible = false
                this.getList() 
              })
              .catch(() => {
                
              })
          }
        }
      })
    },
    handleDialogClose() { 
      this.$refs.addOrEditFormRef?.clearValidate()
    },
    handleImageChange(val) {
      console.log('🚀 ~ val:', val)
      console.log('🚀 ~ val:', this.addOrEditForm.fileList) 
    },
    previewTableImages(fileList){
      if (!fileList) return
      // 拆成数组
      this.previewImages = fileList.split(',')
      this.dialogVisiblePreview = true
    },
    handleFile(fileUrl) {
      // 打开文件预览
      window.open(fileUrl, '_blank')
    },
    // 删除
    async handleDelete(row) {
      // 确认
      this.$modal.confirm('是否确认删除该数据项？').then(async() => {
        try {
          await delContractApi({ id: row.id })
          this.$modal.msgSuccess('操作成功')
          this.getList()
        } catch (error) {
          console.log('🚀 ~ error:', error)
        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.app-container{
  background: #F0F0F0;
}
::v-deep.el-button--primary{
  background-color: #2CBAB2;
  border-color: #2CBAB2;
}
::v-deep.el-button--danger{
  background-color: #FF5129;
  border-color: #FF5129;
}
::v-deep.el-tag.el-tag--info {
    background-color: #F5F5F5;
    border-color: #B3B3B3;
    color: #B3B3B3;
}
::v-deep.el-tag.el-tag--warn{
    background-color: rgba(255,171,41,0.1);;
    border: #FFAB29;
    color: #FFAB29;
}
::v-deep.el-tag.el-tag--success {
    background-color: rgba(52,226,199,0.1);
    border-color: #34E2C7;
    color: #34E2C7;
}
.content-box {
  height: calc(100vh - 260px);
}
</style>
