<template>
  <div class="material-tab">
    <span class="link-text">被监审单位需报送材料：</span>
    <el-button
      v-if="!isView"
      plain
      type="success"
      icon="el-icon-circle-plus"
      style="margin-bottom: 20px"
      @click="handleAddMaterial"
    >
      添加材料
    </el-button>
    <CostAuditTable
      class="mt20"
      :table-data="materialList"
      :columns="materialColumns"
      :show-index="true"
      :show-pagination="true"
      :show-action-column="true"
      :pagination="pagination"
      @pagination-change="handlePaginationChange"
    >
      <template #orderNum="scope">
        <el-input
          v-model="scope.row.orderNum"
          size="mini"
          style="width: 60px"
          @blur="handleSortChange(scope.row)"
        ></el-input>
      </template>
      <template #action="scope">
        <el-button
          type="primary"
          size="mini"
          plain
          icon="el-icon-edit"
          :disabled="isView"
          @click="handleEditMaterial(scope.row)"
        >
          修改
        </el-button>
        <el-button
          type="danger"
          size="mini"
          plain
          icon="el-icon-delete"
          :disabled="isView"
          @click="handleDeleteMaterial(scope.row)"
        >
          删除
        </el-button>
        />
      </template>
    </CostAuditTable>
    <legal-dialog
      ref="legalDialog"
      :dialog-visible="materialDialogVisible"
      :dialog-title="materialDialogTitle"
      :template-data="templateData"
      :template-columns="templateColumns"
      :form-data="formData.material"
      @submit="handleMaterialSubmit"
      @cancel="handleMaterialCancel"
    />
  </div>
