<template>
  <div class="h-full flex flex-col gap-y-3">
    <n-page-header @back="$router.back">
      <template #title> 设备管理 </template>
    </n-page-header>
    <n-space justify="space-between">
      <div style="display: flex;align-items: center;">
        <n-input style="width: 300px" v-model:value="queryData.T_sn" @clear="handleClear" clearable />
        <n-button type="primary" style="margin-left: 10px;" @click="getDataList"> 搜索 </n-button>
        <div style="padding-left: 20px;font-size: 18px;">
           数量 ：{{total}}
        </div>
      </div>
      <n-button type="primary" @click="showAddModal">批量导入</n-button>
    </n-space>
    <n-data-table remote :columns="columns" :data="data" :bordered="false" flex-height class="flex-1" />
  </div>
  <n-modal :show-icon="false" v-model:show="modal.showModal" preset="dialog" style="width: 800px;" :title="modal.title">
    <n-button type="primary" @click="showAddModalobj" style="margin-bottom: 10px" v-if="modal.title!='修改编号'">选择添加</n-button>
    <n-form :model="formValue" label-width="auto" show-require-mark>
      <template v-if="modal.title === '批量导入'">
        <!-- <n-form-item label="布局编号" path="T_snid">
          <n-input v-model:value="formValue.T_snid" type="textarea" :autosize="{
            minRows: 3,
            maxRows: 5,
          }" placeholder="【方式一：001,002,003】【方式二：001~002,005】" />
         
        </n-form-item> -->
        <n-form-item label="布局编号" path="T_snid">
          <n-table :bordered="false" :single-line="false">
            <thead>
              <tr>
                <th>SN</th>
                <th>布局编号</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item in checkedTable">
                <td>{{item.T_sn}}</td>
                <td><n-input v-model:value="item.T_id" placeholder="请输入编号"/></td>
              </tr>
            </tbody>
          </n-table>
        </n-form-item>
        
      </template>

      <template v-else>
        <n-form-item label="编号" path="T_id">
          <n-input v-model:value="formValue.T_id" />
        </n-form-item>
      </template>

      <n-form-item label="备注（默认：产品存放区域）" path="T_remark">
        <n-radio-group v-model:value="formValue.T_remark" style="width: 100%;">
          <div>
            <n-radio value="产品存放区域">
              产品存放区域
            </n-radio>
          </div>
          <div>
            <n-radio value="车厢外环境">
              车厢外环境
            </n-radio>
          </div>
          <div>
            <n-radio value="药品存放区域">
              药品存放区域
            </n-radio>
          </div>
          <div>
            <n-radio :value="otherVal">
              其他
            </n-radio>
            <n-input v-if="!['产品存放区域', '车厢外环境', '药品存放区域'].includes(formValue.T_remark)" v-model:value="otherVal"
              type="textarea" />
          </div>
        </n-radio-group>
      </n-form-item>
      <div style="display: flex; justify-content: flex-end">
          <n-button @click="modal.showModal = false" style="margin-right: 20px;">
            取消
          </n-button>
          <n-button type="primary" @click="submitCallback">
            提交
          </n-button>
        </div>
    </n-form>
    <n-modal :show-icon="false" v-model:show="modal.showModalobj" style="width: 900px;" preset="dialog" title="选择添加">
      <div style="max-height: 700px;display: flex;flex-direction: column;overflow-y: hidden;">
        <n-form inline label-placement="left" :model="formValues">
          <!-- <n-form-item label="布局编号">
            <n-input v-model:value="formValues.T_layout_no" placeholder="输入布局编号" />
          </n-form-item> -->
          <n-form-item label="SN">
            <n-input v-model:value="formValues.T_sn" placeholder="输入SN" />
          </n-form-item>
          <n-form-item>
            <n-button type="primary" attr-type="button" @click="searchFun">
              查询
            </n-button>
          </n-form-item>
          <n-form-item>
            <!-- <n-button type="primary" :disabled="checkedRowKeysRef.length==0" attr-type="button" @click="submitis">
              立即导入
            </n-button> -->
          </n-form-item>
        </n-form>
        <div style="flex: 1;overflow-y: auto;">
          <n-data-table :columns="createColumns()" :data="checje.chkData" :remote="true" :max-height="480" :pagination="{
            pageSize: formValues.page_z, 
            page:formValues.page,
            pageCount:pageData.pageCount,
            'show-quick-jumper':true,
            'show-size-picker':true,
            'display-order':[ 'size-picker', 'pages','quick-jumper'],
            'page-sizes':[10, 20, 30, 40],
            
            prefix() {
              return `共${pageData.pageNum}条`
            }}"
            @update:page="prevFun"
            :on-update:page-size="pagesizeFun"
            v-model:default-checked-row-keys="checkedTableData"
            :row-key="rowKey" @update:checked-row-keys="handleCheck">
          </n-data-table>
        </div>
      </div>

    </n-modal>
  </n-modal>
