<template>
  <div>
    <YaPageContent ref="multipleTableRef" :total="total" :tableData="tableData" :tableColumns="column" :buttons="buttons"
      @submit="handleSubmit" @init="search" @tableBtnClick="tableBtnClick" @selectionChange="handleSelectionChange">
    </YaPageContent>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, FormRules } from "element-plus";
import { provinceData } from '../../assets/map/province'
import { usePermissions } from "../../composables/usePermissions";
import {
  getPage,
  add,
  edit,
  deleteBtn,
  fetchSomeExport,
  allExportAssetManage,
  importCheck,
  importBtn,
  getDictTypeListOne,
  getDept,
  getIssuePerson
} from "../../api/assetsManagement/assetsManagement";
import { getDictTypeList } from "../../api/common";
import { http } from "@/utils/https";
import { yaMessage } from '@/utils/message';
const { permissionsButtons } = usePermissions();
const buttons: any = ref([]);
let bottomData: any = new Map();

const templateUrl = ref('123')
/**
 * @desciption 获取按钮权限
 */
const getButton = () => {
  permissionsButtons.map((item) => {
    bottomData.set(item.menuId, item);
  });
  if (bottomData.has(200404)) {
    buttons.value.push({
      eventName: "export",
      // custom: 'dropdown',
      // title: bottomData.get(200404).label,
      // customData: [
      //   {
      //     name: '批量' + bottomData.get(200404).label,
      //     eventName: 'export',
      //   },
      //   {
      //     name: '全部' + bottomData.get(200404).label,
      //     eventName: 'allExport',
      //   },
      // ],
    });
  }
  if (bottomData.has(200401)) {
    buttons.value.push({
      eventName: "add",
    });
  }
  if (bottomData.has(200405)) {
    buttons.value.push({
      eventName: "import",
      templateUrl: 'asset.xlsx',
      http: http
    });
  }
  if (bottomData.has(200403)) {
    buttons.value.push({
      eventName: "delete"
    });
  }
};
const multipleTableRef = ref();
const total = ref(0);
const tableData = ref([]);
const column = ref([
  {
    type: 'selection',
    width: '65px',
    fixed: "left",
  },
  {
    prop: 'assetName',
    label: '资产名称',
    maxlength: 50,
    type: 'input',
    search: true,
    drawer: true,
    rules: true,
    minWidth: '150px'
  },
  {
    prop: 'assetIp',
    label: 'IP',
    type: 'input',
    search: true,
    drawer: true,
    rules: true,
    minWidth: '150px'
  },
  {
    prop: 'time',
    label: '更新时间',
    search: true,
    type: "daterange",
    valueFormat: "YYYY-MM-DD",
    minWidth: '180px',
    tableHide: true
  },
  {
    prop: 'gmtModified',
    label: '更新时间',
    minWidth: '180px',
  },
  {
    prop: 'assetType',
    label: '资产类型',
    type: 'cascader',
    props: {
      checkStrictly: true,
      emitPath: false,
    },
    search: true,
    drawer: true,
    minWidth: '150px',
    tableHide: true
  },
  {
    prop: 'assetTypeName',
    label: '资产类型',
    minWidth: '150px'
  },
  {
    prop: 'level',
    label: '重要等级',
    type: 'select',
    options: [],
    search: true,
    drawer: true,
    minWidth: '150px',
    tableHide: true
  },
  {
    prop: 'levelName',
    label: '重要等级',
    minWidth: '150px',
  },
  {
    prop: 'deptId',
    label: '归属部门',
    type: 'select',
    search: true,
    drawer: true,
    tableHide: true,
    minWidth: '150px'
  },
  {
    prop: 'deptName',
    label: '归属部门',
    type: 'input',
    minWidth: '150px'
  },
  {
    prop: 'contactName',
    label: '联系人',
    minWidth: '150px'
  },
  {
    prop: 'contact',
    label: '联系人',
    type: 'select',
    drawer: true,
    minWidth: '150px',
    tableHide: true
  },
  {
    prop: 'assetUsage',
    label: '使用用途',
    type: 'textarea',
    maxlength: 50,
    rows: 4,
    drawer: true,
    minWidth: '150px'
  },
  {
    prop: "position",
    label: "地理位置",
    type: 'cascader',
    drawer: true,
    options: provinceData,
    tableHide: true,
  },
  {
    prop: "location",
    label: "地理位置",
    minWidth: '150px'
  },
  {
    label: "操作",
    width: "100px",
    fixed: "right",
    buttons: [
      {
        title: "编辑",
        eventName: "edit",
        disabled: () => {
          return !bottomData.has(200402);
        },
      },
      {
        title: "删除",
        eventName: "delete",
        disabled: () => {
          return !bottomData.has(200403);
        },
      },
    ],
  },
]
);
/**
 * @description 初始化列表数据
 */
const tableInit = () => {
  multipleTableRef.value.initData();
};
/**
 * @description 模板提交事件
 * @param eventName 事件名称 export: 批量导出
 * @param data 表单提交数据
 * @param cb  { Function } 组件回调  （ 新增，编辑，删除，上传需要参数: Boolean true(关闭loading,弹窗)/false(关闭loading) uploadCheck: 上传校验  upload：上传
 */
