<template>
  <basic-container>
    <!-- 首页表格 -->
    <div class="avue-crud">
      <!-- 搜索模块 -->
      <el-row v-if="search">
        <!-- 查询模块 -->
        <el-form :inline="true" :model="queryTop" class="el-fr-d">
          <div>
            <el-form-item label="承运方名称">
              <el-input v-model="queryTop.region" placeholder="请输入承运方名称" />
            </el-form-item>
            <el-form-item label="修改时间">
              <el-date-picker
                v-model="queryTop.costSettlementYear"
                type="datetimerange"
                unlink-panels
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :shortcuts="shortcuts"
                :default-time="defaultTime2"
              />
            </el-form-item>
          </div>
          <!-- 查询按钮 -->
          <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>
      </el-row>

      <!-- 控件模块 -->
      <el-row>
        <div class="avue-crud__header">
          <!-- 头部左侧按钮模块 -->
          <div class="avue-crud__left">
            <el-button type="primary" @click="AddInfo"
              ><el-icon><Download /></el-icon>导出价格</el-button
            >
            <el-button type="primary" @click="AddInfo"
              ><el-icon><Upload /></el-icon>导入价格</el-button
            >
            <el-button type="primary" @click="Informationadd"
              ><el-icon><Plus /></el-icon>新增</el-button
            >
          </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"
          @btnCheck="btnsc"
          @selectCheck="selectsc"
          @selection="selectionChange"
        >
          <template #default="slotProps">
            <template v-if="slotProps.scope.column.label === '操作'">
              <el-text size="small" @click="EditTemplate(slotProps.scope.row)">编 辑</el-text>
              <el-text size="small" @click="deleteTemplate(slotProps.scope.row)">删 除</el-text>
            </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 v-model="Priceconfiguration" :title="PriceconfigurationTitle" width="30%">
      <el-form
        :model="form"
        label-width="auto"
        v-loading="tcloading"
        element-loading-text="Loading..."
        ref="ruleFormRef"
        :rules="rules"
      >
        <el-form-item label="服务仓:" prop="warehouseId">
          <el-select
            @change="changServiceWarehouse"
            v-model="form.warehouseId"
            placeholder="请选择服务仓"
          >
            <el-option
              v-for="item in ServiceWarehouse"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="司机:" prop="driverId">
          <el-select v-model="form.driverId" placeholder="请选择司机">
            <el-option
              v-for="item in driver"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格模板:" prop="templateId">
          <el-select v-model="form.templateId" placeholder="请选择价格模板">
            <el-option
              v-for="item in PriceTemplate"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="Priceconfiguration = false">取消</el-button>
          <el-button type="primary" @click="Priceconfigurationsubmission">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </basic-container>
  <!-- 列表配置显示 -->
  <edittablehead
    @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/storagecost/ServiceProviderPrice.js';
import { getDictionaryBiz } from '@/api/system/dict'; //字典
import { processRowProperty, setNodeHeight,handleClearTableQuery } from '@/utils/util';
import { getDriverList } from '@/api/basicdata/basicdataDriverArtery'; //司机信息
import {
  $_getMyWarehouseList,
  $_ServiceProviderPrice,
  $_ServiceProviderPricesave,
  $_WarehousePricingTemplate,
  $_getDriverList,
  $_ServiceProviderPriceupdate,
  $_ServiceProviderPriceremove,
} from '@/api/storagecost/index.js';
import { ElMessageBox, ElMessage } from 'element-plus';
import { downloadXls } from '@/utils/util';
import { useStore } from 'vuex';
import dayjs from 'dayjs';
const $router = useRouter(); //跳转
const $useStore = useStore(); //权限
const $route = useRoute(); //获取地址栏参数
const warehouseList = ref([]);
const PriceconfigurationTitle = ref('价格配置(新增)');
const form = ref({});
const rowData = ref({});
const ServiceWarehouse = ref([]); //服务仓
const driver = ref([]); //司机
const tcloading = ref(false);
const PriceTemplate = ref([]); //价格模板
const Priceconfiguration = ref(false);
const WarehouseId = ref('');
const queryTop = ref({});
const ruleFormRef = ref(null);
const rules = reactive({
  warehouseId: [{ required: true, message: '请选择服务仓', trigger: 'blur' }],
  driverId: [{ required: true, message: '请选择司机', trigger: 'blur' }],
  templateId: [{ required: true, message: '请选择价格模板', trigger: 'blur' }],
});
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];
      },
    },
  ],
  /** 列表 */
  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,
  data,
  loadingObj,
  selectionList,
  drawerShow,
  page,
  trickleLoadingPage,
  zeroAdditionalRecordingInfo,
  popUpShow,
  defaultTime2,
  recorddata,
} = toRefs(details);