</template>
<script>
  import {
    addCostProjectMaterial,
    updateCostProjectMaterial,
    deleteCostProjectMaterial,
    getCostProjectMaterialPageList,
  } from '@/api/taskCustomizedRelease.js'
  import CostAuditTable from '@/components/costAudit/CostAuditTable.vue'
  import LegalDialog from '@/views/costAudit/baseInfo/catalogManage/legalDialog.vue'
  import { dictMixin } from '@/mixins/useDict'
  export default {
    components: {
      CostAuditTable,
      LegalDialog,
    },
    mixins: [dictMixin],
    props: {
      // 父组件传递的参数
      project: {
        type: Object,
        default: () => {},
      },
      isView: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        dictData: {
          materialType: [], //资料类别
          formatAsk: [], //格式要求
        },
        // 模板相关数据
        templateData: [],
        templateColumns: [
          {
            prop: 'surveyTemplateName',
            label: '模板名称',
            align: 'center',
          },
          {
            prop: 'surveyTemplateCode',
            label: '模板编码',
            align: 'center',
          },
          {
            prop: 'createTime',
            label: '创建时间',
            align: 'center',
          },
        ],
        formData: {
          material: {},
        },
        addMaterial: false,
        materialDialogVisible: false,
        materialDialogTitle: '添加',
        // 简化数据结构，避免嵌套对象可能导致的数据绑定问题
        materialList: [],
        pagination: {
          currentPage: 1,
          pageSize: 50,
          total: 0,
        },
        materialColumns: [],
      }
    },
    computed: {},
    watch: {
      // 监听project变化，确保有项目ID时刷新数据
      project: {
        handler(newVal) {
          if (newVal && newVal.projectId) {
            this.loadMaterialData()
          }
        },
        deep: true,
      },
    },
    mounted() {
      // 组件挂载时先初始化表格列配置
      this.materialColumns = this.getMaterialColumns()
      // 然后加载数据
      if (this.project && this.project.projectId) {
        this.loadMaterialData()
      }
    },
    methods: {
      // 获取表格列配置
      getMaterialColumns() {
        return [
          {
            prop: 'informationType',
            label: '材料分类',
            width: 120,
            align: 'center',
            formatter: (row) => {
              return this.getDictName('materialType', row.informationType)
            },
          },
          {
            prop: 'informationName',
            label: '材料名称',
            minWidth: 200,
            align: 'left',
          },
          {
            prop: 'informationRequire',
            label: '材料要求说明',
            minWidth: 300,
            align: 'left',
          },
          {
            prop: 'formatRequired',
            label: '格式要求',
            width: 120,
            align: 'center',
            formatter: (row) => {
              return this.getDictName('formatAsk', row.formatRequired)
            },
          },
          {
            prop: 'orderNum',
            label: '排序',
            width: 120,
            align: 'center',
            slotName: 'orderNum',
          },
          {
            prop: 'action',
            label: '操作',
            align: 'center',
            width: 200,
            slotName: 'action',
            actions: [
              {
                name: 'edit',
                label: '修改',
                type: 'text',
                size: 'mini',
                onClick: this.handleEditMaterial,
                disabled: this.isView,
              },
              {
                name: 'delete',
                label: '删除',
                type: 'text',
                size: 'mini',
                className: 'delete-btn',
                onClick: this.handleDeleteMaterial,
                disabled: this.isView,
              },
            ],
          },
        ]
      },

      // 加载材料数据
      loadMaterialData() {
        // 确保project和projectId存在
        if (!this.project || !this.project.projectId) {
          console.warn('项目ID不存在，无法加载材料数据')
          return
        }
        const { currentPage, pageSize } = this.pagination
        const params = {
          projectId: this.project.projectId,
          page: currentPage,
          size: pageSize,
        }
        getCostProjectMaterialPageList(params)
          .then((res) => {
            if (res && res.value && res.value.value) {
              this.materialList = Array.isArray(res.value.value.records)
                ? res.value.value.records
                : []
              this.pagination.total = Number(res.value.value.total) || 0
            } else {
              this.materialList = []
              this.pagination.total = 0
            }
          })
          .catch((error) => {
            console.error('加载材料数据失败:', error)
            // 错误时清空数据避免显示异常
            this.materialList = []
            this.pagination.total = 0
          })
      },

      // 排序变更
      handleSortChange(row) {
        // 排序逻辑
        let data = {
          ...row,
          projectId: this.project.projectId,
        }
        updateCostProjectMaterial(data)
          .then(() => {
            this.$message.success('修改成功')
            this.loadMaterialData()
          })
          .catch(() => {})
      },
      // 新增材料
      handleAddMaterial() {
        this.formData.material = {
          informationType: '',
          informationName: '',
          informationRequire: '',
          formatRequired: '',
          templateId: '',
          surveyTemplateName: '',
          orderNum: 1,
          isRequired: '0',
        }
        this.materialDialogVisible = true
        this.materialDialogTitle = '添加'
      },

      // 编辑材料
      handleEditMaterial(row) {
        this.formData.material = { ...row }
        this.materialDialogVisible = true
        this.materialDialogTitle = '修改'
      },

      // 删除材料
      handleDeleteMaterial(row) {
        this.$confirm(
          `确定要删除资料名称为${row.informationName}的数据吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(() => {
            try {
              deleteCostProjectMaterial(row.id).then(() => {
                this.$message.success('删除成功')
                this.loadMaterialData()
              })
            } catch (error) {
              console.error('删除失败:', error)
            }
          })
          .catch(() => {
            this.$message.info('已取消删除')
          })
      },

      // 保存材料
      handleMaterialSubmit(formData) {
        let data = {
          ...formData,
          projectId: this.project.projectId,
        }
        updateCostProjectMaterial(data)
          .then(() => {
            this.$message.success('保存成功')
            this.$refs.legalDialog.setSubmitting(false)
            this.materialDialogVisible = false
            this.loadMaterialData()
          })
          .catch(() => {
            this.$refs.legalDialog.setSubmitting(false)
          })
      },
      handleLegalSubmit() {},
      handleMaterialCancel() {
        this.formData.material = {
          informationType: '',
          informationName: '',
          informationRequire: '',
          formatRequired: '',
          templateId: '',
          surveyTemplateName: '',
          orderNum: 1,
          isRequired: '0',
        }
        this.materialDialogVisible = false
      },
      getTemplateOptions() {},
      templatePaginationChange() {},
      handlePaginationChange({ currentPage, pageSize }) {
        this.pagination.currentPage = currentPage
        this.pagination.pageSize = pageSize
        this.loadMaterialData()
      },
    },
  }
</script>
<style lang="scss" scoped>
  @import '@/styles/costAudit.scss';
</style>
