<template>
  <div class="p-3 bg-white">
    <!-- <template #toolbar> -->
    <div class="inner-toolbar w-11/12">
      <div class="toolbar-search dark:!bg-[#060818]">
        <en-table-search class="!justify-start" @search="searchEvent" :placeholder="$t('place')"> </en-table-search>
      </div>
      <div class="toolbar-btns mt-5 mb-4">
        <el-button size="small" v-if="store.state.user.user.founder !== 1" type="primary" @click="handleAddGoodsLend">{{ $t('overseasWarehouseAuth') }}</el-button>
      </div>
    </div>
    <!--  </template> -->
    <en-table-layout :tableData="tableData.data" :toolbar="false" :loading="loading" @selection-change="handleSelectionChange">
      <template #table-columns>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="warehouse.sn" :label="$t('warechouse_sn')"></el-table-column>
        <el-table-column class="dark:!bg-[#060818]" prop="warehouse.name" :label="$t('warechouse_name')"></el-table-column>
        <el-table-column prop="code" :label="$t('warechouse_code')" />
        <el-table-column prop="type" :label="$t('warechouse_area')">
          <template #default="scope">{{ statusFilter(scope.row.type) }}</template>
        </el-table-column>
        <el-table-column prop="bind_num" :label="$t('warechouse_sku')" />
        <el-table-column :label="$t('operate')" fixed="right" width="300">
          <template #default="scope">
            <el-button size="small" v-if="store.state.user.user.founder !== 1" @click="handleEditGoodsLend(scope.row)">{{ $t('edit') }}</el-button>
            <el-button
              type="success"
              size="small"
              style="margin-top: 5px"
              v-if="store.state.user.user.founder !== 1"
              @click="handleReturnGoodsLend(scope.row)"
              >{{ $t('delete') }}</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="$t('print')" v-model="dialogVisible" width="940px" center @close="handleCancle">
      <el-button size="small" type="primary" @click="handlePrintGoodsLend" class="print">{{ $t('print') }}</el-button>
      <div id="deliverySheet" style="width: 900px">
        <div class="tips-t" v-for="(item, index) in codeList" :key="index">
          <div>
          </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="$t('warechouse')" 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>
        </el-form-item>
        <el-form-item :label="$t('warechouse_area')" 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="$t('warechouse_code')" prop="code">
          <el-input v-model="addLendForm.code" maxlength="12" :placeholder="$t('place') + $t('warechouse_code')" style="width: 270px">
            <template #prepend>{{ warehouseSn }}-{{ AreaTab }}</template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('location_notes')">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" :placeholder="$t('place') + $t('location_notes')" v-model="addLendForm.intro">
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addHandleCancle">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="lendCommit">{{ $t('submit') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script lang="ts" setup>
import { ref, reactive, onMounted, watch, nextTick } 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';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
const store = useStore();

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

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

const rules = ref<any>({
  warehouse_id: [{ required: true, message: t('change') + t('warechouse_code'), trigger: 'change' }],
  name: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入库位号', trigger: 'blur' }],
  type: [{ required: true, message: t('change') + t('warechouse_area'), trigger: 'change' }],
});
const typeList = ref<any>([]);
const AreaTableData = ref<any>([]);
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.value.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 addLendFormRef = ref();
const lendCommit = () => {
  addLendForm.value.code = warehouseSn.value + '-' + addLendForm.value.type + '-' + addLendForm.value.code;
  addLendFormRef.value.validate((valid) => {
    if (valid) {
      if (!id.value) {
        API_GoodsLend.create(addLendForm.value).then(() => {
          ElMessage.success(t('add_success'));
          dialogVisibleForm.value = false;
          warehouseSn.value = '';
          addLendForm.value = {};
          GET_GoodsLendList();
        });
      } else {
        API_GoodsLend.update(addLendForm.value).then(() => {
          ElMessage.success(t('edit_success'));
          dialogVisibleForm.value = false;
          addLendForm.value = {};
          GET_GoodsLendList();
        });
      }
    } else {
      ElMessage.error(t('form_erroe'));
      return false;
    }
  });
};

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 id = ref('');
const handleEditGoodsLend = (row) => {
  id.value = row.id;
  title.value = t('edit');
  const str = row.code;
  warehouseSn.value = str.split('-')[0];
  AreaTab.value = str.split('-')[1];
  // 使用 Object.assign 或者手动赋值来更新 reactive 对象的属性
  /* Object.assign(addLendForm, row); */
  addLendForm.value = row;
  addLendForm.value.code = str.split('-').pop();

  dialogVisibleForm.value = true;
};

const handleReturnGoodsLend = (row) => {
  ElMessageBox.confirm(t('del_info'), t('prompt'), { type: 'warning' })
    .then(() => {
      API_GoodsLend.deletes({ id: row.id }).then(() => {
        ElMessage.success(t('del_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: any) => 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: 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 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 = () => {
  id.value = '';
  title.value = t('add');
  addLendForm.value = {};
  warehouseSn.value = '';
  AreaTab.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);
  params.page_no = 1;
  GET_GoodsLendList();
};
</script>