<template>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-form :inline="true">
        <el-row :span="24">

          <el-col :span="5">
            <el-form-item label="物料名称" style="margin-bottom: 5px;width: 220px;" prop="name">
              <el-select v-model="query.leibmc" placeholder="" clearable>
                <el-option v-for="item in typeList" :key="item.itemCd" :label="item.itemNm"
                           :value="item.itemNm"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card :body-style="cardBodyStyle">
      <el-button type="primary" plain @click="handleSearch">查询</el-button>
      <el-button type="success" plain @click="handleAdd">新增</el-button>
    </el-card>
    <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 prop="index" label="序号" align="center" width="200">
          <template #default="scope">
            <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="leibmc" label="名称" width="250px" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="bcqx" label="保存期限(月)" width="250px" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" header-align="center" align="center" width="300px" fixed="right">
          <template #default="{ row }">
            <el-button plain type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button plain type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSize" :total="totalRows"
                     background="background" layout="total, sizes, prev, pager, next, jumper"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>
  </div>

  <!--新增编辑界面-->
  <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="120px" label-position="right" inline ref="ruleFormRef" :rules="rules">
      <el-form-item label="物料名称" prop="leibmc">
        <el-select v-model="form.leibmc" placeholder="请选择物料名称" clearable style="width: 200px">
          <el-option v-for="item in typeList" :key="item.itemCd" :label="item.itemNm"
                     :value="item.itemNm"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="保存期限(月)" prop="bcqx">
        <el-input-number v-model="form.bcqx" placeholder="请输入保存期限" clearable min="0"
                         style="width: 200px"></el-input-number>
      </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>

</template>

<script setup>

import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance,
  watch
} from 'vue'
import style from '@/tools/style'
import {ElMessage, ElMessageBox} from "element-plus";
import Templates from "@/views/system/templates.vue";

onMounted(() => {

  queryType()
  handleSearch()
})

const {proxy} = getCurrentInstance()
const dialogVisible = ref(false)
const dialogVisibleChe = ref(false)
const dialogVisibleGZ = ref(false)
const ruleFormRef = ref()
const rules = reactive({})
const cardBodyStyle = ref(style.card)
const searchBarRef = ref(null)
const title = ref('')

//查询表单
const query = ref({
  leibmc: ''
})

let dept = localStorage.getItem('dept')
dept = JSON.parse(dept)
let deptCode = dept[0].deptCode

var userName = localStorage.getItem('userDesc')

// 查询委托类型
const smpTypeList = ref([])
const queryWTLXType = () => {
  var url = 'sci/Weituogl/query_YLType'
  var param = {}
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      smpTypeList.value = response.data.data
      // console.log(smpTypeList.value)
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}


const getLeibieid = () => {
  typeList.value.forEach(x => {
    if (x.itemNm == form.value.leibmc) {
      console.log(x)
      form.value.leibieid = x.itemCd
    }
  })

}

// 上方数据
const tableData = ref([])
const activeNameTop = ref('master')
const activeNameBottom = ref('first')
const totalRows = ref(0)

// 使用 ref 创建 form 数据
const form = ref({
  id: '',
  leibmc: '',
  leibieid: '',
  bcqx: '',
});

// 取消
const handleCancelSave = () => {

  dialogVisible.value = false
  dialogVisibleChe.value = false
  dialogVisibleGZ.value = false
}
// 保存
const handleSave = (ruleFormRef) => {
  getLeibieid()

  console.log(form.value, "11")
  ruleFormRef.validate((valid, fields) => {
    if (valid) {
      var url = 'syi/YPLX/save'
      var param = {
        json: JSON.stringify(form.value),
        userName: userName,
        deptCode: 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
          edit_form.value = {}
        } else {
          ElMessage({
            message: '操作失败' + response.data.msg,
            type: 'error'
          })
        }
      })

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


const edit_form = ref({})
// 编辑
const handleEdit = async (row) => {
  rows.value = row;
  await Data(); // 等待 Data 请求完成

  if (data.value.length > 0) {
    ElMessage.warning('该类型下存在数据,不能进行编辑！');
    return; // 阻止继续执行
  }
  title.value = '编辑'
  dialogVisible.value = true
  form.value = JSON.parse(JSON.stringify(row))

}

const openDialog = () => {
}

const data = ref()
const rows =ref()
const Data = async () => {
  var url = 'sci/LYGL/queryLYGL';
  var param = {
    params: JSON.stringify(rows.value),
  };
  await proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      data.value = response.data.data;
    } else {
      ElMessage.error('操作失败！' + response.data.msg);
    }
  });
};

const handleDelete = async (row) => {
  rows.value = row;
  await Data(); // 等待 Data 请求完成

  if (data.value.length > 0) {
    ElMessage.warning('该类型下存在数据，不能进行删除！');
    return; // 阻止继续执行
  }

  ElMessageBox.confirm(
      '确定删除本条记录?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  )
      .then(() => {
        var url = 'syi/YPLX/remove';
        var param = {
          id: row.id,
          userName: userName,
          deptCode: deptCode
        };
        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
}

//新增
const handleAdd = () => {
  title.value = '新增'
  form.value = {
    id: '',
    name: '',
    leibieid: '',
    bcqx: '',

  }
  console.log(form.value)

  dialogVisible.value = true
}


// 查询
const handleSearch = () => {
  currentPage.value = 1
  getTableData()

}


// 查询产品类型
const typeList = ref([])
const queryType = () => {
  var url = 'syi/wuliao/queryType'
  var param = {}
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      typeList.value = response.data.data
      console.log(response.data.data)
      console.log(typeList.value)
      totalRows.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
/**
 * 分页
 */
const currentPage = ref(1)
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 getTableData = () => {

  var url = 'syi/YPLX/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
      console.log(response.data.data.records[0])
      console.log(tableData.value)
      totalRows.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}


</script>

<style scoped></style>
