<template>
  <basic-container v-loading="details.loadingObj.pageLoading">
    <div class="avue-crud">
      <!-- 搜索模块 -->
      <div v-h5uShow="!search">
        <!-- 查询模块 -->
        <el-form :inline="true" :model="query" class="header_search">
          <!-- 查询按钮 -->
          <!-- <el-form-item class="el-btn">
            <el-button type="primary" icon="el-icon-search" @click="searchChange">搜 索</el-button>
            <el-button icon="el-icon-delete" @click="searchReset">清 空</el-button>
          </el-form-item> -->
        </el-form>
      </div>

      <!-- 控件模块 -->
      <div class="avue-crud__header">
        <!-- 头部左侧按钮模块 -->
        <div class="avue-crud__left">
          <el-button type="primary" icon="Plus" @click="handleAdd">新 增</el-button>
        </div>

        <!-- 头部右侧按钮模块 -->
        <div class="avue-crud__right">
          <el-button icon="Download" @click="handleExportData" circle></el-button>
          <el-button icon="el-icon-refresh" @click="searchChange" circle></el-button>
          <el-button icon="Operation" @click="showdrawer(true)" circle></el-button>
          <el-button icon="Search" @click="searchHide" circle></el-button>
        </div>
      </div>

      <!-- 列表模块 -->
      <tablecmt
        :columnList="details.columnList"
        :tableData="details.renderData"
        :loading="loadingObj.list"
        @inputTxt="inputsc"
        @timeCheck="timesc"
        @selectCheck="selectsc"
        @selection="selectionChange"
      >
        <template #default="slotProps">
          <template v-if="slotProps.scope.column.label === '操作'">
            <el-text @click="() => handleEdit(slotProps.scope)">编辑</el-text>
          </template>
        </template>
      </tablecmt>
    </div>
  </basic-container>

  <!-- 处理异常 -->
  <el-dialog
    :title="details.title"
    :visible.sync="details.popUpShow.vehicleInfoVisited"
    width="780px"
    :align-center="true"
    v-model="details.popUpShow.vehicleInfoVisited"
  >
    <el-form :model="details.form" ref="formRef" label-width="120px">
      <!-- 车辆类型 -->
      <el-form-item v-for="item in details.formOption" :key="item.prop" :label="item.label">
        <template v-if="item.type === 1">
          <el-input class="flex1" v-model="details.form[item.prop]" />
        </template>

        <template v-else-if="item.type === 2">
          <el-input-number
            class="flex1 inputNumber"
            v-model="details.form[item.prop]"
            :controls="false"
            :min="0"
            :precision="item.precision"
            :value-on-clear="0"
          />
        </template>

        <template v-else-if="item.type === 3">
          <el-select v-model="details.form.vehicleModel" placeholder="请选择车辆类型" class="flex1">
            <el-option
              v-for="item in details.vehicleModelOption"
              :key="item.dictKey"
              :label="item.dictValue"
              :value="item.dictKey"
            />
          </el-select>
        </template>
      </el-form-item>
    </el-form>

    <div class="text-right">
      <el-button icon="CircleClose" @click="() => (details.popUpShow.vehicleInfoVisited = false)">
        关 闭
      </el-button>
      <el-button type="primary" icon="Position" @click="handleSubmit">提 交</el-button>
    </div>
  </el-dialog>

  <!-- 列表配置显示 -->
  <edittablehead
    @closce="showdrawer"
    :drawerShow="drawerShow"
    v-model="details.columnList"
    :columnList="details.columnList"
  ></edittablehead>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, computed, onMounted, nextTick } from 'vue';
import functions from '@/utils/functions.js';
import dayjs from 'dayjs';
import { mapGetters } from 'vuex';
/** 获取字典 */
import { getDictionaryBiz } from '@/api/system/dict';
import {
  downloadXls,
  setNodeHeight,
  getHtmls,
  deepClone,
  handleClearTableQuery,
  getObjType,
  handleSelectQuery,
  handleInputQuery,
  handleTranslationDataSeclect,
  handleFilterData,
} from '@/utils/util';
import { columnList } from '@/option/basicdata/basicdataVehicleInfo';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getToken } from '@/utils/auth';
import { getList, postSave } from '@/api/basicdata/basicdataVehicleInfo';
import { exportExcel } from '@/utils/exportData';

