<template>
  <div class="contract-detail-page">
    <el-card class="filter-card">
      <el-form :model="searchForm" inline label-width="90px" size="small">
        <el-form-item label="合同名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入合同名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="合同类型">
          <el-select
            v-model="searchForm.contract_type"
            placeholder="全部"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in contractTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="执行状态">
          <el-select
            v-model="searchForm.status"
            placeholder="全部"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-select
            v-model="searchForm.type"
            placeholder="全部"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <div class="filter-actions">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <div slot="header" class="table-card__header">
        <div class="table-card__title">合同台账详情</div>
        <el-button type="primary" size="small" icon="el-icon-plus" @click="openDialog('add')">
          新增明细
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="number" label="合同编号" width="160" show-overflow-tooltip />
        <el-table-column prop="name" label="合同名称" min-width="200" show-overflow-tooltip />
        <el-table-column label="合同类型" width="120">
          <template slot-scope="{ row }">
            {{ formatContractType(row.contract_type) }}
          </template>
        </el-table-column>
        <el-table-column label="类型" width="100">
          <template slot-scope="{ row }">
            {{ formatType(row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="supply" label="供应商" min-width="160" show-overflow-tooltip />
        <el-table-column label="合同金额(元)" width="150" align="right">
          <template slot-scope="{ row }">
            {{ row.money ? moneyFormatter(row.money) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="date" label="签订日期" width="120" />
        <el-table-column label="执行部门" min-width="140" show-overflow-tooltip>
          <template slot-scope="{ row }">
            {{ formatDepartment(row.carry_department) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="110">
          <template slot-scope="{ row }">
            <el-tag :type="row.status === 2 ? 'success' : 'warning'">
              {{ formatStatus(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template slot-scope="{ row }">
            <el-button type="text" size="mini" @click="openDialog('view', row)">查看</el-button>
            <el-button type="text" size="mini" @click="openDialog('edit', row)">编辑</el-button>
            <el-popconfirm title="确认删除该明细？" @confirm="handleDelete(row)">
              <el-button slot="reference" type="text" size="mini">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page.sync="pagination.page"
          :page-size.sync="pagination.page_size"
          :page-sizes="[10, 20, 30, 50]"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="820px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="detailFormRef"
        :model="detailForm"
        :rules="formRules"
        :disabled="dialogMode === 'view'"
        label-width="130px"
        size="small"
        class="detail-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="支出" prop="contract_id">
              <el-select
                v-model="detailForm.contract_id"
                placeholder="输入关键词搜索合同"
                filterable
                remote
                clearable
                reserve-keyword
                :remote-method="searchContractOptions"
                :loading="contractOptionsLoading"
                @change="handleContractSelect"
              >
                <el-option
                  v-for="item in contractOptions"
                  :key="item.id"
                  :label="formatContractOption(item)"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同编号" prop="number">
              <el-input v-model="detailForm.number" placeholder="请输入合同编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同名称" prop="name">
              <el-input v-model="detailForm.name" placeholder="请输入合同名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同类型" prop="contract_type">
              <el-select v-model="detailForm.contract_type" placeholder="请选择合同类型">
                <el-option
                  v-for="item in contractTypeOptions"
                  :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="12">
            <el-form-item label="类型" prop="type">
              <el-select v-model="detailForm.type" placeholder="请选择类型">
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同金额(元)" prop="money">
              <el-input-number
                v-model="detailForm.money"
                :min="0"
                :step="1000"
                :precision="2"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商" prop="supply">
              <el-input v-model="detailForm.supply" placeholder="请输入供应商" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="执行部门" prop="carry_department">
              <el-select
                v-model="detailForm.carry_department"
                placeholder="请选择执行部门"
                filterable
              >
                <el-option
                  v-for="item in departments"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资金渠道" prop="money_way_id">
              <el-select v-model="detailForm.money_way_id" placeholder="请选择资金渠道">
                <el-option
                  v-for="item in moneyWay"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采购形式" prop="purchase_type_id">
              <el-select v-model="detailForm.purchase_type_id" placeholder="请选择采购形式">
                <el-option
                  v-for="item in purchaseType"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购方式" prop="purchase_way_id">
              <el-select v-model="detailForm.purchase_way_id" placeholder="请选择采购方式">
                <el-option
                  v-for="item in purchaseWay"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否预算" prop="is_plan">
              <el-radio-group v-model="detailForm.is_plan">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="detailForm.status" placeholder="请选择状态">
                <el-option
                  v-for="item in statusOptions"
                  :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="12">
            <el-form-item label="签订日期" prop="date">
              <el-date-picker
                v-model="detailForm.date"
                type="date"
                placeholder="请选择签订日期"
                value-format="yyyy-MM-dd"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="起止日期">
              <el-date-picker
                v-model="termRange"
                type="daterange"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="附件">
          <el-upload
            class="upload-block"
            :action="uploadAction"
            :file-list="fileList"
            :on-success="handleUploadSuccess"
            :on-remove="handleUploadRemove"
            :before-upload="beforeUpload"
            :disabled="dialogMode === 'view'"
          >
            <el-button
              v-if="dialogMode !== 'view'"
              type="primary"
              size="mini"
            >
              上传附件
            </el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="detailForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          v-if="dialogMode !== 'view'"
          type="primary"
          :loading="submitLoading"
          @click="submitForm"
        >
          保 存
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getcontractdetail,
  detailcontractdetail,
  delcontractdetail,
  editorcontractdetail
} from '@/api/contract/contractDetail'
import { getContract } from '@/api/contract/contract'
import { getparameter } from '@/api/system/dictionary'
import { listdeptNoAuth } from '@/api/system/department'
import { moneyFormatter } from '@/utils/index'

export default {
  name: 'ContractDetails',
  data() {
    return {
      loading: false,
      submitLoading: false,
      tableData: [],
      pagination: {
        page: 1,
        page_size: 10,
        total: 0
      },
      searchForm: {
        name: '',
        contract_type: '',
        status: '',
        type: ''
      },
      dialogVisible: false,
      dialogMode: 'add',
      detailForm: {
        id: '',
        contract_id: '',
        number: '',
        name: '',
        contract_type: '',
        supply: '',
        money: null,
        start_date: '',
        end_date: '',
        date: '',
        files: [],
        remark: '',
        supply_id: '',
        carry_department: '',
        money_way_id: '',
        is_plan: 1,
        status: 1,
        type: '',
        purchase_type_id: '',
        purchase_way_id: ''
      },
      termRange: [],
      fileList: [],
      uploadAction: process.env.VUE_APP_UPLOAD_API,
      contractTypeOptions: [
        { label: '收入类', value: 1 },
        { label: '支出类', value: 2 },
        { label: '技术协议', value: 3 },
        { label: '其他', value: 4 }
      ],
      typeOptions: [
        { label: '服务', value: 1 },
        { label: '货品', value: 2 },
        { label: '工程', value: 3 }
      ],
      statusOptions: [
        { label: '待签订', value: 1 },
        { label: '已签订', value: 2 }
      ],
      departments: [],
      moneyWay: [],
      purchaseType: [],
      purchaseWay: [],
      contractOptions: [],
      contractOptionsLoading: false,
      formRules: {
        contract_id: [{ required: true, message: '请输入合同ID', trigger: 'blur' }],
        number: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
        name: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
        contract_type: [{ required: true, message: '请选择合同类型', trigger: 'change' }],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        money: [{ required: true, message: '请输入合同金额', trigger: 'blur' }],
        supply: [{ required: true, message: '请输入供应商', trigger: 'blur' }],
        carry_department: [{ required: true, message: '请选择执行部门', trigger: 'change' }],
        money_way_id: [{ required: true, message: '请选择资金渠道', trigger: 'change' }],
        purchase_type_id: [{ required: true, message: '请选择采购形式', trigger: 'change' }],
        purchase_way_id: [{ required: true, message: '请选择采购方式', trigger: 'change' }],
        date: [{ required: true, message: '请选择签订日期', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      }
    }
  },
  computed: {
    dialogTitle() {
      if (this.dialogMode === 'add') return '新增合同明细'
      if (this.dialogMode === 'edit') return '编辑合同明细'
      return '查看合同明细'
    }
  },
  created() {
    this.detailForm = this.getEmptyForm()
    this.fetchDictionaries()
    this.getList()
  },
  methods: {
    moneyFormatter,
    getEmptyForm() {
      return {
        id: '',
        contract_id: this.$route.query.contractId || '',
        number: '',
        name: '',
        contract_type: '',
        supply: '',
        money: null,
        start_date: '',
        end_date: '',
        date: '',
        files: [],
        remark: '',
        supply_id: '',
        carry_department: '',
        money_way_id: '',
        is_plan: 1,
        status: 1,
        type: '',
        purchase_type_id: '',
        purchase_way_id: ''
      }
    },
    async fetchDictionaries() {
      await Promise.all([
        this.getDepartments(),
        this.getMoneyWay(),
        this.getPurchaseType(),
        this.getPurchaseWay()
      ])
    },
    async getDepartments() {
      const res = await listdeptNoAuth()
      this.departments = res || []
    },
    async getMoneyWay() {
      const res = await getparameter({ number: 'money_way' })
      this.moneyWay = res?.detail || []
    },
    async getPurchaseType() {
      const res = await getparameter({ number: 'purchase_type' })
      this.purchaseType = res?.detail || []
    },
    async getPurchaseWay() {
      const res = await getparameter({ number: 'purchase_way' })
      this.purchaseWay = res?.detail || []
    },
    async getList() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.page,
          page_size: this.pagination.page_size,
          ...this.searchForm
        }
        const res = await getcontractdetail(params, true)
        const list = res?.list?.data || res?.data || []
        this.tableData = list
        this.pagination.total = res?.list?.total || res?.total || list.length
      } finally {
        this.loading = false
      }
    },
    handleSearch() {
      this.pagination.page = 1
      this.getList()
    },
    handleReset() {
      this.searchForm = {
        name: '',
        contract_type: '',
        status: '',
        type: ''
      }
      this.pagination.page = 1
      this.getList()
    },
    handleSizeChange(size) {
      this.pagination.page_size = size
      this.pagination.page = 1
      this.getList()
    },
    handleCurrentChange(page) {
      this.pagination.page = page
      this.getList()
    },
    formatContractType(value) {
      return this.contractTypeOptions.find((item) => item.value === Number(value))?.label || '-'
    },
    formatType(value) {
      return this.typeOptions.find((item) => item.value === Number(value))?.label || '-'
    },
    formatStatus(value) {
      return this.statusOptions.find((item) => item.value === Number(value))?.label || '-'
    },
    formatDepartment(id) {
      return this.departments.find((item) => Number(item.id) === Number(id))?.name || '-'
    },
    openDialog(mode, row) {
      this.dialogMode = mode
      if (mode === 'add') {
        this.detailForm = this.getEmptyForm()
        this.termRange = []
        this.fileList = []
        this.dialogVisible = true
        return
      }
      this.loadDetail(row.id)
    },
    async loadDetail(id) {
      this.loading = true
      try {
        const res = await detailcontractdetail({ id })
        this.detailForm = {
          ...this.getEmptyForm(),
          ...res
        }
        this.detailForm.id = res.id
        if (res.contract_id && !this.contractOptions.find((item) => item.id === res.contract_id)) {
          this.contractOptions = [{ id: res.contract_id, name: res.name, number: res.number, ...res }, ...this.contractOptions]
        }
        this.termRange = res.start_date && res.end_date ? [res.start_date, res.end_date] : []
        this.fileList = (res.files_detail || []).map((file) => ({
          name: file.original_name,
          url: file.url,
          response: file
        }))
        this.dialogVisible = true
      } finally {
        this.loading = false
      }
    },
    beforeUpload(file) {
      const maxSize = 20 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.warning('上传文件大小不能超过20MB')
        return false
      }
      return true
    },
    handleUploadSuccess(response, file, fileList) {
      this.fileList = fileList
    },
    handleUploadRemove(file, fileList) {
      this.fileList = fileList
    },
    async searchContractOptions(keyword) {
      if (!keyword) {
        this.contractOptions = []
        return
      }
      this.contractOptionsLoading = true
      try {
        const res = await getContract(
          {
            keyword,
            page: 1,
            page_size: 999,
            is_auth: 1
          },
          true
        )
        this.contractOptions = res?.list?.data || []
      } finally {
        this.contractOptionsLoading = false
      }
    },
    handleContractSelect(contractId) {
      if (!contractId) {
        return
      }
      const selected = this.contractOptions.find((item) => item.id === contractId)
      if (selected) {
        this.syncContractFields(selected)
      }
    },
    syncContractFields(contract) {
      const fields = [
        'number',
        'name',
        'contract_type',
        'supply',
        'money',
        'start_date',
        'end_date',
        'date',
        'remark',
        'supply_id',
        'carry_department',
        'money_way_id',
        'is_plan',
        'status',
        'type',
        'purchase_type_id',
        'purchase_way_id'
      ]
      fields.forEach((field) => {
        if (contract[field] !== undefined && contract[field] !== null) {
          this.$set(this.detailForm, field, contract[field])
        }
      })
    },
    formatContractOption(contract) {
      const number = contract.number || ''
      const name = contract.name || ''
      return number ? `${number} - ${name}` : name
    },
    submitForm() {
      this.$refs.detailFormRef.validate(async(valid) => {
        if (!valid) return
        this.submitLoading = true
        const payload = {
          ...this.detailForm
        }
        payload.start_date = this.termRange?.[0] || ''
        payload.end_date = this.termRange?.[1] || ''
        payload.files = this.fileList.map((item) => item.response?.id).filter(Boolean)
        try {
          if (this.dialogMode === 'add') {
            delete payload.id
          }
          await editorcontractdetail(payload)
          this.$message.success(this.dialogMode === 'add' ? '新增成功' : '编辑成功')
          this.dialogVisible = false
          this.getList()
        } finally {
          this.submitLoading = false
        }
      })
    },
    async handleDelete(row) {
      await delcontractdetail({ id: row.id })
      this.$message.success('删除成功')
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.contract-detail-page {
  padding: 20px;
  .filter-card {
    margin-bottom: 16px;
    .filter-actions {
      display: inline-flex;
      gap: 8px;
      margin-left: 16px;
      vertical-align: middle;
    }
  }
  .table-card__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .table-card__title {
    font-weight: 600;
  }
  .pagination {
    margin-top: 16px;
    text-align: right;
  }
  .detail-form {
    .el-input,
    .el-select,
    .el-date-editor,
    .el-input-number {
      width: 100%;
    }
  }
  .upload-block {
    width: 100%;
  }
}
</style>

