<template>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-form :inline="true">
        <el-form-item label="供应商名称" style="margin-bottom: 5px;" prop="fname">
          <el-input v-model="query.tradePartnerName" placeholder="请输入供应商名称" clearable></el-input>
        </el-form-item>
      </el-form>
    </el-card>
    <ButtonBar area="top" @search="handleSearch" ></ButtonBar>
    <el-card :body-style="cardBodyStyle">
      <el-table :data="tableData" border highlight-current-row @selection-change="handleSelectionChange">
        <el-table-column type="selection" fixed></el-table-column>
        <el-table-column type="index" label="序号" align="center" width="100">
          <template #default="scope">
            <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="true" prop="tradePartnerCode" label="供应商代码" width="400" header-align="center"
                         align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="tradePartnerName" label="供应商名称" width="400" header-align="center"
                         align="center"
                         show-overflow-tooltip>
        </el-table-column>


<!--        <el-table-column label="操作" header-align="center" align="center" width="300px">-->
<!--          <template #default="scope">-->
<!--            <el-button plain type="warning" @click="handleEdit(scope.row)">编辑</el-button>-->
<!--            <el-button plain type="danger" @click="handleDelete(scope.row)">删除</el-button>-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>
    </el-card>
    <el-card :body-style="cardBodyStyle">
      <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes" :total="totalRows"
                     background="background" layout="total, sizes, prev, pager, next, jumper"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>

    <el-dialog :close-on-click-modal="false" draggable :title="title" v-model="dialogVisible" width="1200px" top="5vh"
               @open="openDialog">
      <el-form :model="form" label-width="auto" label-position="right" inline ref="ruleFormRef" :rules="rules">
        <el-form-item label="供应商编号" prop="tradePartnerCode">
          <el-input v-model="form.tradePartnerCode" clearable style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="供应商名称" prop="tradePartnerName">
          <el-input v-model="form.tradePartnerName" clearable style="width: 200px"></el-input>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleSave(ruleFormRef)">保存</el-button>
          <el-button type="danger" @click="handleCancelSave">取消</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup>
import ButtonBar from '@/components/ButtonBar.vue'

import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance
} from 'vue'

const {
  proxy
} = getCurrentInstance()

import tools from '@/tools'
import {ElMessage, ElMessageBox} from 'element-plus';

const cardBodyStyle = ref(tools.style.card)
const inputStyle = ref(tools.style.input)

onMounted(() => {

  handleSearch()
})


/**
 *   查询
 */




const query = ref({
  tradePartnerName: ''
})
const tableData = ref([])
const handleSearch = () => {
  currentPage.value = 1
  getTableData()
}


const getTableData = () => {
  var url = 'syi/Supplier/query'
  var param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(query.value)
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      tableData.value = response.data.data.records
      totalRows.value = response.data.data.total
      console.log(tableData.value,"tableData")
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
/**
 *   查询
 */

/**
 * 分页
 */
const currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([5, 10, 20, 30, 40])
const pageSize = ref(5)
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}
/**
 * 分页
 */


/**
 * 新增
 */
const dialogVisible = ref(false)
const form = ref({
  id: '',
  tradePartnerName: '',
  tradePartnerCode: ''
})
const ruleFormRef = ref()
const rules = reactive({
  tradePartnerName: [{
    required: true,
    message: '请输入供应商名称',
    trigger: 'change' | 'blur'
  }],
  tradePartnerCode: [{
    required: true,
    message: '请输入供应商编码',
    trigger: 'change' | 'blur'
  }]
})
const title = ref('')
const handleAdd = () => {
  title.value= '新增'
  form.value = {
    tradePartnerName: '',
    tradePartnerCode: ''
  }
  dialogVisible.value = true
}
/**
 * 新增
 */


/**
 * 保存、修改、删除
 */

const openDialog = () => {
}

const handleSave = (ruleFormRef) => {
  // 检查新增情况下的编码重复
  if (!form.value.id) {
    const isDuplicate = tableData.value.some((item) => {
      if (item.tradePartnerCode === form.value.tradePartnerCode) {
        ElMessage.error('编码已存在');
        return true; // 发现重复，中断循环并返回 true
      }
      return false;
    });
    if (isDuplicate) return; // 如果重复，直接退出函数
  }

  // 检查编辑情况下的编码重复
  if (form.value.id) {
    const isDuplicate = tableData.value.some((item) => {
      if (item.tradePartnerCode === form.value.tradePartnerCode && item.id !== form.value.id) {
        ElMessage.error('编码已存在');
        return true; // 发现重复，中断循环并返回 true
      }
      return false;
    });
    if (isDuplicate) return; // 如果重复，直接退出函数
  }

  ruleFormRef.validate((valid, fields) => {
    if (valid) {
      var userName = localStorage.getItem('userDesc')
      var url = 'syi/Supplier/save'
      let dept = localStorage.getItem('dept')
      dept = JSON.parse(dept)
      let deptCode = dept[0].deptCode
      var param = {
        json: JSON.stringify(form.value),
        userName,
        deptCode
      }
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
          form.value = response.data.data
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          getTableData()
          dialogVisible.value = false
        } else {
          // ElMessage.error('操作失败！' + response.data.msg)
          ElMessage({
            message: '操作失败' + response.data.msg,
            type: 'error'
          })
        }
      })

    } else {
      console.log('error submit!', fields)
    }
  })
}

const handleCancelSave = () => {
  dialogVisible.value = false
}
const handleEdit = (row) => {
  title.value= '编辑'
  dialogVisible.value = true
  form.value = JSON.parse(JSON.stringify(row))
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确定删除本条记录?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  )
      .then(() => {
        var userName = localStorage.getItem('userDesc')
        var url = 'syi/Supplier/remove'
        var param = {
          id: row.id,
          userName
        }
        proxy.$axios.post(url, param).then(response => {
          if (response.data.code == 0) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
            getTableData()
          } else {
            ElMessage({
              type: 'error',
              message: '删除失败' + response.data.msg
            });
          }
        });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
        })
      })
}

/**
 * 保存、修改、删除
 */

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}


</script>

<style></style>