// 获取路由实例
const $router = useRouter();

// 组件实例
const formRef = ref();

const details = reactive<any>({
  /** 是否开启搜索 */
  search: true,
  /** 表格搜索条件 */
  query: {
    inputQuery: {},
    selectQuery: {},
  },
  /** 时间快捷选择设置 */
  shortcuts: [
    {
      text: '最近一周',
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        return [start, end];
      },
    },
    {
      text: '最近一个月',
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        return [start, end];
      },
    },
    {
      text: '最近三个月',
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        return [start, end];
      },
    },
  ],
  /** 列表 */
  columnList: deepClone(columnList),
  /** 列表数据 */
  data: [],
  renderData: [],
  /** 页面loading */
  loadingObj: {
    /** 列表加载loading */
    list: false,
    packageListLoading: false,
    /** 页面loading */
    pageLoading: false,
  },
  /** 列表复选框选中的数据 */
  selectionList: [],
  /** 是否显示设置表格 */
  drawerShow: false,
  /** 分页参数 */
  page: {
    pageNum: 1,
    pageSize: 30,
    total: 0,
  },
  /** 弹出层显示 */
  popUpShow: {
    /** 图片预览 */
    vehicleInfoVisited: false,
  },
  /** 列表Dom节点 */
  listNode: '',
  form: {},
  /** 全屏 */
  fullscreenObj: {
    /** 查看 */
    view: false,
  },
  title: '新增',
  type: 'add' as 'add' | 'edit',
  vehicleModelOption: [],
  formOption: [
    {
      prop: 'vehicleModel',
      label: '车辆类型',
      type: 1,
      values: '',
    },
    {
      prop: 'vehicleCommander',
      label: '车长(M)',
      type: 2,
      precision: 2,
    },
    {
      prop: 'vehicleHeight',
      label: '外廓高',
      type: 2,
      precision: 4,
    },
    {
      prop: 'approvedVolume',
      label: '核定体积',
      type: 2,
      precision: 4,
    },
    {
      prop: 'vehicleQuality',
      label: '车辆总质量(T)',
      type: 2,
      precision: 4,
    },
    {
      prop: 'curbWeight',
      label: '整备质量(T)',
      type: 2,
      precision: 4,
    },
  ],
});

const { search, query, data, loadingObj, selectionList, drawerShow, page } = toRefs(details);

/** vuex */
const permission = computed(() => mapGetters(['permission', 'tagWel', 'tagList']));

const initData = async () => {
  try {
    // const res = await getDictionaryBiz('price_vehicle_type');
    const res = await getDictionaryBiz('basic_vehicle_model');
    // basic_vehicle_model
    const { code, data } = res.data;
    if (code !== 200) return;
    details.vehicleModelOption = data;
    for (let i = 0; i < details.columnList.length; i++) {
      const value = details.columnList[i];

      if (value.label !== '车辆类型') continue;
      value.checkarr = data.map(val => {
        return { label: val.dictValue, value: val.dictKey };
      });
      break;
    }
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
  }
};

// initData();

/** 请求页面数据 */
const onLoad = async (page?: any, params = {}) => {
  try {
    details.loadingObj.list = true;
    let _page = details.page;
    if (page) _page = page;
    // 获取暂存单列表

    const submitData = { ..._page, ...details.query, ...params };

    const res = await getList(submitData);
    console.log('res :>> ', res);
    const { code, data } = res.data;
    if (code !== 200) return;
    details.data = data;

    handleTranslationDataSeclect(details.data, details.columnList);

    details.renderData = handleFilterData(details.data, [], details.query);
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.list = false;
  }
};

onLoad();

/** 搜索 */
const searchChange = () => {
  onLoad(details.page);
};

