<template>
  <basic-container>
    <div class="avue-crud" v-loading="details.loadingObj.pageLoading">
      <!-- 搜索模块 -->
      <div v-h5uShow="!search">
        <!-- 查询模块 -->
        <el-form :inline="true" :model="query" class="header_search">
          <el-form-item label="车次号:">
            <el-input v-model="query.serviceNumber" placeholder="请输入车次号" clearable></el-input>
          </el-form-item>

          <!-- 查询按钮 -->
          <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>
          <!-- <el-button type="primary" icon="Edit" @click="handleEdit"> 编辑 </el-button> -->
        </div>
        <!-- 头部右侧按钮模块 -->
        <div class="avue-crud__right">
          <el-button icon="el-icon-refresh" @click="searchChange" circle></el-button>
          <el-button icon="Operation" @click="showdrawer(true)" circle></el-button>
          <el-button icon="el-icon-search" @click="searchHide" circle></el-button>
        </div>
      </div>

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

      <!-- 分页模块 -->
      <el-row class="el-fy">
        <div class="avue-crud__pagination flex-c-sb" style="width: 100%">
          <div style="font-size: 14px">勾选数量: {{ selectionList.length }}</div>
          <!-- 分页模块 -->
          <el-pagination
            align="right"
            background
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page="page.pageNum"
            :page-sizes="[30, 50, 80, 120]"
            :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total"
          >
          </el-pagination>
        </div>
      </el-row>
    </div>
  </basic-container>

  <!-- 配置装车目的地 -->
  <el-dialog
    title="新增"
    v-model="details.popUpShow.addVisited"
    width="40%"
    :before-close="beforeClose"
    append-to-body
    class="truckLoadingDetailPopUp"
  >
    <div v-loading="details.loadingObj.truckLoadingDetailPopUpLoading">
      <el-form ref="formRef" label-width="100px" :model="details.form">
        <el-form-item
          label="品牌"
          prop="brandName"
          :rules="[{ required: true, message: '请选择品牌', trigger: ['blur', 'change'] }]"
        >
          <el-select
            class="w100"
            v-model="details.form.brandName"
            filterable
            clearable
            placeholder="请选择品类"
            style="width: 240px"
            :loading="loadingObj.loading"
            @change="handleChangeBrand"
            remote
            reserve-keyword
            default-first-option
            :remote-method="value => debounce(remoteMethodBrand(value), 500)"
          >
            <el-option
              v-for="val in details.brandArr"
              :key="val.id"
              :label="val.brandName"
              :value="val.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="仓库"
          prop="warehouse"
          :rules="[{ required: true, message: '请选择仓库', trigger: ['blur', 'change'] }]"
        >
          <el-select
            class="w100"
            v-model="details.form.warehouse"
            filterable
            clearable
            placeholder="请选择仓库"
            style="width: 240px"
            :loading="loadingObj.loading"
            @change="handleChangeWareHouse"
            remote
            reserve-keyword
            default-first-option
            :remote-method="value => debounce(getMaterialTree(value), 500)"
          >
            <el-option
              v-for="val in details.warehouseArr"
              :key="val.id"
              :label="val.name"
              :value="val.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <div class="dialog-footer">
        <el-button icon="el-icon-circle-close" @click="details.popUpShow.addVisited = false"
          >取 消</el-button
        >
        <el-button type="primary" icon="el-icon-circle-check" @click="handleSubmit"
          >提 交</el-button
        >
      </div>
    </div>
  </el-dialog>

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

<script setup lang="ts">
import { ref, reactive, toRefs, computed, onMounted, nextTick } from 'vue';
import functions from '@/utils/functions';
import dayjs from 'dayjs';
import { mapGetters } from 'vuex';
/** 获取字典 */
import { getDictionaryBiz } from '@/api/system/dict';
import {
  downloadXls,
  setNodeHeight,
  debounce,
  deepClone,
  handleClearTableQuery,
} from '@/utils/util';
import { columnList } from '@/option/basicdata/ConfigureBillingAndWarehousing';
import {
  postPageList,
  postRemove,
  postSave,
  postBrandLists,
  getListName,
} from '@/api/basicdata/ConfigureBillingAndWarehousing';

import { useStore } from 'vuex';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';

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

const $store = useStore();

const Mydata = ref<any>({});

Mydata.value = JSON.parse(localStorage.getItem('my_data')); //获取本地仓库信息

console.log('Mydata :>> ', Mydata);