/** 展开列表控件 */
const showdrawer = _flag => {
  details.drawerShow = _flag;
};
/** 表格表头输入框搜索 */
const inputsc = (index, row) => {
  details.query[row.prop] = index;
  processRowProperty(index, row, details);
  onLoad();
};
// 实例函数
const test = val => {};
/** 表格表头时间选择 */
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 btnsc = val => {
  console.log(val);
};
/** 表格表头下拉框选择 */
const selectsc = (index, row) => {
  processRowProperty(index, row, details);
  onLoad();
};
/** 表格表头复选框选择 */
const selectionChange = list => {
  console.log(list);
  details.selectionList = list;
};
// 网页顶部搜索按钮
const searchChange = () => {
  // details.search = false; //关闭搜索
  onLoad()
};
const searchReset=()=>{
  details.query={}
  queryTop.value={}
  handleClearTableQuery(details.columnList);
  onLoad()
}
// 每页多少条
const sizeChange = val => {
  details.page.pageSize = val;
  onLoad();
};
/** 页码改变执行的回调 */
const currentChange = val => {
  details.page.currentPage = val;
  onLoad();
};

// 刷新按钮
const searchChangeS = () => {
  onLoad();
};
// 顶部搜索
const searchHide = () => {
  console.log(details);
  details.search = !details.search;
  const _node = document.querySelector('.tableNode');
  setNodeHeight(_node, '', true);
};
// 字典公共函数
function updateDictionary(targetArray, dictionaryType) {
  getDictionaryBiz(dictionaryType).then(res => {
    console.log(res, '字典');
    res.data.data.forEach(item => {
      targetArray.push({
        value: item.dictKey,
        label: item.dictValue,
      });
    });
  });
}

