<template>
  <div class="dark:!bg-[#060818] bg-white p-3">
    <en-table-layout :tableData="tableData" :loading="loading" @selection-change="handleSelectionChange">
      <template #toolbar>
        <div class="inner-toolbar">
          <div class="toolbar-btns">
            <!-- checkPermission(['createAreaType:add'])&& -->
            <el-button size="small" v-if="store.state.user.user.founder !== 1" type="primary" @click="handleAddGoodsLend">{{ $t('add') }}</el-button>
          </div>
          <div class="toolbar-search"></div>
        </div>
      </template>

      <template #table-columns>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="code" :label="$t('location_code')"/>
        <el-table-column prop="name" :label="$t('location_name')"/>
        <el-table-column prop="remark" :label="$t('notes')"/>
        <el-table-column :label="$t('operate')" fixed="right" width="300">
          <template #default="scope"
            ><!-- checkPermission(['updateAreaType:update'])&& -->
            <el-button size="small" v-if="store.state.user.user.founder !== 1" @click="handleEditGoodsLend(scope.row)">{{ $t('edit') }}</el-button
            ><!-- checkPermission(['removeAreaType:delete'])&& -->
            <el-button type="danger" size="small" v-if="store.state.user.user.founder !== 1" @click="handleReturnGoodsLend(scope.row)">{{
              $t('delete')
            }}</el-button>
          </template>
        </el-table-column>
      </template>
    </en-table-layout>
    <el-dialog :title="title" v-model="dialogVisibleForm" width="30%" center @close="addHandleCancle" class="!rounded-lg">
      <el-form ref="addLendFormRef" :model="addLendForm" :rules="rules" label-width="120px">
        <el-form-item :label="$t('location_code')" prop="code">
          <el-input :placeholder="$t('place') + $t('location_code')" v-model="addLendForm.code" />
        </el-form-item>
        <el-form-item :label="$t('location_name')" prop="name">
          <el-input :placeholder="$t('place') + $t('location_name')" v-model="addLendForm.name" />
        </el-form-item>
        <el-form-item :label="$t('notes')">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" :placeholder="$t('place') + $t('notes')" v-model="addLendForm.remark" />
        </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, getCurrentInstance } from 'vue';
import { ElMessageBox, FormInstance, ElMessage } from 'element-plus';
import * as API_GoodsLend from '@/api/goodsLend';
import * as API_Setting from '@/api/setting';
import { useStore } from 'vuex';
/* import Print from 'print-js';
import QRCode from 'qrcodejs2'; */
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

const store = useStore();
const instance = getCurrentInstance();
const proxy = instance?.proxy as any; // 类型断言
const checkPermission = (value: string[]): boolean => {
  return proxy.checkPermission(value);
};

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 = ref<any>({});
const codeList = ref<any>([]);
const title = ref('');
const dialogVisibleForm = ref(false);
let addLendForm = ref<any>({
  name: '',
  remark: '',
  code: '',
});
const rules = reactive({
  name: [{ required: true, message: t('place') + t('location_code'), trigger: 'blur' }],
  code: [{ required: true, message: t('place') + t('location_name'), trigger: 'blur' }],
});
const typeList = ref([]);
const id = ref('');
const addLendFormRef = ref();

const lendCommit = () => {
  addLendFormRef.value.validate((valid) => {
    if (valid) {
      if (!id.value) {
        console.log(id.value);
        // addLendForm.value.code = warehouseSn.value + '-' + addLendForm.value.code;
        API_GoodsLend.addCreateAreaType(addLendForm.value).then(() => {
          ElMessage.success(t('add_success'));
          dialogVisibleForm.value = false;
          warehouseSn.value = '';
          addLendForm.value.name = '';
          addLendForm.value.remark = '';
          GET_GoodsLendList();
        });
      } else {
        API_GoodsLend.editUpdateAreaType(id.value, addLendForm.value).then(() => {
          ElMessage.success(t('edit_success'));
          dialogVisibleForm.value = false;
          id.value = '';
          addLendForm.value.name = '';
          addLendForm.value.remark = '';
          GET_GoodsLendList();
        });
      }
    } else {
      ElMessage.error(t('form_erroe'));
      return false;
    }
  });
};

const addHandleCancle = () => {
  dialogVisibleForm.value = false;
  addLendForm.value.name = '';
  addLendForm.value.remark = '';
};

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

/* const creatQrCode = () => {
  nextTick(() => {
    codeList.value.forEach((item, index) => {
      const codeItem = document.querySelectorAll('.code-item')[index];
      codeItem.innerHTML = '';
      new QRCode(codeItem, {
        text: item,
        width: 600,
        height: 660,
        render: 'table',
        colorDark: '#333333',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H,
      });
    });
  });
}; */

const handleEditGoodsLend = (row) => {
  id.value = row.id;
  title.value = t('edit');
  addLendForm.value.code = row.code;
  addLendForm.value.name = row.name;
  addLendForm.value.remark = row.remark;
  dialogVisibleForm.value = true;
};

const handleReturnGoodsLend = (row) => {
  ElMessageBox.confirm(t('del_info'), t('prompt'), { type: 'warning' })
    .then(() => {
      API_GoodsLend.removeAreaType(row.id).then(() => {
        ElMessage.success(t('del_success'));
        GET_GoodsLendList();
      });
    })
    .catch(() => {});
};

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


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;
  });
};

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 = {};
  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) {
      let str = '';
      response.product_list.forEach((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();
}; */

const GET_GoodsLendList = () => {
  loading.value = true;
  API_GoodsLend.getListAreaType(params)
    .then((response) => {
      loading.value = false;
      tableData.value = response;
    })
    .catch(() => {
      loading.value = false;
    });
};
onMounted(() => {
  GET_GoodsLendList();
  GET_DeptList();
});
</script>
  
  <style scoped>
.print {
  margin-left: 790px;
}

.tips-t {
  display: flex;
  padding: 10px 0;
}
.tips-t div {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.tips-f {
  padding: 20px 0;
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

::v-deep .el-dialog__body {
  padding: 10px 20px;
}

::v-deep .el-form .el-form-item__content {
  display: flex;
}
</style>