<template>
  <el-dialog
    top="5vh"
    :visible.sync="visible"
    :title="isView ? '查看库存余额表明细' : '选择库存余额表明细'"
    width="90vw"
  >
    <el-card shadow="never">
      <!-- 数据表格 -->
      <div>
        <el-form
          label-position="left"
          class="ele-form-search"
          :model="formData"
          :rules="rules"
          @keyup.enter.native="search"
          @submit.native.prevent
        >
          <el-row :gutter="15">
            <el-col :span="5">
              <el-form-item
                label-width="110px"
                label="库存余额编码:"
                prop="code"
              >
                <el-input
                  disabled
                  v-model="formData.code"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item
                label-width="110px"
                label="库存余额名称:"
                prop="name"
              >
                <el-input
                  :disabled="isView"
                  v-model="formData.name"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label-width="90px" label="起止时间:" prop="time">
                <el-date-picker
                  :disabled="isView"
                  style="width: 100%"
                  class="w100"
                  size="small"
                  v-model="formData.time"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label-width="60px" label="关键词:" prop="keyWord">
                <el-input
                  :disabled="isView"
                  v-model="formData.keyWord"
                  placeholder="请输入关键词"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col v-if="!isView" :span="3">
              <div class="ele-form-actions">
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  class="ele-btn-icon"
                  @click="search"
                  size="small"
                >
                  查询
                </el-button>
                <el-button
                  @click="reset"
                  icon="el-icon-refresh-left"
                  size="small"
                  type="primary"
                  >重置</el-button
                >
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <ele-pro-table
        ref="table"
        class="table"
        :needPage="!isView"
        :columns="columns"
        :datasource="datasource"
        height="calc(100vh - 405px)"
        full-height="calc(100vh - 116px)"
        tool-class="ele-toolbar-form"
        cache-key="systemOrgUserTable"
      >
        <!-- <template v-slot:toolbar="{ row }">
          <el-button
            size="small"
            type="primary"
            icon="el-icon-download"
            class="ele-btn-icon"
            @click="downLoad"
          >
            导出库存余额
          </el-button>
        </template> -->
      </ele-pro-table>
    </el-card>
    <div slot="footer" class="dialog-footer" style="margin-right: 2%">
      <el-button
        v-if="!isView"
        size="small"
        @click="downLoad"
        :loading="loading"
        type="primary"
        >提交并导出</el-button
      >
      <el-button v-else size="small" @click="visible = false" type="primary"
        >确定</el-button
      >
      <el-button size="small" @click="visible = false">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { getCode } from '@/api/codeManagement/index.js';
  import ItemSearch from './components/item-search.vue';
  import {
    exportStockExcel,
    getStockPage
  } from '@/api/warehouseManagement/statisticalReports';

  export default {
    components: { ItemSearch },
    data() {
      return {
        loading: false,
        isView: false,
        formData: {
          code: '',
          name: '',
          time: [],
          keyWord: ''
        },
        // 表单验证规则
        rules: {
          name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
          time: [
            { required: true, message: '请选择起止时间', trigger: 'change' }
          ]
        },
        pickerOptions: {
          shortcuts: [
            {
              text: '最近一周',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '最近一个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '最近三个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '最近一年',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
                picker.$emit('pick', [start, end]);
              }
            }
          ]
        },
        visible: false
      };
    },
    computed: {
      // 表格列配置
      columns() {
        let arr = [
          {
            columnKey: 'index',
            type: 'index',
            width: 50,
            align: 'center',
            label: '序号',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'warehouseName',
            label: '仓库名称',
            align: 'center'
          },
          {
            prop: 'categoryCode',
            label: '物品编码',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'categoryName',
            label: '物品名称',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'brandNum',
            label: '牌号',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'categoryModel',
            label: '型号',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'specification',
            label: '规格',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'measureQuantity',
            label: '计量数量',
            sortable: 'custom',
            showOverflowTooltip: true,
            width: 130,
            align: 'center'
          },
          {
            prop: 'measureUnit',
            label: '计量单位',
            align: 'center'
          },
          {
            prop: 'startTime',
            label: '统计时间',
            align: 'center'
          }
        ];
        return arr.filter((item) => item != '');
      },
      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      }
    },
    methods: {
      // 获取时间函数
      getDate(date) {
        console.log(date);
        let obj = {
          year: date.getFullYear(), //获取完整的年份(4位)
          month: date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
          strDate: date.getDate() // 获取当前日(1-31)
        };
        Object.keys(obj).forEach((key) => {
          if (obj[key] < 10) obj[key] = `0${obj[key]}`;
        });
        return `${obj.year}-${obj.month}-${obj.strDate}`;
      },
      downLoad() {
        if (!this.formData.name) {
          return this.$message.error('请输入名称');
        }
        if (!this.formData.time) {
          return this.$message.error('请选择时间');
        }
        this.loading = true;
        const params = Object.assign({}, this.formData);
        if (params.time?.length) {
          params.startTime = params.time[0];
          params.endTime = params.time[1];
        }
        delete params.time;
        exportStockExcel(params).then((data) => {
          try {
            let objectUrl1 = window.URL.createObjectURL(new Blob([data]));
            let elink = document.createElement('a');
            elink.setAttribute(
              'download',
              decodeURI(decodeURI('库存余额.xlsx'))
            );
            elink.style.display = 'none';
            elink.href = objectUrl1;
            document.body.appendChild(elink);
            elink.click();
            document.body.removeChild(elink);
            window.URL.revokeObjectURL(elink.href);
            this.loading = false;
            this.visible = false;
            this.$emit('reload');
          } catch (err) {
            this.$message.error('导出失败,请联系管理员!');
          }
        });
      },
      async open(isView, row) {
        console.log(row);
        if (isView) {
          this.tableList = row.info.map((item) => {
            return {
              ...item,
              startTime: this.getDate(new Date(Number(item.startTime)))
            };
          });
          this.formData.code = row.code;
          this.formData.name = row.name;
          this.formData.time =
            row.startTime && row.endTime ? [row.startTime, row.endTime] : [];
          this.formData.keyWord = row.keyWord;
        } else {
          this.tableList = [];
          this.formData = {
            code: await getCode('statistics_log_code'),
            name: '',
            time: [],
            keyWord: ''
          };
        }
        this.isView = isView;
        this.visible = true;
        this.$nextTick(() => {
          this.$refs.table.reload();
        });
      },
      /* 表格数据源 */
      async datasource({ page, limit, where, order }) {
        if (this.isView) {
          return this.tableList;
        } else {
          const params = Object.assign({}, this.formData);
          if (params.time?.length) {
            params.startTime = params.time[0];
            params.endTime = params.time[1];
          }
          delete params.time;
          const data = await getStockPage({
            ...params,
            ...where,
            ...order,
            pageNum: page,
            size: limit
          });
          console.log(data);
          this.tableList = data;
          return data;
        }
      },
      search() {
        this.$refs.table.reload();
      },
      reset() {
        this.formData.time = [];
        this.formData.keyWord = '';
        this.search();
      }
    }
  };
</script>
<style lang="scss" scoped>
  #inventoryBalance {
    height: 100%;
    width: 100%;
    padding: 10px;
    box-sizing: border-box;
    .ele-form-actions {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>
