<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-select
                filterable
                v-model="queryTop.clientId"
                multiple
                placeholder="请填写客户"
                style="min-width: 340px"
              >
                <el-option
                  v-for="item in dictList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item> -->
            <el-form-item label="租用仓库">
              <el-select
                filterable
                v-model="queryTop.warehouse"
                multiple
                placeholder="请选择仓库"
                :max-collapse-tags="2"
                style="min-width: 340px"
              >
                <el-option
                  v-for="item in warehouseList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </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><Plus /></el-icon>新增</el-button
            >
          </div>
          <!-- 头部右侧按钮模块 -->
          <div class="avue-crud__right">
            <el-button icon="Download" @click="handleExportData" circle></el-button>
            <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 === '操作'">
              <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 v-model="dialogCustomer" :title="Customertitle" width="46%">
      <el-form
        :model="form"
        label-width="auto"
        class="el_form_tc"
        :rules="rules"
        ref="ruleFormRef"
        v-loading="formloading"
        element-loading-text="Loading..."
      >
        <div class="el_div">
          <el-form-item label="客户名称" prop="clientId">
            <el-select
              filterable
              v-model="form.clientId"
              placeholder="请填写客户名称进行搜索"
              style="min-width: 340px"
              :remote-method="changeclientId"
              remote
              :loading="clientloading"
            >
              <el-option
                v-for="item in dictList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="租用仓库" prop="warehouseId">
          <el-select
            v-model="form.warehouseId"
            placeholder="请选择租用仓库"
            @change="changewarehouse"
          >
            <el-option
              v-for="item in warehouseList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 虚拟字段 -->
        <el-form-item label="剩余可租用面积(m²)">
          <el-input-number
            v-model="form.residualArea"
            :min="0"
            :controls="false"
            :precision="2"
            disabled
          />
        </el-form-item>

        <el-form-item label="客户租用类型">
          <el-select v-model="form.type" placeholder="请选择客户租用类型" @change="changetype">
            <el-option
              v-for="item in CustomerrentalList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户租用库位数" v-if="form.type == 2" prop="storageLocationCount">
          <el-input-number
            v-model="form.storageLocationCount"
            :min="0"
            :controls="false"
            @change="changestorageLocationCount"
            :value-on-clear="0"
            :precision="2"
          />
        </el-form-item>

        <el-form-item label="客户租用面积(m²)" prop="leasedArea">
          <el-input-number
            v-model="form.leasedArea"
            :disabled="form.type == 2"
            :min="0"
            :value-on-clear="0"
            :controls="false"
            :precision="2"
          />
        </el-form-item>

        <el-form-item label="月租金(元/月)" prop="monthlyRent">
          <el-input-number v-model="form.monthlyRent" :min="1" :controls="false" :precision="2" />
        </el-form-item>

        <el-form-item label="租赁合同时间" prop="LeasecontractDate">
          <el-date-picker
            v-model="form.LeasecontractDate"
            type="datetimerange"
            range-separator="-"
            start-placeholder="租赁合同开始时间"
            end-placeholder="租赁合同结束时间"
            :default-time="defaultTime2"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogCustomer = false">关闭</el-button>
          <el-button type="primary" @click="Customeradded">确认 </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/Warehouserentalmanagement.js';
import {
  $_getMyWarehouseList,
  $_Warehouserentalmanagement,
  $_listNameLike,
  $_residualArea,
  $_Warehouserentalmanagementsave,
  $_Warehouserentalmanagementremove,
  $_Warehouserentalmanagementupdate,
} from '@/api/storagecost/index.js';
import { getDictionaryBiz } from '@/api/system/dict'; //字典
import { processRowProperty, setNodeHeight } from '@/utils/util';
import functions from '@/utils/functions.js';
import { ElMessageBox, ElMessage } from 'element-plus';
import { downloadXls } from '@/utils/util';
import { useStore } from 'vuex';
import dayjs from 'dayjs';
import error from '@/error';
import { exportExcel } from '@/utils/exportData';
const $router = useRouter(); //跳转
const $useStore = useStore(); //权限
const $route = useRoute(); //获取地址栏参数
const queryTop = ref({});
const clientloading = ref(false);
const formloading = ref(false);
const DataRwo = ref({});
const ruleFormRef = ref(null);
const Customertitle = ref('客户租仓信息新增');
const dictList = ref([]); //客户
const form = ref({
  type: 2,
}); //表单
const dialogCustomer = ref(false); //弹窗
const warehouseList = ref([]);
const CustomerrentalList = ref([
  { label: '库位', value: 2 },
  { label: '面积', value: 1 },
]); //客户租用类型
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,
  recorddata,
  defaultTime2,
} = toRefs(details);
const rules = reactive({
  clientId: [{ required: true, message: '请填写客户名称', trigger: 'u' }],
  warehouseId: [{ required: true, message: '请选择租用仓库', trigger: 'change' }],
  monthlyRent: [{ required: true, message: '请选填写月租金', trigger: 'change' }],
  LeasecontractDate: [{ required: true, message: '请选择租赁合同时间', trigger: 'change' }],
  storageLocationCount: [{ required: true, message: '请输入客户租用数', trigger: 'change' }],
  leasedArea: [{ required: true, message: '请输入客户租用面积(m²)', trigger: 'change' }],
});
/** 展开列表控件 */
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];
  }
};