const details = reactive<any>({
  /** 是否开启搜索 */
  search: true,
  /** 表格搜索条件 */
  query: {},
  /** 时间快捷选择设置 */
  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: [],
  /** 页面loading */
  loadingObj: {
    /** 列表加载loading */
    list: false,
    /** 配置装车目的地详情 */
    truckLoadingDetailPopUpLoading: false,
    /** 页面laoding */
    pageLoading: false,
    loading: false,
  },
  /** 列表复选框选中的数据 */
  selectionList: [],
  /** 是否显示设置表格 */
  drawerShow: false,
  /** 分页参数 */
  page: {
    pageNum: 1,
    pageSize: 30,
    total: 0,
  },
  /** 弹出层显示 */
  popUpShow: {
    /** 新增 */
    addVisited: false,
  },
  form: {},
  /** 品牌 */
  brandArr: [],
  /** 仓库数据 */
  warehouseArr: [],
});

/** 表格实例 */
const tableNodeRef = ref();

/** 表单实例 */
const formRef = ref();

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

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

/** 请求页面数据 */
const onLoad = debounce(async (params = {}) => {
  try {
    // 开启loading
    details.loadingObj.list = true;

    // 请求页面数据
    const res = await postPageList({ ...details.page, ...details.query, ...params });
    const { code, data } = res.data;
    if (code !== 200) return;
    details.data = data.records;
    details.page.total = data.total;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.list = false;
  }
}, 10);

const initOnload = () => {
  details.page.pageNum = 1;
  onLoad();
};

initOnload();

/** 搜索 */
const searchChange = () => {
  initOnload();
};

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

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

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

  setNodeHeight(tableNodeRef.value.$el, '', true);
};

/** 表格表头输入框搜索 */
const inputsc = (index, row) => {
  details.query[row.prop] = index;
  if (!index && index !== 0) delete details.query[row.prop];
  initOnload();
};

/** 表格表头时间选择 */
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];
  }
  initOnload();
};

/** 表格表头输入框搜索 */
const btnsc = () => {};

/** 表格表头下拉框选择 */
const selectsc = (index, row) => {
  const _key = row.prop.replace('Name', '');

  details.query[_key] = index;
  if (!index) delete details.query[_key];

  initOnload();
};

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

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

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

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

/** 新增配载 */
const handleAdd = async () => {
  details.form = {};

  details.popUpShow.addVisited = true;
  await nextTick();
  formRef.value.resetFields();
};

/** 编辑配载信息 */
const handleEdit = ({ row }) => {};

/** 品牌切换 */
const handleChangeBrand = value => {
  console.log('value :>> ', value);

  for (let i = 0; i < details.brandArr.length; i++) {
    const item = details.brandArr[i];

    if (item.id !== value) continue;
    console.log('item :>> ', item);

    details.form.brand = item.brandName;
    details.form.brandId = item.id;
    break;
  }
};

/** 远程搜索品牌 */
const remoteMethodBrand = async value => {
  try {
    details.loadingObj.loading = true;

    const res = await postBrandLists({ brandName: value });

    const { code, data } = res.data;

    if (code !== 200) return;

    details.brandArr = data;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.loading = false;
  }
};

remoteMethodBrand('');

/** 搜索仓库 */
const getMaterialTree = async value => {
  if (!value) return;
  const res = await getListName({ name: value });

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

/** 物料变化时 */
const handleChangeWareHouse = value => {
  for (let i = 0; i < details.warehouseArr.length; i++) {
    const item = details.warehouseArr[i];
    console.log('item :>> ', item);

    if (item.id !== value) continue;
    console.log('item :>> ', item);
    details.form.warehouseName = item.name;
    details.form.warehouseId = item.id;
    break;
  }
};

/** 提交 */
const handleSubmit = () => {
  formRef.value.validate(async valid => {
    if (!valid) return;

    try {
      details.popUpShow.addVisited = false;
      details.loadingObj.pageLoading = true;
      const submitData = { ...details.form };

      const res = await postSave(submitData);

      const { code, msg } = res.data;

      if (code !== 200) return;
      ElMessage.success(msg || '操作成');

      initOnload();
    } catch (error) {
      console.log('error :>> ', error);
    } finally {
      details.loadingObj.pageLoading = false;
    }
  });
};

/** 删除 */
const handleRemove = ({ row }) => {
  ElMessageBox.confirm('确认删除吗?', '', {
    confirmButtonText: '确认',
    cancelButtonText: '关闭',
    type: 'warning',
  }).then(async () => {
    try {
      details.loadingObj.pageLoading = true;

      const res = await postRemove({ openIncomingId: row.id });

      const { code, msg } = res.data;

      if (code !== 200) return;

      ElMessage.success(msg);
      initOnload();
    } catch (error) {
      console.log('error :>> ', error);
    } finally {
      details.loadingObj.pageLoading = false;
    }
  });
};
</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;
}

.mr-10 {
  margin-right: 10px;
}

// 弹窗底部按钮
.dialog-footer {
  margin-top: 10px;
  text-align: center;
}

.w100 {
  width: 100% !important;
}
</style>
