<template>
  <div>
    <en-table-layout :tableData="tableData.data" :loading="loading" @selection-change="handleSelectionChange">
      <template #toolbar>
        <div class="inner-toolbar w-11/12 flex justify-between">
          <div class="toolbar-btns">
            <el-button size="mini" v-if="checkPermission(['goodsLend:add'])" type="primary" @click="handleAddGoodsLend">新增</el-button>
            <el-button
              type="success"
              size="mini"
              v-if="checkPermission(['goodsLend:confirm'])"
              @click="handleConfirmGoodsLend"
              :disabled="multipleSelection.length === 0"
              >打印</el-button
            >
          </div>
          <div class="toolbar-search">
            <en-table-search @search="searchEvent" @advancedSearch="advancedSearchEvent" placeholder="请输入仓库编号" advanced advancedWidth="465">
              <template #advanced-content>
                <el-form ref="advancedForm" :model="advancedForm" label-width="90px">
                  <el-form-item label="仓库">
                    <el-cascader
                      v-model="advancedForm.dept_id"
                      :options="warehouseList"
                      :props="{
                        label: 'name',
                        value: 'id',
                        emitPath: false,
                        checkStrictly: true,
                      }"
                      clearable
                    ></el-cascader>
                  </el-form-item>
                  <el-form-item label="状态">
                    <el-select v-model="advancedForm.status" clearable>
                      <el-option key="NEW" label="新创建" value="NEW" />
                      <el-option key="CONFIRMED" label="已确认" value="CONFIRMED" />
                      <el-option key="RETURNED" label="已归还" value="RETURNED" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="时间">
                    <el-date-picker
                      v-model="advancedForm.goodsLend_time_range"
                      type="daterange"
                      align="center"
                      :editable="false"
                      unlink-panels
                      :clearable="true"
                      :default-time="['00:00:00', '23:59:59']"
                      range-separator="-"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="timestamp"
                      :picker-options="{
                        disabledDate(time) {
                          return time.getTime() - 1 >= new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime() + 86400000 - 1;
                        },
                        shortcuts: MixinPickerShortcuts,
                      }"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-form>
              </template>
            </en-table-search>
          </div>
        </div>
      </template>

      <template #table-columns>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="warehouse.sn" label="仓库编号"></el-table-column>
        <el-table-column prop="warehouse.name" label="仓库名称"></el-table-column>
        <el-table-column prop="code" label="库位号" />
        <el-table-column prop="type" label="库位区域">
          <template #default="scope">{{ statusFilter(scope.row.type) }}</template>
        </el-table-column>
        <el-table-column prop="bind_num" label="已绑定SKU数" />
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <!-- <el-button size="mini" v-if="checkPermission(['inventoryItem'])" @click="introGoodsLend(scope.row)">查看</el-button>
            <el-button size="mini" v-if="checkPermission(['bindAreaStock:update'])" @click="AddGoodsLend(scope.row)">绑定商品</el-button> -->
            <el-button size="mini" v-if="checkPermission(['goodsLend:edit'])" @click="handleEditGoodsLend(scope.row)">编辑</el-button>
            <el-button type="success" size="mini" style="margin-top: 5px" v-if="checkPermission(['goodsLend:del'])" @click="handleReturnGoodsLend(scope.row)"
              >删除</el-button
            >
            <el-button type="primary" size="mini" style="margin-top: 5px" @click="handlePrintGoodsLendDialog(scope.row)">打印</el-button>
          </template>
        </el-table-column>
      </template>

      <template #pagination>
        <el-pagination
          v-if="tableData"
          @size-change="handlePageSizeChange"
          @current-change="handlePageCurrentChange"
          :current-page="tableData.page_no"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="tableData.page_size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.data_total"
        >
        </el-pagination>
      </template>
    </en-table-layout>

    <el-dialog title="打印预览" v-model:visible="dialogVisible" width="940px" center @close="handleCancle">
      <el-button size="mini" type="primary" @click="handlePrintGoodsLend" class="print">打印</el-button>
      <div id="deliverySheet" style="width: 900px">
        <div class="tips-t" v-for="(item, index) in codeList" :key="index">
          <div>
            <barcode :value="item" height="20" format="CODE128" fontSize="20"></barcode>
          </div>
        </div>
      </div>
    </el-dialog>
    <el-dialog :title="title" v-model="dialogVisibleForm" width="940px" center @close="addHandleCancle" style="width: 30%; border-radius: 10px">
      <el-form :model="addLendForm" ref="addLendFormRef" :rules="rules" label-width="90px">
        <el-form-item label="仓库" prop="warehouse_id">
          <el-select v-model="addLendForm.warehouse_id" clearable @change="selWarehouse">
            <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <span style="color: red; margin-left: 20px; cursor: pointer; text-decoration: underline" v-if="warehouseList.length == 0" @click="gowareHouse"
            >新增仓库</span
          >
        </el-form-item>
        <el-form-item label="库位区域" prop="type">
          <el-select v-model="addLendForm.type" clearable @change="selAreaTableData">
            <el-option v-for="item in AreaTableData" :key="item.id" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="库位号" prop="code">
          <el-input v-model="addLendForm.code" maxlength="12" placeholder="请输入库位号" style="width: 270px">
            <template #prepend>{{ warehouseSn }}-{{ AreaTab }}</template>
          </el-input>
        </el-form-item>
        <el-form-item label="库位说明">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入内容" v-model="addLendForm.intro"> </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addHandleCancle">取 消</el-button>
        <el-button type="primary" @click="lendCommit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import * as API_GoodsLend from '@/api/goodsLend';