/** 表格表头输入框搜索 */
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 = () => {
  let data = {
    warehouseIds: queryTop.value.warehouse.join(','),
  };
  if (queryTop.value.warehouse?.length) {
    onLoad(data);
  }
};
// 每页多少条
const sizeChange = val => {
  details.page.pageSize = val;
  onLoad();
};
/** 页码改变执行的回调 */
const currentChange = val => {
  details.page.currentPage = val;
  onLoad();
};
// 刷新按钮
const searchChangeS = () => {
  details.search = false; //关闭搜索
};
const searchReset = () => {
  details.query = {};
  queryTop.value = {};
  details.data = [];
  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 changeclientId = value => {
  if (value) {
    let data = {
      name: value,
    };
    clientloading.value = true; //开启客户搜索加载
    $_listNameLike(data)
      .then(res => {
        console.log(res, '客户');
        if (res.data.code == 200 && res.data.data?.length) {
          res.data.data.forEach(item => {
            dictList.value.push({
              label: item.clientName,
              value: item.id,
            });
          });
        } else {
          dictList.value = [];
        }
      })
      .catch(error => {
        console.log(error);
      })
      .finally(() => {
        clientloading.value = false; //关闭客户搜索加载;
      });
  } else {
    dictList.value = [];
  }
};
// 查询客户

// 获取仓库
const MyWarehouseList = () => {
  $_getMyWarehouseList().then(res => {
    console.log(res, '仓库列表');
    res.data.data.forEach(item => {
      warehouseList.value.push({
        value: item.id,
        label: item.name,
      });
    });
  });
};
// 页面初始化
const onLoad = value => {
  let data = {
    current: details.page.currentPage,
    size: details.page.pageSize,
    ...details.query,
    ...value,
  };
  details.loadingObj.list = true;
  $_Warehouserentalmanagement(data)
    .then(res => {
      console.log(res, '初始化数据');
      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 PageOnload = () => {
  onLoad(); //获取列表参数
  MyWarehouseList(); //获取仓库
};

//页面初始化方法
PageOnload();
// 新增
const AddInfo = () => {
  dictList.value = [];
  form.value = {
    clientId: '', //客户名称ID
    warehouseId: '', //租用仓库ID
    leaseCommencementDate: '', //租赁合同开始时间
    leaseTerminationDate: '', //租赁合同结束时间
    monthlyRent: '', //月租金
    leasedArea: '', //客户租用面积
    type: 2, //租用类型
    storageLocationCount: '', //客户租用库位数
    residualArea: null, //剩余库位面积
    singleStorageArea: null, //单库位面积
  };
  Customertitle.value = '客户租仓信息新增';
  dialogCustomer.value = true; //开启弹窗
  ruleFormRef.value.resetFields();
};
// 客户租用类型计算
const changetype = () => {
  form.value.storageLocationCount = null; //客户租用库位数
  form.value.leasedArea = null; //客户租用库位数
};

const changewarehouse = async () => {
  let data = {
    warehouseId: form.value.warehouseId,
  };
  form.value.residualArea = null; //剩余库位面积
  form.value.singleStorageArea = null; //单库位面积
  formloading.value = true;
  await $_residualArea(data)
    .then(res => {
      console.log(res, '剩余可租用面积');
      if (res.data.code == 200) {
        const sope = res.data.data;
        if (sope.residualArea != null) {
          form.value.residualArea = Number(sope.residualArea); //剩余库位面积
        } else {
          form.value.residualArea = sope.residualArea;
          ElMessage({
            message: '请维护仓库基础资料',
            type: 'warning',
          });
          return;
        }
        if (sope.singleStorageArea != null) {
          form.value.singleStorageArea = Number(sope.singleStorageArea); //单库位面积
        } else {
          form.value.singleStorageArea = sope.singleStorageArea;
          ElMessage({
            message: '请维护仓库基础资料',
            type: 'warning',
          });
          return;
        }

        if (Customertitle.value == '客户租仓信息编辑') {
          form.value.leasedArea = Number(form.value.leasedArea);
          form.value.residualArea = form.value.residualArea + form.value.leasedArea; //剩余库位面积 //租用面积
        }
      }
    })
    .catch(error => {
      console.log(error);
    })
    .finally(() => {
      formloading.value = false;
    });
};

// 计算租用数面积
const changestorageLocationCount = () => {
  console.log(form.value.singleStorageArea, 'form.value.singleStorageArea');
  if (form.value.residualArea == null || form.value.singleStorageArea == null) {
    ElMessage({
      message: '请维护仓库基础资料',
      type: 'warning',
    });
    return;
  }

  // 租用库位数 *单库位面积 =客户租用面积
  form.value.leasedArea = form.value.storageLocationCount * form.value.singleStorageArea;
};
// 最后提交
const Customeradded = () => {
  ruleFormRef.value.validate(valid => {
    if (valid) {
      const { type, storageLocationCount, leasedArea } = form.value;

      if ((type === 1 && leasedArea == null) || (type === 2 && storageLocationCount == null)) {
        ElMessage({
          message: '请维护仓库基础资料',
          type: 'warning',
        });
        return;
      }

      if (form.value.type == 2 && form.value.leasedArea > form.value.residualArea) {
        ElMessage({
          message: '客户租用面积不能大于剩余可租用面积,请重新填写客户租用库位数',
          type: 'warning',
        });
        return;
      }

      if (form.value.type == 1 && form.value.leasedArea > form.value.residualArea) {
        ElMessage({
          message: '客户租用面积不能大于剩余可租用面积',
          type: 'warning',
        });
        return;
      }

      // clientId: '', //客户名称ID
      // warehouseId: '', //租用仓库ID
      // leaseCommencementDate: '', //租赁合同开始时间
      // leaseTerminationDate: '', //租赁合同结束时间
      // monthlyRent: '', //月租金
      // leasedArea: '', //客户租用面积
      // type: '', //租用类型
      // storageLocationCount: '', //客户租用库位数
      let data = {
        ...form.value,
      };
      data.leaseCommencementDate = data.LeasecontractDate[0];
      data.leaseTerminationDate = data.LeasecontractDate[1];
      console.log(data, '准备提交的数据');
      formloading.value = true;
      if (Customertitle.value == '客户租仓信息编辑') {
        data.id = DataRwo.value.id;
        $_Warehouserentalmanagementupdate(data)
          .then(res => {
            if (res.data.code == 200) {
              ElMessage({
                message: res.data.msg,
                type: 'success',
              });
              dialogCustomer.value = false;
              onLoad();
            }
          })
          .catch(error => {
            console.log(error);
          })
          .finally(() => {
            formloading.value = false;
          });
      } else {
        $_Warehouserentalmanagementsave(data)
          .then(res => {
            console.log(res, '新增');
            if (res.data.code == 200) {
              ElMessage({
                message: res.data.msg,
                type: 'success',
              });
              dialogCustomer.value = false;
              onLoad();
            }
          })
          .catch(error => {
            console.log(error);
          })
          .finally(() => {
            formloading.value = false;
          });
      }
    }
  });
};
// 编辑
const edit = row => {
  DataRwo.value = row;
  console.log(row);
  Customertitle.value = '客户租仓信息编辑';
  dialogCustomer.value = true;
  form.value.clientId = row.clientId; //客户名称ID
  dictList.value = [
    {
      label: row.clientName,
      value: row.clientId,
    },
  ];
  // 租用仓库
  form.value.warehouseId = row.warehouseId; //仓库
  form.value.type = row.type; //租用类型
  form.value.leasedArea = row.leasedArea; //租用面积
  form.value.storageLocationCount = row.storageLocationCount; //客户租用库位数
  form.value.monthlyRent = row.monthlyRent; //月租金
  changewarehouse(); //获取剩余可租用面积
  form.value.LeasecontractDate = [];
  form.value.LeasecontractDate[0] = row.leaseCommencementDate; //开始时间
  form.value.LeasecontractDate[1] = row.leaseTerminationDate; //结束时间
};
// 删除数据
const Viewdelete = rwo => {
  console.log(rwo);
  ElMessageBox.confirm('是否确认删除该数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      console.log(rwo);
      let data = {
        ids: rwo.id,
      };
      details.loadingObj.list = true;
      $_Warehouserentalmanagementremove(data)
        .then(res => {
          if (res.data.code == 200) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            });
            onLoad();
          }
        })
        .catch(error => {
          console.log(error);
        })
        .finally(() => {
          details.loadingObj.list = false;
        });
    })
    .catch(() => {});
};

/** 导出表格数据 */
const handleExportData = () => {
  exportExcel(details.columnList, details.data, '仓库租用 - ' + new Date().getTime());
};
</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;
  .el-btn {
    margin-right: 0;
  }
}
:deep(.el_form_tc) {
  display: flex;
  width: 100%;
  flex-wrap: wrap;
  justify-content: space-between;
  .el-select {
    width: 100%;
  }
  .el-input-number {
    width: 100%;
  }
  .el-form-item {
    width: 46%;
    margin-right: 0;
    .el-input {
      width: 100%;
    }
  }
  .el_div {
    width: 100%;
    .el-form-item {
      width: 100%;
    }
  }
}
</style>
