<template>
  <basic-container>
    <!-- 首页表格 -->
    <div class="avue-crud" v-loading="loadingObj.packageListLoading">
      <!-- 搜索模块 -->
      <div v-h5uShow="search">
        <!-- 查询模块 -->
        <el-form :inline="true" :model="query" class="el-fr-d">
          <!-- 查询按钮 -->
          <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>

      <!-- 控件模块 -->
      <el-row>
        <div class="avue-crud__header">
          <!-- 头部左侧按钮模块 -->
          <div class="avue-crud__left"></div>
          <!-- 头部右侧按钮模块 -->
          <div class="avue-crud__right">
            <el-button icon="el-icon-refresh" @click="searchChangeS" circle></el-button>
            <el-button icon="Operation" @click="showdrawer(true)" circle></el-button>
            <el-button icon="Search" @click="searchHide" circle></el-button>
          </div>
        </div>
      </el-row>

      <!-- 首页表格 -->
      <el-row>
        <!-- 列表模块 -->
        <tablecmt
          class="tableNode"
          :columnList="details.columnList"
          :tableData="data"
          :loading="loadingObj.list"
          @inputTxt="inputsc"
          @timeCheck="timesc"
          @selectCheck="selectsc"
          @selection="selectionChange"
        >
          <template #default="slotProps">
            <template v-if="slotProps.scope.column.label === '操作'">
              <div class="ElBtnClass">
                <el-text @click="edit(slotProps.scope.row)">编辑</el-text>
                <el-text @click="ViewDelete(slotProps.scope.row)">删除</el-text>
              </div>
            </template>
          </template>
        </tablecmt>
      </el-row>

      <!-- 分页模块 -->
      <el-row class="el-fy">
        <div class="avue-crud__pagination flex-c-sb" style="width: 100%">
          <div></div>
          <el-pagination
            align="right"
            background
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page="page.currentPage"
            :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>
    <el-dialog title="编辑" v-model="malldialog" width="50%" append-to-body>
      <el-form :model="form" label-width="80px" :disabled="loadingObj.list">
        <el-form-item label="三方商城">
          <el-input v-model.trim="form.tripartiteMall" placeholder="请输入三方商城" />
        </el-form-item>
        <el-form-item label="三方编码">
          <el-input v-model.trim="form.tripartiteCoding" placeholder="请输入三方编码" />
        </el-form-item>
        <el-form-item label="品牌">
          <el-select
            v-model="form.brandId"
            filterable
            remote
            :remote-method="remoteMethod"
            class="m-2"
            placeholder="请选择品牌"
            clearable
          >
            <el-option
              v-for="item in brandList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 表单按钮 -->
      <template #footer>
        <span v-if="!view" class="dialog-footer">
          <el-button
            type="primary"
            icon="el-icon-circle-check"
            :disabled="loadingObj.list"
            @click="handleSubmit"
            >提 交</el-button
          >
        </span>
      </template>
    </el-dialog>
  </basic-container>
  <!-- 列表配置显示 -->
  <edittablehead
    @setcolum="setnewcolum"
    @closce="showdrawer"
    :drawerShow="drawerShow"
    :columnList="details.columnList"
    v-model="details.columnList"
  ></edittablehead>
</template>

<script setup>
import { ref, reactive, toRefs, computed, onMounted, nextTick, watch } from 'vue';
import { columnList } from '@/option/basicdata/ThreePartyMallManagement.js';
import { $_pageList } from '@/api/basicdata/ThreePartyMallManagement';
import { getDetail, update, remove } from '@/api/basicdata/basicdataTripartiteMall';
import { getList as getBrandList } from '@/api/basicdata/basicBrand';
import { processRowPropertyName, setNodeHeight } from '@/utils/util';
import { ElMessageBox, ElMessage } from 'element-plus';
import { downloadXls, handleClearTableQuery } from '@/utils/util';
import { useStore } from 'vuex';
import { getDictionaryBiz } from '@/api/system/dict';
import dayjs from 'dayjs';
const $router = useRouter(); //跳转
const $useStore = useStore(); //权限
const $route = useRoute(); //获取地址栏参数
const DeliveryType = ref([]); //配送类型
const brandList = ref([]); //品牌
const form = ref({});
const malldialog = ref(false);
const details = reactive({
  /** 是否开启搜索 */
  search: false,
  /** 表格搜索条件 */
  query: {},
  defaultTime2: [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)], // '12:00:00', '08:00:00'
  /** 时间快捷选择设置 */
  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];
      },
    },
  ],
  /** 时间选择器数据 */
  stockupDate: [],
  /** 列表 */
  columnList,

  /** 列表数据 */
  data: [],
  /** 页面loading */
  loadingObj: {
    /** 列表加载loading */
    list: false,
    packageListLoading: false,
  },
  /** 列表复选框选中的数据 */
  selectionList: [],
  /** 是否显示设置表格 */
  drawerShow: false,
  /** 分页参数 */
  page: {
    currentPage: 1,
    pageSize: 50,
    total: 0,
  },

  /** 弹出层显示 */
  popUpShow: {
    /** 包件明细 */
    packageOrderListlVisited: false,
    /** 二维码 */
    QRCodeVisible: false,
    /** 修改客户信息 */
    editClientInfoVisible: false,
  },
  /** 列表Dom节点 */
  listNode: '',
  form: {},
  /** 全屏 */
  fullscreenObj: {
    /** 包明细 */
    packageOrderListlVisited: false,
  },
});