import Print from 'print-js';
import * as API_Setting from '@/api/setting';
import { useRouter, useRoute } from 'vue-router';
import QRCode from 'qrcode';
/* import EnTableLayout from '@/components/TableLayout/index.vue';
import EnTableSearch from '@/components/TableSearch/index.vue'; */
import { ElMessageBox, ElMessage } from 'element-plus';
import { useStore } from 'vuex';
const store = useStore();

const router = useRouter();
const route = useRoute();

const warehouseSn = ref('');
const warehouseList = ref([]);
const loading = ref(false);
const params = reactive({
  page_no: 1,
  page_size: 10,
  company_id: store.state.companId,
});
const advancedForm = reactive({});
const tableData = ref('');
const dialogVisible = ref(false);
const multipleSelection = ref([]);
const goodsLendForm = reactive({});
const codeList = ref([]);
const title = ref('');
const dialogVisibleForm = ref(false);
const addLendForm = reactive({
  warehouse_id: '',
  type: '',
  code: '',
  intro: '',
});

const rules = reactive({
  warehouse_id: [{ required: true, message: '请选择仓库', trigger: 'change' }],
  name: [{ required: true, message: '请选择输入仓库名称', trigger: 'blur' }],
  code: [{ required: true, message: '请选择输入库位号', trigger: 'blur' }],
  type: [{ required: true, message: '请选择仓库类型', trigger: 'change' }],
});
const typeList = ref([]);
const AreaTableData = ref([]);
const AreaTab = ref('');

const GET_GoodsLendList = () => {
  loading.value = true;
  API_GoodsLend.query(params)
    .then((response) => {
      loading.value = false;
      tableData.value = response;
    })
    .catch(() => {
      loading.value = false;
    });
};

onMounted(() => {
  GET_GoodsLendList();
  GET_DeptList();
});

watch(
  route,
  (newVal) => {
    if (newVal.query.status) {
      params.status = newVal.query.status;
      advancedForm.status = newVal.query.status;
    }
    params.page_no = 1;
    GET_GoodsLendList();
  },
  { immediate: true }
);

const introGoodsLend = (row) => {
  router.push({
    name: 'inventoryItem',
    params: { id: row.id, type: 'check', code: row.code },
  });
};

const AddGoodsLend = (row) => {
  router.push({
    name: 'bindAreaStock',
    params: { id: row.id, warehouse_id: row.warehouse_id, code: row.code },
  });
};

const gowareHouse = () => {
  dialogVisibleForm.value = false;
  router.push({ name: 'warehouseList' });
};

const selWarehouse = (val) => {
  const list = warehouseList.value.filter((el) => el.id === val);
  let obj = list[0];
  warehouseSn.value = obj.sn;
};

const selAreaTableData = (val) => {
  const list = AreaTableData.value.filter((el) => el.code === val);
  let obj = list[0];
  AreaTab.value = obj.code;
};

const lendCommit = () => {
  console.log(addLendForm);
  addLendForm.code = warehouseSn.value +'-'+ addLendForm.type + '-' + addLendForm.code;

  if (title.value === '新增') {
    API_GoodsLend.create(addLendForm).then(() => {
      ElMessage.success('添加成功!');
      dialogVisibleForm.value = false;
      warehouseSn.value = '';
      addLendForm.value = {};
      GET_GoodsLendList();
    });
  } else if (title.value === '编辑') {
    API_GoodsLend.update(addLendForm).then(() => {
      ElMessage.success('修改成功!');
      dialogVisibleForm.value = false;
      addLendForm.value = {};
      GET_GoodsLendList();
    });
  }
};

const addHandleCancle = () => {
  dialogVisibleForm.value = false;
};

