<template>
  <div class="mod-config">
    <el-form :inline="true" label-position="top" :model="searchData">
      <el-form-item label="付款条款编码">
        <el-input v-model="searchData.paymentTermId" clearable style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item label="付款条款描述">
        <el-input v-model="searchData.paymentTerm" clearable style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item label="启用">
        <el-select v-model="searchData.active" clearable style="width: 120px">
          <el-option label="Y" value="Y"></el-option>
          <el-option label="N" value="N"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label=" ">
        <el-button v-if="authSearch" type="primary" @click="getDataList()">查询</el-button>
        <el-button v-if="authSave" type="primary" @click="addModal()">新增</el-button>
<!--        <el-button @click="exportExcel()" type="primary" style="margin-left: 2px">导出</el-button>-->
      </el-form-item>
    </el-form>

    <el-table
      :height="height"
      :data="dataList"
      border
      v-loading="dataListLoading"
      style="width: 100%;">
      <el-table-column
        v-for="(item,index) in columnList" :key="index"
        :sortable="item.columnSortable"
        :prop="item.columnProp"
        :header-align="item.headerAlign"
        :show-overflow-tooltip="item.showOverflowTooltip"
        :align="item.align"
        :fixed="item.fixed == '' ? false : item.fixed"
        :min-width="item.columnWidth"
        :label="item.columnLabel">
        <template slot-scope="scope">
    <span v-if="!item.columnHidden">
      <span v-if="columnsProp.includes(item.columnProp)">
        {{ scope.row[`${item.columnProp}Desc`] }}
      </span>
      <span v-else>
        {{ item.columnProp === 'days' ? Math.floor(scope.row[item.columnProp]) : scope.row[item.columnProp] }}
      </span>
    </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" v-if="authUpdate" @click="updateModal(scope.row)">编辑 |</el-link>
          <el-link style="cursor: pointer" v-if="authDelete" @click="deletePaymentTerm(scope.row)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>

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

    <el-dialog title="付款条款" :close-on-click-modal="false" v-drag :visible.sync="modalFlag" width="560px">
      <el-form label-position="top" :model="modalData" :rules="rules" style="margin-left: 7px; margin-right: 7px;" ref="modalForm">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="付款条款编码" prop="paymentTermId">
              <el-input v-model="modalData.paymentTermId" :disabled="modalDisableFlag"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用" prop="active">
              <el-select v-model="modalData.active" style="width: 100%">
                <el-option label="Y" value="Y"></el-option>
                <el-option label="N" value="N"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="天数" prop="days">
              <el-input v-model.number="modalData.days"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-input v-model="modalData.type"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="付款条款描述" prop="paymentTerm">
              <el-input v-model="modalData.paymentTerm" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </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 {
  getPaymentTermListPaging,
  savePaymentTerm,
  updatePaymentTerm,
  deletePaymentTerm
} from "@/api/baseInformation/srmPaymentTerm.js"
import excel from "@/utils/excel-util.js";