/** 清空表单 */
const searchReset = () => {
  details.query = {};
  details.page.pageNum = 1;
  handleClearTableQuery(details.columnList);
  onLoad(details.page);
};

/** 展开列表控件 */
const showdrawer = (_flag?: boolean) => {
  details.drawerShow = _flag;
};

/** 是否开启搜索区 */
const searchHide = () => {
  details.search = !details.search;

  setNodeHeight(details.listNode, '', true);
};

/** 表格表头输入框搜索 */
const inputsc = (index, row) => {
  handleInputQuery(index, row, details.query.inputQuery, true);
  details.renderData = handleFilterData(details.data, [], details.query);
};

/** 表格表头时间选择 */
const timesc = (index, row) => {
  console.log(index, row);
  if (!!index) {
    index = dayjs(index).format('YYYY-MM-DD');
  }
  details.query[row.prop] = index;
  if (!index) {
    delete details.query[row.prop];
  }
  onLoad(details.page);
};

/** 表格表头下拉框选择 */
const selectsc = (index, row) => {
  handleSelectQuery(index, row, details.query.selectQuery);
  details.renderData = handleFilterData(details.data, [], details.query);
};

/** 表格表头复选框选择 */
const selectionChange = (list: any) => {
  details.selectionList = list;
};

/** 每页数量改变执行的回调 */
const sizeChange = (pageSize: number) => {
  details.page.pageSize = pageSize;
  onLoad(details.page);
};

/** 页码改变执行的回调 */
const currentChange = current => {
  details.page.pageNum = current;
  onLoad();
};

/** 弹出层开启前清除数据 */
const beforeClose = done => {
  done();
  details.form = {};
  details.selectionList = [];
  details.view = false;
};

/** 新增 */
const handleAdd = () => {
  details.title = '新增';
  details.popUpShow.vehicleInfoVisited = true;

  details.form = {};
  for (let i = 0; i < details.formOption.length; i++) {
    const value = details.formOption[i];
    if (value.label === '车辆类型') continue;
    details.form[value.prop] = 0;
  }
};

/** 编辑 */
const handleEdit = ({ row }) => {
  details.title = '编辑';
  details.popUpShow.vehicleInfoVisited = true;

  for (let i = 0; i < details.formOption.length; i++) {
    const value = details.formOption[i];
    // if (value.label === '车辆类型') continue;
    details.form[value.prop] = value.type === 2 ? Number(row[value.prop]) || 0 : row[value.prop];
  }
  details.form.id = row.id;
};

/** 提交 */
const handleSubmit = async () => {
  try {
    details.loadingObj.pageLoading = true;
    details.popUpShow.vehicleInfoVisited = false;
    const submitData = { ...details.form };
    for (let i = 0; i < details.formOption.length; i++) {
      const value = details.formOption[i];
      if (value.label === '车辆类型') {
        if (!submitData[value.prop]) return ElMessage.warning('请选择车辆类型');
        continue;
      }
      submitData[value.prop] =
        getObjType(submitData[value.prop]) !== 'number' || submitData[value.prop] < 0
          ? 0
          : submitData[value.prop];
    }
    const res = await postSave(details.form);
    const { code, msg } = res.data;
    if (code !== 200) return;
    msg && ElMessage.success(msg);
    onLoad();
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.pageLoading = false;
  }
};

/** 导出表格数据 */
const handleExportData = () => {
  exportExcel(details.columnList, details.data, '车型 - ' + new Date().getTime());
};
</script>

<style scoped lang="scss">
// 日期选择器
:deep(.el-date-editor.el-input) {
  height: 100% !important;
  width: 100% !important;
}

:deep(.el-range-editor.el-input__wrapper) {
  height: 100% !important;
}

.mt20 {
  margin-top: 20px;
}

.fwb {
  font-weight: bold;
}

:deep(.el-tag) {
  border: none;

  &.blue {
    background: var(--el-color-primary);
  }
}

:deep(.el-input-number .el-input__inner) {
  text-align: left !important;
}

.text-right {
  text-align: right;
}
</style>
