<template>
  <div>
    <!--查询区域-->
    <div class="jeecg-basic-table-form-container">
      <a-form ref="formRef" @keyup.enter.native="searchQuery" :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
          <a-col :lg="6">
            <a-form-item name="paramWlxx">
              <template #label><span title="物料信息">物料信息</span></template>
              <a-input placeholder="请填写物料信息" v-model:value="queryParam.paramWlxx"  allow-clear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-col :lg="6">
                <a-button type="primary" preIcon="ant-design:search-outlined" @click="searchQuery">查询</a-button>
                <a-button type="primary" preIcon="ant-design:reload-outlined" @click="searchReset" style="margin-left: 8px">重置</a-button>
              </a-col>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)"/>
      </template>
      <template v-slot:bodyCell="{ column, record, index, text }">
      </template>
    </BasicTable>
  </div>
</template>

<script lang="ts" name="materialInfo-nuConfigMaterialInfo" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { columns4 } from '../BlWarehouseMaterialInfo.data';
  import { list, batchDelete } from '../BlWarehouseMaterialInfo.api';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import { useUserStore } from '/@/store/modules/user';
import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';

  const { createMessage,createConfirm } = useMessage();
  const formRef = ref();
  const queryParam = reactive<any>({});
  const toggleSearchStatus = ref<boolean>(false);
  const registerModal = ref();
  const userStore = useUserStore();
  const emit = defineEmits(['register', 'ok']);
  
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: 'nu_config_material_info',
      api: list,
      columns: columns4,
      canResize:false,
      useSearchForm: false,
      immediate: false,
      showActionColumn: false,
      showTableSetting: false,
      actionColumn: {
        width: 120,
        fixed: 'right',
      },
      beforeFetch: async (params) => {
        return Object.assign(params, queryParam);
      },
    },
  });
  
  const formData = reactive<Record<string, any>>({
    id: '',
    nuId: '',   
    wlId: '',   
    upperLimit: '',   
    lowerLimit: '',   
  });
  const [registerTable, { reload, collapseAll, updateTableDataRecord, findTableDataRecord, getDataSource }, { rowSelection, selectedRowKeys, selectedRows }] = tableContext;
  const labelCol = reactive({
    xs:24,
    sm:4,
    xl:6,
    xxl:4
  });
  const wrapperCol = reactive({
    xs: 24,
    sm: 20,
  });

  
  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    registerModal.value.disableSubmit = false;
    registerModal.value.edit(record);
  }
   
   
   
  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
   
  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
      },
    ];
  }
   

  /**
   * 查询
   */
  function searchQuery() {
    reload();
  }
  
  /**
   * 重置
   */
  function searchReset() {
    formRef.value.resetFields();
    selectedRowKeys.value = [];
    //刷新数据
    reload();
  }
  
  async function edit(record) {
    console.log("🚀 ~ edit ~ record:", record)
    selectedRowKeys.value = [];
    selectedRows.value = [];
    nextTick(() => {
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });
    // var checkId = "";
    // for(let item of record){
    //   checkId += item.id + ",";
    // }
    // if(checkId.length > 0){
    //   checkId = checkId.substring(0,checkId.length - 1);
    // }
    queryParam.nuId = formData.nuId;
    reload();
  }

  function submitForm() {
    
    var list = selectedRows.value;
    if(list.length == 0){
      createMessage.warning('请选择想要移除的物料！');
      return;
    }
    var ids = "";
    for(let item of list){
      if(parseFloat(item.kcsl) == 0){
        ids += item.id + ",";
      }else{
        createMessage.warning('库存数量大于0的物料不予移除,请重新选择！');
        return;
      }
    }
    if(ids.length == 0){
      createMessage.warning('请选择想要移除的物料,库存数量大于0的物料不予移除！');
      return;
    }
    if(ids.length > 0){
      ids = ids.substring(0,ids.length - 1);
    }
    createConfirm({
      iconType: 'warning',
      title: '确认移除',
      content: '是否移除选中物料',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        defHttp.get({url:'/invoicing/blWarehouseMaterialInfo/deleteBatch',params:{ids}}).then(res=>{
          console.log("🚀 ~ submitForm ~ res:", res)
          emit('ok');
        })
      }
    });
  }
  function handleAllDel() {
    
    createConfirm({
      iconType: 'warning',
      title: '确认移除',
      content: '是否移除全部物料！！！',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        defHttp.get({url:'/invoicing/blWarehouseMaterialInfo/deleteAllWuliao',params:{nuId:formData.nuId}}).then(res=>{
          emit('ok');
        })
      }
    });
    
  }

  defineExpose({
    edit,
    submitForm,
    handleAllDel
  });


</script>

<style lang="less" scoped>
  .jeecg-basic-table-form-container {
    padding: 0;
    .table-page-search-submitButtons {
      display: block;
      margin-bottom: 24px;
      white-space: nowrap;
    }
    .query-group-cust{
      min-width: 100px !important;
    }
    .query-group-split-cust{
      width: 30px;
      display: inline-block;
      text-align: center
    }
    .ant-form-item:not(.ant-form-item-with-help){
      margin-bottom: 16px;
      height: 32px;
    }
    :deep(.ant-picker),:deep(.ant-input-number){
      width: 100%;
    }
  }
</style>