const {
  search,
  query,
  shortcuts,
  stockupDate,
  data,
  loadingObj,
  selectionList,
  drawerShow,
  page,
  trickleLoadingPage,
  zeroAdditionalRecordingInfo,
  popUpShow,
  recorddata,
  defaultTime2,
} = toRefs(details);

/** 展开列表控件 */
const showdrawer = _flag => {
  details.drawerShow = _flag;
};
/** 表格表头输入框搜索 */
const inputsc = (index, row) => {
  processRowPropertyName(index, row, details.query);
  onLoad();
};

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

/** 表格表头下拉框选择 */
const selectsc = (index, row) => {
  processRowPropertyName(index, row, details.query);
  onLoad();
};
/** 表格表头复选框选择 */
const selectionChange = list => {
  console.log(list);
  details.selectionList = list;
};
// 网页顶部搜索按钮
const searchChange = () => {
  onLoad();
};
// 每页多少条
const sizeChange = val => {
  details.page.pageSize = val;
  onLoad();
};
/** 页码改变执行的回调 */
const currentChange = val => {
  details.page.currentPage = val;
  onLoad();
};
// 刷新按钮
const searchChangeS = () => {
  details.search = false; //关闭搜索
  onLoad();
};
//清空
const searchReset = () => {
  details.query = {};
  details.page.currentPage = 1;
  handleClearTableQuery(details.columnList);
  onLoad();
};
// 顶部搜索
const searchHide = () => {
  console.log(details);
  details.search = !details.search;
  const _node = document.querySelector('.tableNode');
  setNodeHeight(_node, '', true);
};
const remoteMethod = value => {
  getBrandList(1, 1000, { brandName: value }).then(res => {
    console.log('res ===>', res);
    const {
      code,
      data: { records },
    } = res.data;
    if (code !== 200) return;
    brandList.value = records.map(val => {
      return {
        value: val.id,
        label: val.brandName,
      };
    });
  });
};
const GeBrandListt = async () => {
  let res = await getBrandList();
  const {
    code,
    data: { records },
  } = res.data;
  if (code !== 200) return;
  brandList.value = records.map(val => {
    return {
      value: val.id,
      label: val.brandName,
    };
  });
};
// 字典公共函数
function updateDictionary(targetArray, dictionaryType) {
  getDictionaryBiz(dictionaryType).then(res => {
    console.log(res, '字典');
    res.data.data.forEach(item => {
      targetArray.push({
        value: item.dictKey,
        label: item.dictValue,
      });
    });
    return;
  });
}
// 请求字典配送类型
const Dictionaryrequest = async () => {
  await updateDictionary(DeliveryType.value, 'distribution_type');
};
const Dictionaryprocessing = data => {
  if (data?.length) {
    data.forEach(item => {
      if (['1', '2', '3', '4'].includes(item.typeService)) {
        item.typeServiceNameS = DeliveryType.value.find(i => i.value == item.typeService)?.label;
      }
    });
  }
};
// 页面初始化
const onLoad = async () => {
  details.loadingObj.list = true;
  let submitData = {
    current: details.page.currentPage,
    size: details.page.pageSize,
    ...details.query,
  };
  let _res = await $_pageList(submitData);
  details.loadingObj.list = false;
  const { code, data } = _res.data;
  if (code != 200) {
    return;
  }
  details.data = data.records;
  Dictionaryprocessing(details.data);
  details.page.total = data.total;
  console.log(_res, 'res');
};
const onLoadPage = async () => {
  details.loadingObj.list = true;
  await Dictionaryrequest();
  onLoad();
  GeBrandListt();
};
// 页面初始化
onLoadPage();
// 编辑
const edit = async row => {
  details.loadingObj.list = true;
  let res = await getDetail(row.id);
  details.loadingObj.list = false;
  malldialog.value = true;
  form.value = res.data.data;
  console.log(res);
};
const handleSubmit = async () => {
  const submitForm = form.value;
  submitForm.brandName = brandList.value.find(item => item.value == form.value.brandId)?.label;
  let _res = await update(submitForm);
  if (_res.data.code == 200) {
    malldialog.value = false;
    ElMessage.success('编辑成功');
    onLoad();
  }
};
// 删除
const ViewDelete = (row) => {
  ElMessageBox.confirm('是否确认删除数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      details.loadingObj.list = true;
      let res = await remove(row.id);
      details.loadingObj.list = false;
      if (res.data.code == 200) {
        ElMessage.success('删除成功');
        onLoad();
      }
    })
    .catch(() => {});
};
</script>

<style scoped lang="scss">
.ElBtnClass button {
  border: none;
  padding: 0;
  background-color: transparent;
}
:deep(.el-card) {
  height: 100%;
}
:deep(.el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.el-fy {
  flex: 1;
  display: flex;
  align-items: flex-end;
}
.avue-crud {
  height: 100%;
  display: flex;
  flex-direction: column;
}
</style>