</template>

<script setup>
import { h, reactive, ref, watch } from 'vue';
import { NButton, NSpace, NPopconfirm, NInput ,useNotification } from 'naive-ui';
import {
  getDeviceClassListList,
  addDeviceClassList,
  editDeviceClassList,
  deleteDeviceClassList,
  getCertificateList
} from '@/api';

const task = window.sessionStorage.getItem('task')
  ? JSON.parse(window.sessionStorage.getItem('task'))
  : {};

const checje = reactive({
  Selecteds: null,
  chkData: []
})
const checkedRowKeysRef = ref([]);
const checkedTable = ref([])
const checkedTableData = ref([])

const createColumns = () => [
  {
    type: "selection",
  },
  // {
  //   title: "布局编号",
  //   key: "T_layout_no",
  //   // sortOrder: false,
  //   // sorter (rowA, rowB) {
  //   //   return rowA.age - rowB.age
  //   // }
  // },
  {
    title: "SN",
    key: "T_sn"
  }
];





const rowKey = (row) => row.T_sn
const handleCheck = (rowKeys) => {//点击选项框勾选存值
  checkedRowKeysRef.value = rowKeys;

  const arr = [...checkedRowKeysRef.value]
  const arr1 = []
  arr.forEach(item=>{
    arr1.push({T_sn:item,T_id:''})
  })
  checkedTable.value = arr1;
}



const submitis = ()=>{
  console.log(checkedRowKeysRef.value)
  return
  if(checkedRowKeysRef.value.length!=0){   
    addDeviceClassList({
      T_class: queryData.T_class,
      T_layout_no_list:checkedRowKeysRef.value.join(',')
    }).then(res=>{
      if(res.data.Code==200){
        getDataList();
        message.success('导入成功')
      }
    });
    
  }
}
const message = useMessage();
//上下页分页
const prevFun = (e) => {
  formValues.page = e
  GetficateListApi()

}


//每页显示条数
const pagesizeFun = (e) => {
  formValues.page_z = e
  GetficateListApi()

}
const pageData = reactive({
  pageCount: 0,
  pageNum: 0
})
const formValues = reactive({
  T_sn: '',//SN
  T_task_id:JSON.parse(sessionStorage.getItem('task')).T_task_id,
  // T_layout_no: '',//布局编号
  // T_layout_no_sort: '',//排序 0默认 1升2降
  page: 1,
  page_z: 10,
});

// 选择导入
const showAddModalobj = () => {
  // formValues.page = 1
  checkedTableData.value = []
  modal.showModalobj = true;
  checkedTable.value.forEach(item=>{
    checkedTableData.value.push(item.T_sn)
  })
};
//搜索
const searchFun = ()=>{
  formValues.page = 1
  GetficateListApi()
}
//列表Api
const GetficateListApi = () => {
  
  getCertificateList(formValues).then(res => {
    let { data: resIt } = res
    if (resIt.Code == 200) {
      resIt.Data.List!=null?checje.chkData = resIt.Data.List:checje.chkData = []
      pageData.pageCount = resIt.Data.Page_size
      pageData.pageNum = resIt.Data.Num
    }
  })
}

// 查询参数
const queryData = reactive({
  T_sn: '',
  T_class: task.T_class,
});
const otherVal = ref('')
watch(otherVal, (newval) => {
  console.log('将变化', newval)
  formValue.T_remark = newval
})
// 需要展示的列
const columns = [
  {
    title: '编号',
    key: 'T_id',
    // defaultSortOrder: 'descend',
  },
  {
    title: 'SN',
    key: 'T_sn',
  },
  {
    title: '证书有效期',
    key: 'T_failure_time',
  },
  {
    title: '备注',
    key: 'T_remark',
  },
  {
    title: '操作',
    key: 'actions',
    render(row) {
      return h(
        NSpace,
        {},
        {
          default: () =>
            ['修改', '删除'].map((item) => {
              if (item === '修改') {
                return h(
                  NButton,
                  {
                    type: 'primary',
                    size: 'small',
                    onClick: () => showEditModal(row),
                  },
                  { default: () => item }
                );
              } else {
                return h(
                  NPopconfirm,
                  {
                    onPositiveClick: () => deleteDeviceClass(row),
                  },
                  {
                    default: () => '是否确认删除？',
                    trigger: () =>
                      h(
                        NButton,
                        {
                          type: 'error',
                          size: 'small',
                        },
                        { default: () => item }
                      ),
                  }
                );
              }
            }),
        }
      );
    },
  },
];