export default {
  data () {
    return {
      columnsProp:['createdBy','updateBy','status'],
      // 导出
      exportName: "付款条款" + this.dayjs().format('YYYYMMDDHHmmss'),
      searchData: {
        site: this.$store.state.user.site,
        paymentTermId: '',
        paymentTerm: '',
        active: '',
        days: '',
        type: '',
        page: 1,
        limit: 10,
      },
      height: 200,
      pageIndex: 1,
      pageSize: 20,
      totalPage: 0,
      dataList: [],
      dataListLoading: false,
      modalFlag: false,
      modalDisableFlag: false,
      modalData: {
        paymentTermId: '',
        paymentTerm: '',
        site: this.$store.state.user.site,
        active: '',
        days: '',
        type: '',
        createBy: this.$store.state.user.name,
        updateBy: this.$store.state.user.name
      },
      // 展示列集
      columnList: [
        {
          userId: this.$store.state.user.name,
          functionId: '9003',
          serialNumber: '9003TablePaymentTermId',
          tableId: '9003Table',
          tableName: "付款条款表",
          columnProp: 'paymentTermId',
          headerAlign: "center",
          align: "left",  // 修改为左对齐顶格显示
          columnLabel: '付款条款编码',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 120
        },
        {
          userId: this.$store.state.user.name,
          functionId: '9003',
          serialNumber: '9003TablePaymentTerm',
          tableId: "9003Table",
          tableName: "付款条款表",
          columnProp: 'paymentTerm',
          headerAlign: "center",
          align: "left",
          columnLabel: '付款条款描述',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 200,
        },
        {
          userId: this.$store.state.user.name,
          functionId: '9003',
          serialNumber: '9003TableDays',
          tableId: "9003Table",
          tableName: "付款条款表",
          columnProp: 'days',
          headerAlign: "center",
          align: "right",
          columnLabel: '天数',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 80,
        },
        {
          userId: this.$store.state.user.name,
          functionId: '9003',
          serialNumber: '9003TableType',
          tableId: "9003Table",
          tableName: "付款条款表",
          columnProp: 'type',
          headerAlign: "center",
          align: "center",
          columnLabel: '类型',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 80,
        },
        {
          userId: this.$store.state.user.name,
          functionId: '9003',
          serialNumber: '9003TableActive',
          tableId: "9003Table",
          tableName: "付款条款表",
          columnProp: 'active',
          headerAlign: "center",
          align: "center",
          columnLabel: '启用',
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 0,
          status: true,
          fixed: '',
          columnWidth: 80,
        }
      ],
      rules: {
        paymentTermId: [
          {
            required: true,
            validator: this.validateField,
            trigger: 'blur'
          }
        ],
        paymentTerm: [
          {
            required: true,
            validator: this.validateField,
            trigger: 'blur'
          }
        ],
        days: [
          {
            validator: this.validateDays,
            trigger: 'blur'
          }
        ]
      },
      authSearch: false,
      authSave: false,
      authUpdate: false,
      authDelete: false,
      menuId: this.$route.meta.menuId || 'srmPaymentTerm',
    }
  },

  mounted () {
    this.$nextTick(() => {
      this.height = window.innerHeight - 180
    })
  },

  created () {
    // 按钮控制
    this.getButtonAuthData()
    // 无论是否有查询权限，都获取数据列表
    this.getDataList()
  },

  methods: {
    validateField(rule, value, callback) {
      if (!value || value.trim() === '') {
        callback(new Error(' '));
      } else {
        callback();
      }
    },

    validateDays(rule, value, callback) {
      if (!value || value.trim() === '') {
        callback(new Error(' '));
        return;
      }
      const numberPattern = /^\d+$/;
      if (!numberPattern.test(value)) {
        callback(new Error('请输入正确的天数'));
      } else {
        callback();
      }
    },
// 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },

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

    async exportExcel() {
      const params = {
        ...this.searchData,
        limit: -1,
        page: 1
      };

      excel.exportTable({
        url: "/srmPaymentTerm/getPaymentTermListPaging",
        columnMapping: this.columnList,
        mergeSetting: [],
        params: params,
        fileName: this.exportName + ".xlsx",
        // 返回包含rows字段的对象，让excel工具能够正确提取数据
        rowFetcher: res => {
          if (res && res.data && res.data.code === 0) {
            return { rows: res.data.data || [] };
          }
          return { rows: [] };
        },
        columnFormatter: [],
        dropColumns: [],
      });
    },

    // 获取数据列表
    getDataList () {
      this.dataListLoading = true;
      // 准备请求参数
      const params = {
        ...this.searchData,
        site: this.$store.state.user.site, // 确保使用当前用户的站点
        page: this.pageIndex,
        limit: this.pageSize
      };

      getPaymentTermListPaging(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;
      })
    },

    addModal () {
      this.modalData = {
        paymentTermId: '',
        paymentTerm: '',
        site: this.$store.state.user.site, // 使用当前用户默认站点
        active: 'Y',
        days: '',
        type: '',
        createBy: this.$store.state.user.name,
        updateBy: this.$store.state.user.name,
        flag: '1'
      }
      this.modalDisableFlag = false
      this.modalFlag = true
      this.$nextTick(() => {
        // 清除表单验证
        if (this.$refs.modalForm) {
          this.$refs.modalForm.clearValidate();
        }
      });
    },

    updateModal (row) {
      this.modalData = {
        paymentTermId: row.paymentTermId,
        paymentTerm: row.paymentTerm,
        site: row.site,
        active: row.active,
        days: row.days != null ? parseInt(row.days, 10) : '',
        type: row.type,
        createBy: row.createBy,
        updateBy: this.$store.state.user.name,
        flag: '2'
      }
      this.modalDisableFlag = true
      this.modalFlag = true
      this.$nextTick(() => {
        // 清除表单验证
        if (this.$refs.modalForm) {
          this.$refs.modalForm.clearValidate();
        }
      });
    },

    // 删除
    deletePaymentTerm (row) {
      this.$confirm(`确定删除此付款条款吗？条款代码：${row.paymentTermId}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const deleteData = {
          paymentTermId: row.paymentTermId,
          site: row.site
        };

        deletePaymentTerm(deleteData).then(({data}) => {
          if (data && data.code === 0) {
            this.getDataList()
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {}
            })
          } else {
            this.$alert(data.msg, '错误', {
              confirmButtonText: '确定'
            })
          }
        }).catch(error => {
          console.error('删除付款条款失败:', error)
          this.$message.error('删除失败: ' + (error.message || '网络错误'))
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    saveData () {
      this.$refs.modalForm.validate(valid => {
        if (!valid) return

        this.modalData.days = parseInt(this.modalData.days, 10)

        const api = this.modalData.flag === '1'
          ? savePaymentTerm
          : updatePaymentTerm

        api(this.modalData).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message.success('操作成功')
            this.modalFlag = false
            this.getDataList()
          } else {
            this.$alert(data.msg || '操作失败', '错误')
          }
        }).catch(err => {
          console.error(err)
          this.$message.error('请求失败')
        })
      })
    },

    //获取按钮的权限数据
    getButtonAuthData () {
      let searchFlag = this.isAuth(this.menuId+":search")
      let saveFlag = this.isAuth(this.menuId+":save")
      let updateFlag = this.isAuth(this.menuId+":update")
      let deleteFlag = this.isAuth(this.menuId+":delete")
      //处理页面的权限数据
      this.authSearch = !searchFlag
      this.authSave = !saveFlag
      this.authUpdate = !updateFlag
      this.authDelete = !deleteFlag
    },
  }
}
</script>
<style scoped lang="scss">
.el-table /deep/ .cell{
  height: auto;
  line-height: 1.5;
}
</style>
