<template>
  <div class="mod-config">
    <!-- 查询条件 -->
    <el-form :inline="true" label-position="top" :model="searchData">
      <el-form-item label="货币代码">
        <el-input v-model="searchData.currency" clearable style="width: 120px" placeholder="货币代码"></el-input>
      </el-form-item>
      <el-form-item label="货币描述">
        <el-input v-model="searchData.currencyDesc" clearable style="width: 160px" placeholder="货币描述"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchData.active" clearable placeholder="状态" style="width: 120px">
          <el-option label="启用" value="Y"></el-option>
          <el-option label="禁用" value="N"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label=" ">
        <el-button type="primary" @click="getDataList()">查询</el-button>
        <el-button type="primary" @click="addModal()">新增</el-button>
      </el-form-item>
    </el-form>

    <!-- 主表 -->
    <el-table
      :height="height"
      :data="dataList"
      border
      v-loading="dataListLoading"
      style="width: 100%;">
      <el-table-column
        prop="currency"
        header-align="center"
        align="left"
        width="120"
        label="货币代码">
      </el-table-column>
      <el-table-column
        prop="currencyDesc"
        header-align="center"
        align="left"
        min-width="150"
        label="货币描述"
        show-overflow-tooltip>
      </el-table-column>
      <el-table-column
        prop="site"
        header-align="center"
        align="center"
        width="120"
        label="站点">
      </el-table-column>
      <el-table-column
        prop="active"
        header-align="center"
        align="center"
        width="100"
        label="状态">
        <template slot-scope="scope">
          <span>{{ scope.row.active === 'Y' ? '启用' : '禁用' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="baseCurrency"
        header-align="center"
        align="center"
        width="120"
        label="基础货币">
        <template slot-scope="scope">
          <span>{{ scope.row.baseCurrency === 'Y' ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="120"
        label="操作">
        <template slot-scope="scope">
          <el-link style="cursor: pointer" @click="updateModal(scope.row)">编辑 |</el-link>
          <el-link style="cursor: pointer" @click="deleteHandle(scope.row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <!-- 新增/修改对话框 -->
    <el-dialog :title="modalTitle" :close-on-click-modal="false" v-drag :visible.sync="modalFlag" width="415px">
      <el-form :inline="true" label-position="top" :model="modalData" :rules="rules" ref="modalForm" style="margin-left: 7px;">
        <el-form-item label="货币代码" prop="currency" :rules="rules.currency">
          <el-input v-model="modalData.currency" :disabled="modalDisableFlag" style="width: 100px"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="active">
          <el-select v-model="modalData.active" style="width: 100px">
            <el-option label="启用" value="Y"></el-option>
            <el-option label="禁用" value="N"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="基础货币" prop="baseCurrency">
          <el-select v-model="modalData.baseCurrency" style="width: 100px">
            <el-option label="是" value="Y"></el-option>
            <el-option label="否" value="N"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-form :inline="true" label-position="top" :model="modalData" :rules="rules" style="margin-left: 7px;">
        <el-form-item label="货币描述" prop="currencyDesc" :rules="rules.currencyDesc">
          <el-input v-model="modalData.currencyDesc" style="width: 325px"></el-input>
        </el-form-item>
        <el-form-item label="站点" prop="site" :rules="rules.site" v-if="modalData.flag === '2'">
          <el-input v-model="modalData.site" disabled style="width: 325px"></el-input>
        </el-form-item>
      </el-form>
      <el-footer style="height:40px;margin-top: 20px;text-align:center">
        <el-button type="primary" @click="saveData()">保存</el-button>
        <el-button type="primary" @click="modalFlag = false">关闭</el-button>
      </el-footer>
    </el-dialog>
  </div>
</template>

<script>
import { getCurrencyListWithPaging,
  addCurrency,
  updateCurrency,
  deleteCurrency } from '@/api/baseInformation/srmCurrency.js'

export default {
  name: "srmSupplierCurrency",
  data() {
    return {
      height: 300,
      dataList:[],
      dataListLoading: false,
      pageIndex: 1,
      pageSize: 20,
      totalPage: 0,
      searchData: {
        currency: '',
        currencyDesc: '',
        active: '',
        baseCurrency: '',
        site: this.$store.state.user.site
      },
      modalFlag: false,
      modalTitle: '',
      modalDisableFlag: false,
      isEdit: false,
      modalData: {
        currency: '',
        currencyDesc: '',
        site: this.$store.state.user.site,
        active: 'Y',
        baseCurrency: 'N'
      },
      rules: {
        currency: [
          { required: true, message: '请输入货币代码', trigger: 'blur' }
        ],
        currencyDesc: [
          { required: true, message: '请输入货币描述', trigger: 'blur' }
        ],
        site: [
          { required: true, message: '请输入站点', trigger: 'blur' }
        ],
        active: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        baseCurrency: [
          { required: true, message: '请选择是否基础货币', trigger: 'change' }
        ]
      },
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.height = window.innerHeight - 240;
    })
    // 初始化数据
    this.getDataList()
  },
  methods: {
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true
      const params = {
        ...this.searchData,
        page: this.pageIndex,
        limit: this.pageSize
      }

      getCurrencyListWithPaging(params).then(({data}) => {
        if (data && data.code === 0) {
          const pageData = data.data || data.page
          this.dataList = pageData && pageData.list ? pageData.list : pageData
          if(pageData && pageData.currPage) {
            this.pageIndex = pageData.currPage
            this.pageSize = pageData.pageSize
            this.totalPage = pageData.totalCount
          } else {
            this.totalPage = this.dataList ? this.dataList.length : 0
          }
        } else {
          this.$message.error(data.msg || '获取数据失败')
        }
      }).catch(error => {
        console.error('获取货币列表失败:', error)
        this.$message.error('获取数据失败: ' + (error.message || '网络错误'))
      }).finally(() => {
        this.dataListLoading = false
      })
    },

    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },

    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },

    // 新增
    addModal() {
      this.modalTitle = '新增货币'
      this.isEdit = false
      this.modalDisableFlag = false
      this.modalData = {
        currency: '',
        currencyDesc: '',
        site: this.$store.state.user.site || this.$store.state.user.currentSite || '',  // 设置默认值但不显示在界面上
        active: 'Y',
        baseCurrency: 'N',
        flag: '1'
      }
      this.$nextTick(() => {
        if (this.$refs.modalForm) {
          this.$refs.modalForm.clearValidate()
        }
      })
      this.modalFlag = true
    },

    // 修改
    updateModal(row) {
      this.modalTitle = '修改货币'
      this.isEdit = true
      this.modalDisableFlag = true
      this.modalData = {
        currency: row.currency,
        currencyDesc: row.currencyDesc,
        site: row.site,
        active: row.active,
        baseCurrency: row.baseCurrency
      }
      this.$nextTick(() => {
        if (this.$refs.modalForm) {
          this.$refs.modalForm.clearValidate()
        }
      })
      this.modalFlag = true
    },

    // 保存数据
    saveData() {
      this.$refs.modalForm.validate((valid) => {
        if (valid) {
          const saveData = { ...this.modalData }
          let apiCall

          if (this.modalData.flag === '1') {
            apiCall = addCurrency(saveData)
          } else {
            apiCall = updateCurrency(saveData)
          }

          apiCall.then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500
              })
              // 立即关闭弹窗并刷新数据，不依赖 onclose 回调
              this.modalFlag = false
              this.getDataList()
            } else {
              this.$message.error(data.msg || '操作失败')
            }
          }).catch(error => {
            console.error('保存货币失败:', error)
            this.$message.error('保存失败: ' + (error.message || '网络错误'))
          })
        } else {
          return false
        }
      })
    },

    // 删除
    deleteHandle(row) {
      this.$confirm(`确定删除此货币吗？货币代码：${row.currency}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          currency: row.currency,
          site: row.site
        }

        deleteCurrency(params).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '删除成功',
              type: 'success',
              duration: 1500
            })
            // 立即刷新数据，不依赖 onclose 回调
            this.getDataList()
          } else {
            this.$message.error(data.msg || '删除失败')
          }
        }).catch(error => {
          console.error('删除货币失败:', error)
          this.$message.error('删除失败: ' + (error.message || '网络错误'))
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.mod-config {
  padding: 20px;
}
</style>