// 设备分类-设备列表
const data = ref([]);

// 模态框数据源
const modal = reactive({
  title: '',
  showModal: false,
  showModalobj: false,
});

// 获取表项中收集到的值的对象
const formValue = reactive({
  T_snid: '',
  T_id: 0,
  T_remark: '',
});

// 输入框点击清空按钮时触发
const handleClear = () => {
  queryData.T_sn = '';
  getDataList();
};

const notification = useNotification();
//
const submitCallback = async() => {
  if (modal.title === '批量导入') {
    if(checkedTable.value.length==0){
      message.error('缺少布局编号，请选择添加')
      return
    }else{
      const b = checkedTable.value.every(item => item.T_id!='')
      if(!b){
        message.error('请填写编号');
      }else{//可以提交
        console.log('提交',checkedTable.value)
        const arr = []
        checkedTable.value.forEach(item=>{
          arr.push(item.T_sn + ',' + item.T_id)
        })
        const code = await addDeviceClass(arr.join('|'),formValue.value);
        console.log('返回',code)
        if(code.Code==200){
          message.success(code.Msg);
          modal.showModal = false 
        }
      }
      
    }
    
  } else {
    editDeviceClass();
  }
};

// 显示编辑
const showEditModal = (row) => {
  console.log('显示编辑', row)
  if (!['产品存放区域', '车厢外环境', '药品存放区域'].includes(row.T_remark)) {
    otherVal.value = row.T_remark;
  }
  modal.title = '修改编号';
  modal.showModal = true;
  formValue.Id = row.Id;
  formValue.T_id = `${row.T_id}`;
  formValue.T_remark = row.T_remark;
};

// 显示批量导入
const showAddModal = () => {
  modal.title = '批量导入';
  modal.showModal = true;
  formValue.T_snid = '';
  formValue.T_remark = '产品存放区域';
  formValues.page = 1
  GetficateListApi()
};




// 删除
const deleteDeviceClass = async (row) => {
  try {
    const { data: res } = await deleteDeviceClassList({
      Id: row.Id,
    });
    if (res.Code === 200) {
      message.success(res.Msg);
      getDataList();
    }
  } catch (e) {
    console.log(e);
  }
};

// 编辑编号
const editDeviceClass = async () => {
  try {
    const { data: res } = await editDeviceClassList({
      Id: formValue.Id,
      T_id: formValue.T_id,
      T_remark: formValue.T_remark,
    });
    if (res.Code === 200) {
      message.success(res.Msg);
      modal.showModal = false 
      getDataList();
    }
  } catch (e) {
    console.log(e);
  }
};

// 批量导入
const addDeviceClass = async (T_sn_id_list, T_id) => {
  try {
    const { data: res } = await addDeviceClassList({
      T_class: queryData.T_class,
      T_sn_id_list,
      T_id,
      T_remark: formValue.T_remark,
    });
    return res;
  } catch (e) {
    console.log(e);
  } finally {
    getDataList();
  }
};
const total = ref(0)
// 获取列表
const getDataList = async () => {
  try {
    const { data: res } = await getDeviceClassListList(queryData);
    data.value = res.Data.List || [];
    total.value = res.Data.Num
    console.log('数量列表2',data.value)
  } catch (e) {
    console.log(e);
  }
};

getDataList();
</script>

<style scoped>
table tbody {
    display:block;
    max-height:300px;
    overflow-y:scroll;
    -webkit-overflow-scrolling: touch;
}

table tbody::-webkit-scrollbar {
    display: none; 
}

table thead, tbody tr {
    display:table;
    width:100%;
    table-layout:fixed;
}

table thead {
    /* width: calc( 100% - 1em ) */
    width: 100%
}
table thead th{ background:#ccc;}
</style>
