<template>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-form :inline="true">
        <el-row>
          <el-col :span="5">
            <el-form-item label="物料名称" style="margin-bottom: 5px;" prop="name">
              <el-input v-model="query.name" placeholder="请输入名称" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <ButtonBar area="top" @search="handleSearch" @add="handleAdd"></ButtonBar>
    <el-card :body-style="cardBodyStyle">
      <el-table :data="tableData" border row-key="id" highlight-current-row @selection-change="handleSelectionChange" >
        <el-table-column type="selection" fixed></el-table-column>
        <el-table-column type="" label="ID" prop="itemCd" align="center" width="360"></el-table-column>
        <el-table-column v-if="true" prop="itemNm" label="名称" width="600" header-align="left" align="left"
          show-overflow-tooltip></el-table-column>
        <!-- <el-table-column v-if="true" prop="remark" label="数据类型" width="290px" header-align="center" align="center"
          show-overflow-tooltip></el-table-column> -->
        <el-table-column label="操作" header-align="center" align="center" width="210px">
          <template #default="scope">
            <el-button plain type="primary" @click="handleEdit(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="新增" 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="erpbm">
          <el-autocomplete v-model="form.erpbm" :fetch-suggestions="querySearchErpbm" placeholder="请输入物料编码" clearable
            style="width: 300px" @select="handleBlur"></el-autocomplete>
        </el-form-item>
        <el-form-item label="物料名称">
          <el-autocomplete v-model="form.name" :fetch-suggestions="querySearChName" placeholder="请输入物料名称" clearable
            style="width: 300px" @select="handleBlur"></el-autocomplete>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remarks" clearable style="width: 300px; height: 100px;"></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 SearchBox from '@/components/SearchBox.vue'
import { getCurrentInstance, onActivated, onMounted, reactive, ref } from 'vue'
import tools from '@/tools'
import Attachment from '@/components/Attachment.vue'

const searchBarRef = ref(null)
const {
  proxy
} = getCurrentInstance()
const PopupUserRef = ref(null)
const showPop = () => {
  PopupUserRef.value.open()
}
const reset = () => {
  Object.keys(query.value).map(key => {
    query.value[key] = ''
  })
}

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

onMounted(() => {

  handleSearch();

})


/**
 *   查询
 */

const query = ref({
  name: '',
})

const form = ref({
  name: '',// 物料名称
  // 有无规则
  remark: '', // 数据类型
  sortindex: '', // 排序
  erpbm: '', // 物料编码
  // 取样方式
  // 是否启用
  // 是否外粉外矿
  // 成品间隔
  remarks: '' // 备注
});
/*method方法调用后端接口查询子类的值*/

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


/**
 *   查询
 */
const getTableData = () => {
  var url = 'syi/wuliao/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)
      console.log(tableData.value)
      totalRows.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
};
/*绑定监听*/

// 定义一个方法
const handleBlur = (item) => {
  console.log(item.name)
  // 假数据
  //传参
};

// 定义一个方法来获取建议
const querySearchErpbm = (queryString, cb) => {
  // 假设你的接口返回的数据格式如下
  const response = [
    { id: 1, name: '物料1', remark: '检测项目', sortindex: '1', erpbm: '001' },
    { id: 2, name: '物料2', remark: '检测项目', sortindex: '2', erpbm: '001' },
  ];

  // 模拟接口响应
  cb(response.map(item => ({
    value: item.erpbm
  })));
};

const querySearChName = (queryString, cb) => {
  // 假设你的接口返回的数据格式如下
  const response = [
    { id: 1, name: '物料1', remark: '检测项目', sortindex: '1', erpbm: '001' },
    { id: 2, name: '物料2', remark: '检测项目', sortindex: '2', erpbm: '001' },
  ];

  // 模拟接口响应
  cb(response.map(item => ({
    value: item.name
  })));
};

// const querySearchStackCd = (queryString, cb) => {
// // 假设你的接口返回的数据格式如下
// const response = [
// { id: 1, name: '物料1', remark: '检测项目',sortindex:'1',erpbm:'001' },
// { id: 2, name: '物料2', remark: '检测项目',sortindex:'2',erpbm:'001' },
// ];

// // 模拟接口响应
// cb(response.map(item => ({
//     value: item.stackCd
// })));
// };

/**
 * 分页
 */
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 ruleFormRef = ref()
const rules = reactive({

})

const handleAdd = () => {
  form.value = {
    id: '',//id
    name: '',// 物料名称
    // 有无规则
    remark: '', // 数据类型
    sortindex: '', // 排序
    erpbm: '', // 物料编码
    // 取样方式
    // 是否启用
    // 是否外粉外矿
    // 成品间隔
    remarks: '' // 备注
  }
  dialogVisible.value = true
}
/**
 * 新增
 */


/**
 * 保存、修改、删除
 */
const refUpload = ref()

const openDialog = () => {

}

const handleSave = (ruleFormRef) => {
  ruleFormRef.validate((valid, fields) => {
    if (valid) {
      // 假数据
      const fakeData = {
        code: 0,
        data: {

        },
        msg: '保存成功'
      };

      // 模拟接口响应
      if (fakeData.code == 0) {
        form.value = fakeData.data;
        ElMessage({
          message: '保存成功',
          type: 'success',
        });
        getTableData();
        dialogVisible.value = false;
      } else {
        ElMessage({
          message: '操作失败' + fakeData.msg,
          type: 'error'
        });
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};



const handleCancelSave = () => {
  dialogVisible.value = false
}


const handleEdit = (row) => {

  // dialogVisible.value = true
  // form.value = row

  proxy.$router.push({
    path: '/syi/planDetail',
    query: {
      param: JSON.stringify(row)
    }
  })
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定删除本条记录?',
    '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }
  )
    .then(() => {
      // 假数据
      const fakeData = {
        code: 0,
        msg: '删除成功'
      };

      // 模拟接口响应
      if (fakeData.code == 0) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        });
        getTableData();
      } else {
        ElMessage({
          type: 'error',
          message: '删除失败' + fakeData.msg,
        });
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      });
    });
};

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

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

const handleRemoveBatch = () => {
  console.log('handleRemoveBatch')

  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据!'
    })
    return
  }

  ElMessageBox.confirm('此操作将删除该数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    var ids = []
    multipleSelection.value.forEach((item, index) => {
      ids.push(item.id)
    })
    /* var url = 'cot/SignRequest/removeBatch'*/
    var param = {
      ids: JSON.stringify(ids)
    }
    proxy.$axios.post(url, param).then(response => {
      if (response.data.code == '0') {
        ElMessage({
          type: 'success',
          message: '操作成功!',
        });
        getTableData()
        dialogVisible.value = false
      } else {
        ElMessage({
          type: 'error',
          message: '操作失败!' + response.data.msg
        });
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

const handleEditBatch = () => {
  console.log('handleEditBatch')
  if (multipleSelection.value.length != 1) {
    ElMessage({
      type: 'warning',
      message: '请选择一条数据编辑!'
    })
    return
  }
  handleEdit(multipleSelection.value[0])
}

const handleUpload = () => {
  console.log('handleUpload')
}

const handleDownload = () => {
  console.log('handleDownload')
}

const handleImport = () => {
  console.log('handleImport')
}

const handleExport = () => {


  var params = {
    name: '测试',
    age: 12
  }
  location.href = import.meta.env.VITE_APP_BASE_API + '/exp/Imexport/exportExcel?params' + encodeURIComponent(JSON.stringify(params))
}

// 处理复选框选中
const handleChange = (form) => {
  console.log(form)
}
</script>

<style></style>