const handleCancle = () => {
  dialogVisible.value = false;
  codeList.value = [];
};

const creatQrCode = () => {
  nextTick(() => {
    codeList.value.forEach((item, index) => {
      document.getElementById(`codeItem${index}`).innerHTML = '';
      new QRCode(document.getElementById(`codeItem${index}`), {
        text: item,
        width: 600,
        height: 660,
        render: 'table',
        colorDark: '#333333',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H,
      });
    });
  });
};

const handleEditGoodsLend = (row) => {
  title.value = '编辑';
  const str = row.code;
  warehouseSn.value = str.split('-')[0];
  AreaTab.value = str.split('-')[1];
  // 使用 Object.assign 或者手动赋值来更新 reactive 对象的属性
  Object.assign(addLendForm, row);
  console.log(warehouseSn.value,AreaTab.value);
  addLendForm.code = str.split('-').pop();

  dialogVisibleForm.value = true;
};

const handleReturnGoodsLend = (row) => {
  ElMessageBox.confirm('确定要删除吗？', '提示', { type: 'warning' })
    .then(() => {
      API_GoodsLend.deletes({ id: row.id }).then(() => {
        ElMessage.success('删除成功！');
        GET_GoodsLendList();
      });
    })
    .catch(() => {});
};

const statusFilter = (val) => {
  const obj = AreaTableData.value.filter((el) => el.code === val);
  return obj.length !== 0 ? obj[0].name : '';
};

const handleConfirmGoodsLend = () => {
  if (!multipleSelection.value.length) return ElMessage.error('请先选择！');
  const ids = multipleSelection.value.map((item) => item.code);
  codeList.value = ids;
  dialogVisible.value = true;
  creatQrCode();
};

const GET_DeptList = () => {
  API_Setting.getListAll().then((response) => {
    warehouseList.value = response;
  });
  API_Setting.getPage({
    dictType: 'Warehouse_location_type',
    page_no: 1,
    page_size: 1,
    page_size: 50,
  }).then((res) => {
    typeList.value = res.data;
  });
  API_GoodsLend.getListAreaType({ page_no: 1,
  page_size: 100,
  company_id: store.state.companId,})
    .then((response) => {
      loading.value = false;
      AreaTableData.value = response;
    })
    .catch(() => {
      loading.value = false;
    });
};

const handlePrintGoodsLend = () => {
  Print({
    printable: 'deliverySheet',
    type: 'html',
    targetStyles: ['*'],
    ignoreElements: ['no-logs', 'goods-image', 'no-btn', 'elementToIgnore'],
  });
};

const handleDeleteGoodsLend = () => {
  if (!multipleSelection.value.length) return ElMessage.error('请先选择！');
  ElMessageBox.confirm('确定要删除这些借出单吗？', '提示', { type: 'warning' })
    .then(() => {
      const ids = multipleSelection.value.map((item) => item.id);
      API_GoodsLend.deleteGoodsLend(ids).then(() => {
        ElMessage.success('删除成功！');
        GET_GoodsLendList();
      });
    })
    .catch(() => {});
};

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const handlePageSizeChange = (size) => {
  params.page_size = size;
  GET_GoodsLendList();
};

const handlePageCurrentChange = (page) => {
  params.page_no = page;
  GET_GoodsLendList();
};

const handleAddGoodsLend = () => {
  title.value = '新增';
  dialogVisibleForm.value = true;
};

const handlePrintGoodsLendDialog = (row) => {
  dialogVisible.value = true;
  codeList.value.push(row.code);
  creatQrCode();
};

const GET_GoodsLendDetail = (id) => {
  API_GoodsLend.getGoodsLendInfo(id).then((response) => {
    goodsLendForm.value = response;
    if (response.product_list && response.product_list.length) {
      var str = '';
      response.product_list.forEach(function (i) {
        str += i.product_name + '、';
      });
    }
    goodsLendForm.value.illustrate = str;
  });
};

const searchEvent = (data) => {
  params.sn = data;
  Object.keys(advancedForm).forEach((key) => delete params[key]);
  params.page_no = 1;
  GET_GoodsLendList();
};

const advancedSearchEvent = () => {
  Object.assign(params, advancedForm);
  delete params.start_time;
  delete params.end_time;
  if (advancedForm.goodsLend_time_range) {
    params.start_time = parseInt(Number(advancedForm.goodsLend_time_range[0]) / 1000);
    params.end_time = parseInt(Number(advancedForm.goodsLend_time_range[1]) / 1000);
  }
  delete params.goodsLend_time_range;
  params.page_no = 1;
  GET_GoodsLendList();
};
</script>