// 禁止选择的仓库
const disabledWarehouse = () => {
  let WarehouseName = localStorage.getItem('WarehouseName');
  console.log(WarehouseName, 'WarehouseName');
  if (WarehouseName != 'undefined') {
    let data = ServiceWarehouse.value.find(res => res.label == WarehouseName);
    console.log(data, 'data====');
    WarehouseId.value = data.value; //仓库ID
    ServiceWarehouse.value.forEach(item => {
      item.disabled = true;
    });
    data.disabled = false;
  }
};
// 获取仓库
const MyWarehouseList = async () => {
  await $_getMyWarehouseList().then(res => {
    console.log(res, '仓库列表');
    res.data.data.forEach(item => {
      ServiceWarehouse.value.push({
        value: item.id,
        label: item.name,
      });
    });
    disabledWarehouse();
  });
};
const GetTemplate = () => {
  let data = {
    size: 1000,
    current: 1,
    warehouseName:
      ServiceWarehouse.value.find(res => res.value == form.value.warehouseId)?.label || '',
  };
  // 重置模板
  form.value.templateId = '';
  PriceTemplate.value = [];
  $_WarehousePricingTemplate(data).then(res => {
    console.log(res, '可选的模板');
    if (res.data.code == 200) {
      if (res.data.data.records?.length) {
        res.data.data.records.forEach(item => {
          PriceTemplate.value.push({
            label: item.templateName,
            value: item.id,
          });
        });
        console.log(PriceTemplate.value, '模板');
      }
    }
  });
};
// 页面初始化
const onLoad = value => {
  let data = {
    current: details.page.currentPage,
    size: details.page.pageSize,
    warehouseId: WarehouseId.value,
    ...details.query,
    ...value,
  };
  details.loadingObj.list = true;
  $_ServiceProviderPrice(data)
    .then(res => {
      console.log(res, 'rsss');
      if (res.data.code == 200) {
        details.data = res.data.data.records || [];
        details.page.total = res.data.data.total; //页码
      }
    })
    .catch(error => {
      console.log(error);
    })
    .finally(() => {
      details.loadingObj.list = false;
    });
};
const Getdriver = async () => {
  if (form.value.warehouseId) {
    let data = {
      warehouseId: form.value.warehouseId,
    };
    await $_getDriverList(data).then(res => {
      console.log(res, '司机列表');
      if (res.data.code == 200) {
        if (res.data.data.length) {
          res.data.data.forEach(item => {
            driver.value.push({
              value: item.userId,
              label: item.name,
            });
          });
        }
      }
    });
  }
};
const PageOnload = async () => {
  await MyWarehouseList(); //获取仓库
  onLoad();
};
const AddInfo=()=>{
  ElMessage({
    message: '功能维护',
    type: 'warning',
  })
  return
}
//页面初始化方法
PageOnload();
// 价格配置提交
const Priceconfigurationsubmission = async () => {
  const _flag = await ruleFormRef.value.validate();
  if (!_flag) {
    return;
  }
  const categoryMap = new Map(details.data.map(item => [item.driverId, item]));
  //这里查找是否已经存在添加过的品类（只能查询当前页）
  if (categoryMap.has(form.value.driverId)) {
    ElMessage({
      message: '司机已经存在',
      type: 'warning',
    });
    return;
  }
  let data = {
    warehouseName:
      ServiceWarehouse.value.find(res => res.value == form.value.warehouseId)?.label || '', //仓库名称
    warehouseId: form.value.warehouseId, //仓库ID
    driverId: form.value.driverId, //司机ID
    driverName: driver.value.find(res => res.value == form.value.driverId)?.label || '', //司机名称
    templateId: form.value.templateId, //模板ID
  };
  tcloading.value = true;
  if (PriceconfigurationTitle.value == '价格配置(编辑)') {
    data.id = rowData.value.id;
    $_ServiceProviderPriceupdate(data)
      .then(res => {
        console.log(res, '提交成功');
        if (res.data.code == 200) {
          ElMessage({
            message: res.data.msg,
            type: 'success',
          });
          Priceconfiguration.value = false;
          onLoad();
        }
      })
      .catch(error => {
        console.log(error, '提交失败');
      })
      .finally(() => {
        tcloading.value = false;
      });
  } else {
    $_ServiceProviderPricesave(data)
      .then(res => {
        console.log(res, '提交成功');
        if (res.data.code == 200) {
          ElMessage({
            message: res.data.msg,
            type: 'success',
          });
          Priceconfiguration.value = false;
          onLoad();
        }
      })
      .catch(error => {
        console.log(error, '提交失败');
      })
      .finally(() => {
        tcloading.value = false;
      });
  }
};
// 新增
const Informationadd = () => {
  form.value.driverId = '';
  form.value.warehouseId = '';
  form.value.templateId = '';
  PriceTemplate.value = [];
  driver.value = [];
  Priceconfiguration.value = true;
  PriceconfigurationTitle.value = '价格配置(新增)';
};
// 服务仓事件
const changServiceWarehouse = () => {
  GetTemplate(); //获取可用模板
  Getdriver(); //获取司机
};
const EditTemplate = async row => {
  rowData.value = row;
  form.value.warehouseId = row.warehouseId; //仓库
  await Getdriver();
  console.log(row);
  Priceconfiguration.value = true;
  PriceconfigurationTitle.value = '价格配置(编辑)';
  form.value.driverId = row.driverId; //司机
  form.value.templateId = row.templateId;
  PriceTemplate.value = [
    {
      value: row.templateId,
      label: row.templateName,
    },
  ];
};
const deleteTemplate = row => {
  ElMessageBox.confirm('是否确认删除该数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      let data = {
        ids: row.id,
      };
      details.loadingObj.list = true;
      $_ServiceProviderPriceremove(data)
        .then(res => {
          console.log(res);
          if (res.data.code == 200) {
            onLoad();
          }
        })
        .catch(error => {
          console.log(error);
        })
        .finally(() => {
          details.loadingObj.list = false;
        });
    })
    .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;
  margin-bottom: 10px;
}
.avue-crud {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.el-fr-d {
  width: 100%;
  display: flex;
  justify-content: space-between;
  :deep(.el-btn) {
    margin-right: 0;
    width: 15%;
    align-items: flex-start;
    .el-form-item__content{
      justify-content: flex-end;
    }
  }
}
</style>
