<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>
      <div style="display: flex;grid-gap: 20px;">
        <n-button type="primary" @click="copylistData">复制</n-button>
        <n-button type="primary" @click="affixlistData">粘贴</n-button>
        <n-button type="primary" @click="batchEditing">批量修改</n-button>
        <n-button type="primary" @click="showAddModal">批量导入</n-button>
      </div>
    </n-space>
    <n-data-table remote :columns="createColumn()"
    v-model:checked-row-keys="checkedRowKeysListRef"
    :row-key="rowKeyTable"
    :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">
    <div style="margin-bottom: 10px;display: flex;gap:10px" v-if="modal.title!='修改编号'&&modal.title != '批量修改'">
      <!-- <n-button type="primary" @click="showAddModalobj" v-if="modal.title!='修改编号'&&modal.title != '批量修改'">选择添加</n-button> -->
      <n-upload :default-upload="false" :max="1" @change="handleChange">
        <n-button type="primary">
          <template #icon>
                      <n-icon><CloudUploadOutline /></n-icon>
                    </template>
          上传文件</n-button>
      </n-upload>
      <n-button @click="downloadFun" type="warning">
        <template #icon>
          <n-icon><CloudDownloadOutline /></n-icon>
        </template>
        模板下载</n-button>
    </div>
    <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">
          <div>
            <n-table :border="true" :single-line="true">
            <thead>
              <tr>
                <th>SN</th>
                <th>布局编号</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item,index in checkedTable">
                <td><n-input v-model:value="item.T_sn" placeholder="请输入SN"/></td>
                <td><n-input v-model:value="item.T_id" placeholder="请输入编号"/></td>
                <td >
                  <n-button @click="delectRow(index)"  type="error">删除行</n-button>
                </td>
              </tr>
            </tbody>
            <n-button @click="addRows" style="margin: 10px;" type="primary">
              <template #icon> <n-icon><Add /></n-icon> </template> 添加一行
            </n-button>
            <n-button v-show="checkedTable.length!=0" @click="checkedTable = []" style="margin: 10px;">
              <template #icon> <n-icon><TrashOutline /></n-icon> </template> 全部清空
            </n-button>
          </n-table>
          </div>
        </n-form-item>
        
      </template>

      <template v-else-if="modal.title != '批量修改'">
        <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 style="display: grid;grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));grid-gap:5px 0;">
            <n-radio :value="item" v-for="item,index in selectData" :key="index">
              {{item}}
            </n-radio>
          </div>
          <div style="padding-top: 20rpx;">
            <n-radio :value="otherVal">
              其他
            </n-radio>
            <n-input v-if="!selectData.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 { Add,CloudUploadOutline,CloudDownloadOutline,TrashOutline } from '@vicons/ionicons5'
import { h, reactive, ref, watch } from 'vue';
import { NButton, NSpace, NPopconfirm, NInput ,useNotification } from 'naive-ui';
import { downloadExcelFun,getDeviceClassDownload } from "@/utils/download";
import { useStore } from 'vuex';
import { read, utils } from 'xlsx';
import {
  getDeviceClassListList,
  addDeviceClassList,
  editDeviceClassList,
  deleteDeviceClassList,
  getCertificateList,
  getDeviceClassCopy,
} from '@/api';



//添加一行
const addRows = async ()=>{
  checkedTable.value.push({
    T_sn:'',  
    T_id:'' 
  })
}
//删除一行
const delectRow = async (row)=>{
  checkedTable.value.splice(row,1)
}
//模板下载
const downloadFun = async ()=>{
  
  const reslut = await getDeviceClassDownload({})
  console.log('下载',reslut)
  downloadExcelFun(reslut)
}


// 组件状态变化的回调
const handleChange = async ({ file }) => {
  const dataBinary = await readFile(file.file);
  const workBook = read(dataBinary, {
    type: 'binary',
    cellDates: true,
  });
  const workSheet = workBook.Sheets[workBook.SheetNames[0]];
  let list = utils.sheet_to_json(workSheet);

  let arr = list.map(obj => ({  
    T_sn: obj.SN,  
    T_id: obj['布局编号'] 
  })); 
  checkedTable.value = [...checkedTable.value,...arr]

};
/* 读取文件 */
const readFile = (file) => {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = (ev) => {
      resolve(ev.target.result);
    };
  });
};



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 selectData = ref([
  '均匀性布点','作业出入口测点','1号作业出入口测点',
  '2号作业出入口测点','1号风机测点','2号风机测点',
  '风机回风口','1号风机回风口','2号风机回风口',
  '照明灯测点','除湿机测点','风幕机测点',
  '外部环境测点','作业口外部环境测点','产品存放区域测点',
  '温控传感器绑定点1','温控传感器绑定点2','温湿度监测绑定点1','温湿度监测绑定点2'
])

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 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
})

let checkedRowKeysListRef = ref([])//列表勾选的选项
const rowKeyTable = (row) => row.Id + '|' +  row.T_id

const store = useStore()
const message = useMessage()
/**
 * 复制
 */
const copylistData = async ()=>{
  let initPomes = {
    T_copy_task_id:task.T_task_id,//复制的T_task_id
    T_paste_task_id:''//粘贴的T_task_id
  }
  store.commit('setcopy',initPomes)  
  message.success('复制成功');
}

/**
 * 粘贴
 */
const affixlistData = async ()=>{
  let initPomes = {...store.state.setcopyData}
  if(initPomes.T_copy_task_id==''){
    message.error('还未复制内容哦');
    return
  }
  initPomes.T_paste_task_id = task.T_task_id
  const reslut = await getDeviceClassCopy(initPomes)
  if(reslut.data.Code==200){
    message.success('粘贴成功');
    getDataList();
  }
  
}

//批量编辑
const batchEditing = async ()=>{
  if (checkedRowKeysListRef.value.length==0) {
    message.error('批量修改至少选择一项');
    return
  }
  modal.title = '批量修改';
  modal.showModal = true;
  formValue.T_remark = '均匀性布点';
}
const createColumn = () => [
  {
    type: "selection",
    options: [
        {
            label: '反选',
            key: 'f2',
            onSelect: (pageData) => {
              let arrMap = [...checkedRowKeysListRef.value]
              let result = pageData.filter(itemA => !arrMap.find(itemB => (itemA.Id + '|' +  itemA.T_id) === itemB));
              const valuesArray = result.map(item => item.Id + '|' +  item.T_id);  
              checkedRowKeysListRef.value = valuesArray
            }
          }
      ],
  },
  {
    title: '布局编号',
    key: 'T_id',
  },
  {
    title: '证书编号',
    key: 'T_Certificate_sn',
  },
  {
    title: '设备编号',
    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,
});
watch(()=>modal.showModal,(newData)=>{
  if(!newData) checkedTable.value = []
})
// 获取表项中收集到的值的对象
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 if(modal.title == '批量修改'){
    let array = [...checkedRowKeysListRef.value]
    for (let i = 0; i < array.length; i++) {
      const { data: res } = await editDeviceClassList({
        Id: array[i].split('|')[0],
        T_id:array[i].split('|')[1],
        T_remark: formValue.T_remark,
      });
      if (i === array.length-1) {
        message.success('批量编辑完成');
        modal.showModal = false 
        getDataList();
      }
    }
  } else {
    editDeviceClass();
  }
};

// 显示编辑
const showEditModal = (row) => {
  console.log('显示编辑', row)
  if (!selectData.value.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
  } 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>
