<template>
  <div>
    <BasicTable :clickToRowSelect="false" @register="registerTable">
      <template #form-formHeader="{ model, field }">
        <div class="form-box">
          <a-row>
            <a-col :span="8">
              <span class="span-label"> 关键字: </span>
              <a-input
                class="custom-input"
                v-model:value="dataCenter.formState.value"
                placeholder="搜索传感器名称，传感器代码"
              />
            </a-col>
            <a-col :span="8">
              <span class="span-label"> 测站: </span>
              <a-select
                class="custom-input sitemore"
                placeholder="监测站点"
                v-model:value="dataCenter.formState.name"
                :options="dataCenter.optionArr"
              />
            </a-col>
            <a-col :span="8">
              <span class="span-label"> 传感器类型: </span>
              <a-select
                class="custom-input sitemore"
                placeholder="监测站点"
                v-model:value="dataCenter.formState.type"
                :options="dataCenter.optionArr1"
              />
            </a-col>
          </a-row>
        </div>
      </template>
      <template #storage="{ record }">
        <!--  @change="(checked:boolean)=>statusChange(checked,record)" -->
        <Switch
          :checked="record.storage == 1"
          checkedChildren="是"
          unCheckedChildren="否"
          @change="(checked:boolean)=>statusChange(checked,record)"
        />
      </template>
      <template #toolbar>
        <Authority value="api:sw:cgqgl:add">
          <a-button type="primary" @click="handleCreate">新增</a-button>
        </Authority>
        <Authority>
          <a-button type="primary" @click="exportDataFn">导出</a-button>
        </Authority>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: '详情',
              auth: 'api:sw:cgqgl:detail',
              icon: 'clarity:info-standard-line',
              onClick: handleViewDetail.bind(null, record),
            },
            {
              label: '编辑',
              auth: 'api:sw:cgqgl:eidt',
              icon: 'clarity:note-edit-line',
              onClick: handleViewEidt.bind(null, record),
            },
            {
              label: '删除',
              auth: 'api:sw:cgqgl:del',
              icon: 'ant-design:delete-outlined',
              popConfirm: {
                title: '是否确认删除',
                confirm: handleViewdel.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <AccountModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
import { defineComponent, ref, watch, onMounted, reactive } from 'vue';
import { useModal } from '/@/components/Modal';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { getAllCom, getDeleteTree, getSensorTable, getProperties } from '/@/api/swHome/index';
import { Switch, Popconfirm } from 'ant-design-vue';
import { exportData } from '/@/utils/fnUtils.ts';
let dataCenter = reactive({
  tableValue: [],
  columns: [],
  accountFormSchema: [],
  optionArr: [],
  optionArr1: [],
  formState: {
    value: '',
    name: '',
    type: '',
  },
});
const [registerTable, { reload, getColumns, getDataSource, setLoading, setColumns, setTableData }] = useTable({
  title: '传感器管理',
  // api: getAllCom,
  columns: [],
  // resizeHeightOffset:40,
  canResize:true,
  showIndexColumn: false,
  clickToRowSelect: false,
  pagination: false,
  loading: false,
  useSearchForm: true,
  showTableSetting: true,
  bordered: true,
  rowKey: 'id',
  tableSetting: {
    redo: false,
    setting: false,
  },
  // 搜索表格
  formConfig: {
    labelWidth: 120,
    // 自定义提交逻辑
    submitFunc: submitFunc,
    // 自定义重置逻辑
    resetFunc: resetFunc,
  },
  actionColumn: {
    width: 200,
    title: '操作',
    dataIndex: 'action',
    slots: { customRender: 'action' },
    fixed: 'right',
  },
  fetchSetting: {
    listField: 'data.value',
  },
});
//弹窗开始
import AccountModal from './components/AccountModal.vue';
const [registerModal, { openModal }] = useModal();

function handleSuccess(record) {
  // console.log(1);
  getSensorTableData();
}
// 筛选数据
function screenData() {
  let screenDataArr = [];
  let arr = [];
  // 筛选value
  if (dataCenter.formState.value == '') {
    arr = dataCenter.tableValue;
  } else {
    dataCenter.tableValue.forEach((element) => {
      if (
        element.sensor_name.indexOf(dataCenter.formState.value) != -1 ||
        (element.senid + '').indexOf(dataCenter.formState.value) != -1
      ) {
        arr.push(element);
      }
    });
  }
  screenDataArr = arr;
  let arr1 = [];
  if (dataCenter.formState.name == '') {
    arr1 = screenDataArr;
  } else {
    screenDataArr.forEach((element) => {
      if (dataCenter.formState.name == element.st_name) {
        arr1.push(element);
      }
    });
  }
  screenDataArr = arr1;
  let arr2 = [];
  if (dataCenter.formState.type == '') {
    arr2 = screenDataArr;
  } else {
    screenDataArr.forEach((element) => {
      if (dataCenter.formState.type == element.sensor_type) {
        arr2.push(element);
      }
    });
  }
  screenDataArr = arr2;
  setTableData(screenDataArr);
}
// 自定义提交逻辑
function submitFunc() {
  screenData();
}

//自定义重置逻辑
function resetFunc() {
  dataCenter.formState.name = '';
  dataCenter.formState.type = '';
  dataCenter.formState.value = '';
  screenData();
}
// 新增
function handleCreate() {
  openModal(true, {
    isUpdate: false,
  });
}
// 详情
function handleViewDetail(record) {
  console.log(record)
  getProperties({
    type: 'sensor',
    attr: {
      com_name: '',
      basin_id: 0,
      stcd: record.senid,
      pid: record.pid,
    },
  }).then((res) => {
    let obj = res.data.attr
    obj.sensor_name = res.data.name
    openModal(true, {
    details: true,
    formData: obj,
  });
  });
  
}
// 编辑
function handleViewEidt(record) {
  // console.log(record);
  // openModal(true, {
  //   isUpdate: true,
  //   formData: record,
  // });
  console.log(record)
  getProperties({
    type: 'sensor',
    attr: {
      com_name: '',
      basin_id: 0,
      stcd: record.senid,
      pid: record.pid,
    },
  }).then((res) => {
    let obj = res.data.attr
    obj.sensor_name = res.data.name
    // console.log(res);
    openModal(true, {
      isUpdate: true,
      formData: obj,
    });
  });
}
// 删除
function handleViewdel(record) {
  let formData = {};
  formData.type = 'sensor';
  formData.attr = {
    stcd: record.senid,
    pid: record.pid,
  };
  getDeleteTree(formData).then((res) => {
    if(res.code == 200){
      getSensorTableData()
    }
  });
}

function processingData(table_head) {
  table_head.forEach((element) => {
    for (let key in element) {
      let item = element[key];
      element.title = item;
      element.key = key;
      element.dataIndex = key;
      if (key == 'storage') {
        element.slots = { customRender: 'storage' };
      }
    }
  });
  return table_head;
}
// 点击是否入库
function statusChange(checked, record) {
  console.log(checked);
  console.log(record);
}
// 筛选查询条件
function measuringStation(table_value) {
  let option1 = [];
  let option2 = [];
  // table_value.forEach((element) => {
  //   option1.push(element.st_name);
  // });
  dataCenter.optionArr = reduction(JSON.parse(JSON.stringify(table_value)), 'st_name');
  dataCenter.optionArr1 = reduction(JSON.parse(JSON.stringify(table_value)), 'sensor_type');
}
// 对象数组去重
function reduction(list, key) {
  const uniqueArr = list.filter((item, index) => {
    item.label = item[key];
    item.value = item[key];
    if (item[key]) {
      return list.findIndex((i) => i[key] === item[key]) === index;
    }
  });
  return uniqueArr;
}
function getSensorTableData() {
  getSensorTable().then((res) => {
    dataCenter.accountFormSchema = res.data.table_head;
    setColumns(processingData(res.data.table_head));
    dataCenter.tableValue = res.data.table_value;
    setTableData(res.data.table_value);
    measuringStation(res.data.table_value);
  });
}
const exportDataFn = () => {
  exportData(getColumns(),getDataSource(),'传感器管理.xlsx')
}
onMounted(() => {
  getSensorTableData();
});
</script>
<style scoped lang="less">
.form-box {
  position: absolute;
  z-index: 9;
  width: 66.6666%;
  .custom-input {
    width: calc(100% - 100px);
  }
}
.span-label {
  width: 90px;
  padding-right: 10px;
  display: inline-block;
  text-align: right;
  line-height: 32px;
}
.marg-left {
  margin-left: 10px;
}
.ant-table-striped-modal {
  margin-top: 20px;
}
.box-basic {
  height: calc(100% - 46px);
  width: calc(100% - 28px);
  position: absolute;
  // min-height: 600px;
}
.moddal-box {
  display: flex;
  height: calc(100% - 32px);
  .left-box {
    flex: 1;
    overflow: hidden;
    height: 100%;
  }
  .right-box {
    width: 400px;
    height: 100%;
    overflow: auto;
    margin-left: 20px;
    position: relative;
    ul {
      // position: relative;
      li {
        display: flex;
        line-height: 36px;
        & > div {
          // flex: 1;
          text-align: center;
        }
        & > div:nth-child(1) {
          min-width: 180px;
        }
        & > div:nth-child(2) {
          flex: 1;
        }
        & > div:nth-child(3) {
          flex: 1;
        }
      }
      li:nth-child(1) {
        position: absolute;
        width: 100%;
      }
      li:nth-child(2) {
        padding-top: 36px;
      }
    }
  }
}
.vben-basic-table-form-container {
  padding: 0px;
}
</style>