const handleSubmit = (eventName, data, cb) => {
  let params = JSON.parse(JSON.stringify(data));
  switch (eventName) {
    case 'export':
      fetchSomeExport({ ids: data.toString() }).then((res) => {
        cb && cb(res, "资产管理.xlsx");
      });
      break;
    case 'add':
      if (params.position) {
        params.country = params.position[0]
        params.province = params.position[1]
        params.city = params.position[2]
      }
      delete params.position
      submitBtn(params, cb)
      break;
    case 'edit':
      if (params.position) {
        params.country = params.position[0]
        params.province = params.position[1]
        params.city = params.position[2]
      }
      delete params.position
      submitBtn(params, cb)
      break;
    case 'batchDelete':
      delBtn('some', '')
      break;
    case "delete":
      delBtn('one', params.id)
      break;
    case 'uploadCheck':
      // data ---> file
      // cb && cb('上传返回的信息')
      let fd = new FormData();
      fd.append("file", data.raw);
      importCheck(fd).then((res) => {
        if (res.code === 200) {
          cb && cb(res.data)
        } else {
          cb && cb({
            importStatus: false
          })
        }
      }).catch(() => {
        cb && cb({
          importStatus: false
        })
      })
      break;
    case 'upload':
      let fd1 = new FormData();
      fd1.append("file", data.raw);
      importBtn(fd1).then((res) => {
        if (res.code === 200) {
          cb && cb()
          ElMessage.success(res.message)
          tableInit();
        }
      })
      break;
  }
};
/**
 * @desciption 查询列表数据
 */
const search = async (type) => {
  let _data = JSON.parse(JSON.stringify(type))._value;
  if (_data.time) {
    _data.updateTimeStart = _data.time[0];
    _data.updateTimeEnd = _data.time[1];
    delete _data.time
  }
  let parms = {
    ..._data,
  }
  let res = await getPage(parms);
  if (res.code == 200) {
    total.value = res.data.total;
    tableData.value = res.data.records;
  }
};
/**
 * @description  列表按钮点击事件
 * @param btn  eventName = 'detail': 详情, 'study': 研判, 'down': 下载
 * @param row  单条数据
 */
const tableBtnClick = (btn, row) => {
  let { eventName } = btn;
  switch (eventName) {
    case 'edit':
      if (row.country) {
        row.position = row.location.split('·')
      }
      break;
    case 'allExport':
      allExportAssetManage().then(res => {
        const { code, message } = res || {}
        code == 200 && yaMessage(message, 'success')
      })
      break;
  }
};
/**
 * @description 全选
 */
const selectData = ref([]);
const handleSelectionChange = function (val) {
  selectData.value = val;
};

/**
 * @descripiton 新增，编辑提交
 */
const submitBtn = async (data, cb) => {
  let require = data.id ? edit : add;
  try {
    let res = await require(data);
    if (res.code == 200) {
      ElMessage.success(res.message);
      cb(true)
    } else {
      cb(false)
    }
  } catch {
    cb(false)
  }
}
/**
 * @description 删除
 */
const delBtn = async (type, row) => {
  let ids;
  if (type == 'some') {
    ids = selectData.value.map((item) => {
      return item.id
    }).toString()
  } else {
    ids = row
  }
  let res = await deleteBtn({ ids: ids });
  if (res.code == 200) {
    ElMessage.success('删除成功!')
    tableInit()
  }
}
const flatten = (tree = [], nodes = []) => {
  for (let item of tree) {
    item.label = item.dictName;
    item.value = item.dictValue;
    item.children = item.childList;
    delete item.childList
    nodes.push(item)
    item.children && flatten(item.children)
  }
  return nodes
}

/**
 * @description 字典列表
 */
const setData = (node, resolve) => {

}
const getDict = () => {
  getDictTypeList("assetLevel").then((res) => {
    column.value.forEach((item) => {
      if (item.prop == 'level') {
        item.options = res
      }
    })
  });
  getDictTypeListOne({
    dictType: 'assetType',
    needChildTree: true,
    needChild: true
  }).then(res => {
    if (res.code == 200) {
      column.value.forEach((item) => {
        if (item.prop == 'assetType') {
          item.options = flatten(res.data)
        }
      })
    }
  })
  getDept({}).then(res => {
    if (res.code == 200) {
      column.value.forEach((item) => {
        if (item.prop == 'deptId') {
          item.options = res.data.map((item) => {
            return {
              label: item.deptName,
              value: item.id
            }
          })
          // console.log(item.options)
        }
      })
    }
  })
  getIssuePerson({}).then(res => {
    if (res.code == 200) {
      column.value.forEach((item) => {
        if (item.prop == 'contact') {
          item.options = res.data.map((item) => {
            return {
              label: item.realityName,
              value: item.id
            }
          })
          // console.log(item.options)
        }
      })
    }
  })
}
const getProvinceAndCity = (data) => {
  if (!data || !data.length) return;
  data.forEach(item => {
    item.value = item.label
    if (item.children) {
      getProvinceAndCity(item.children)
    }
  })
}
/**
 * @description 初始化
 */
onMounted(() => {
  getButton()
  getDict()
  getProvinceAndCity(provinceData)

})
</script>
<style lang="scss" scoped></style>
