<template>
  <div v-loading="loading" element-loading-text="图片上传中。。。">
    <!-- 头部 -->
    <div class="QueryInvoice" style="margin: 10px 15px">
      <el-row :gutter="30">
        <el-col :span="30">
          <el-form :inline="true" :model="invoiceQruey">
            <el-form-item label="发票号码" style="margin-left">
              <el-input v-model="invoiceQruey.number" placeholder="发票号码"></el-input>
            </el-form-item>
            <el-form-item label="发票代码">
              <el-input v-model="invoiceQruey.code" placeholder="发票代码"></el-input>
            </el-form-item>
            <el-form-item label="发票类型">
              <el-select v-model="invoiceQruey.category" placeholder="请选择">
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.value"
                  :label="item.category"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="发票类别">
              <el-select v-model="invoiceQruey.type" placeholder="请选择">
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.type"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="发票状态">
              <el-select v-model="invoiceQruey.status" placeholder="请选择">
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.status"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="12" style="margin: 20px 5px">
          <el-button
            type="primary"
            icon="el-icon-search"
            style="margin: 1px 5px"
            @click="selectexpend()"
          >查询</el-button>
          <el-button type="info" icon="el-icon-refresh-right" @click="upddlist()">重置</el-button>
          <el-button
            type="success"
            icon="el-icon-download"
            v-if="isgetid"
            @click="Reimbursement()"
          >添加发票单</el-button>
          <el-button type="warning" v-if="!isgetid" @click="Reimbursement()">返回</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 表格区域 -->
    <div class="drawer" v-show="isgetid" style="margin-left: 15px">
      <el-table
        :data="invoicegetList"
        border
        style="width: 99%"
        :cell-style="{ 'text-align': 'center' }"
        :header-cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column label="序号" width="50" style>
          <template slot-scope="scope">
            {{
            (invoiceQruey.pageNum - 1) * invoiceQruey.pageSize +
            scope.$index +
            1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="code" label="发票代码"></el-table-column>
        <el-table-column prop="number" label="发票号码" width="width"></el-table-column>
        <el-table-column prop="time" label="发票时间" :formatter="getFroms"></el-table-column>
        <el-table-column prop="category" label="发票类型">
          <template slot-scope="scope">
            <el-tag :type="scope.row.category == '0' ? 'info' : 'primary'">
              {{
              scope.row.category == "0" ? "普票" : "专票"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="发票类别">
          <template slot-scope="scope">
            <el-tag
              :type="
                scope.row.type == '0'
                  ? 'success'
                  : scope.row.type == '1'
                  ? 'danger'
                  : 'warning'
              "
            >
              {{
              scope.row.type == "0"
              ? "收入"
              : scope.row.type == "1"
              ? "支出"
              : "报销"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="mone" label="发票金额"></el-table-column>
        <el-table-column prop="prop" label="发票文件" width="120px">
          <template slot-scope="scope">
            <div v-if="formatProtocolType(scope.row)">
              <el-image
                style="width: 80px; height: 80px"
                :src="scope.row.fileUrl"
                :preview-src-list="srcList"
              ></el-image>
            </div>
            <div v-else>
              <a class="a-style" @click="handlePreView(scope.row)">点击查看文件</a>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="发票状态" width="90px">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status == '0' ? 'info' : 'warning'">
              {{
              scope.row.status == 0 ? "未报销" : "已报销"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="prop" label="操作">
          <template slot-scope="scope">
            <el-popover placement="top" width="160" v-model="scope.row.visible">
              <p>确定要删除当前发票吗</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="scope.row.visible = false">取消</el-button>
                <el-button type="primary" size="mini" @click="YesGet(scope.row)">确定</el-button>
              </div>
              <el-button
                type="danger"
                icon="el-icon-delete"
                slot="reference"
                size="mini"
                :disabled="scope.row.status == 0 ? false : true"
              ></el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <el-row :gutter="20">
        <el-col :span="24">
          <!-- 分页 -->
          <div class="foot_yi">
            <el-pagination
              @current-change="handleCurrentChange"
              layout="total, prev, pager, next"
              :total="total"
              :current-page.sync="invoiceQruey.pageNum"
              :page-size="invoiceQruey.pageSize"
            ></el-pagination>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 添加区域 -->
    <div class="getadd" v-show="!isgetid" style="margin-left: 5%">
      <el-row >
        <el-col :xl="8" :lg="10" :md="8" :sm="12" :xs="24">
          <el-form
            style="width: 100%; margin: 30px 0px"
            :model="addTO"
            :rules="rules"
            ref="addTO"
            label-width="80px"
            class="demo-ruleForm"
          >
            <el-form-item label="发票代码" prop="code">
              <el-input
                v-model="addTO.code"
                maxlength="12"
                minlength="12"
                onkeyup="this.value=this.value.replace(/\D|^/g,'')"
              ></el-input>
            </el-form-item>
            <el-form-item label="发票号码" prop="number">
              <el-input
                v-model="addTO.number"
                maxlength="8"
                minlength="8"
                onkeyup="this.value=this.value.replace(/\D|^/g,'')"
              ></el-input>
            </el-form-item>
            <el-form-item label="发票时间" required prop="time">
              <el-date-picker
                v-model="addTO.time"
                type="datetime"
                placeholder="选择日期时间"
                @change="timestampToTime1()"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="发票类型" prop="category">
              <el-select v-model="addTO.category" placeholder="请选择">
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.value"
                  :label="item.category"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="发票类别" prop="type">
              <el-select v-model="addTO.type" placeholder="请选择">
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.type"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="发票金额" prop="mone">
              <el-input v-model="addTO.mone"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="success" icon="el-icon-folder-checked" @click="getlistForm()">立即创建</el-button>
              <el-button type="info" icon="el-icon-refresh" @click="delectdd">重置信息</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :xs="4" :sm="6" :md="8" :lg="10" :xl="11">
          <el-upload
            class="upload-demo"
            ref="upload"
            :file-list="fileList"
            :action="action"
            :auto-upload="false"
            :data="proutlist"
            :on-change="onChange"
            :on-remove="delfile"
            :on-success="fileSuccess"
            :limit="1"
            :on-error="geterror"
            style="margin-left: 90px"
          >
            <el-button
              slot="trigger"
              size="small"
              type="primary"
              style="margin-left: 20px; margin-top: 40px"
            >选取文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png/pdf文件，且不超过500kb</div>
          </el-upload>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { insertList, queryBypageIncomeAdd, deleteexpen } from "@/api/project";
import { getFileUrl } from "@/api/companyFile";
import { money, Invoice_code, Invoice_No } from "@/utils/myValidate";
export default {
  data() {
    return {
      //搜索条件
      invoiceQruey: {
        number: null,
        code: null,
        category: null,
        type: null,
        status: null,
        pageNum: 1,
        pageSize: 10,
        companyId: null,
        userId: null
      },
      categoryOptions: [
        {
          value: 0,
          category: "普票"
        },
        {
          value: 1,
          category: "专票"
        }
      ],
      typeOptions: [
        {
          value: 0,
          type: "收入"
        },
        {
          value: 1,
          type: "支出"
        },
        {
          value: 2,
          type: "报销"
        }
      ],
      statusOptions: [
        {
          value: 0,
          status: "未报销"
        },
        {
          value: 1,
          status: "已报销"
        }
      ],
      total: 0,
      invoicegetList: [],
      srcList: [],
      isgetid: true, //表格区域的切换
      //添加发票的数据
      addTO: {
        category: null,
        code: null,
        companyId: null,
        mone: null,
        number: null,
        status: 0,
        time: null,
        type: null
      },
      rules: {
        time: [
          { required: true, message: "请输入发票时间", trigger: "change" }
        ],
        number: [
          {
            required: true,
            validator: Invoice_No,
            trigger: "change"
          }
        ],
        code: [{ required: true, validator: Invoice_code, trigger: "change" }],
        category: [
          {
            required: true,
            message: "请至少选择一个发票类型",
            trigger: "change"
          }
        ],
        type: [
          {
            required: true,
            message: "请至少选择一个发票类别",
            trigger: "change"
          }
        ],
        mone: [
          {
            required: true,
            validator: money,
            trigger: "change"
          }
        ]
      },
      fileList: [],
      action: null,
      proutlist: {
        Id: 1,
        status: 0,
        companyId: null
      },
      loading: false
    };
  },
  created() {
    this.proutlist.companyId = this.$store.getters.companyId;
    this.invoiceQruey.companyId = this.$store.getters.companyId;
    this.invoiceQruey.userId = this.$store.getters.urId;
    this.action = process.env.VUE_APP_BASE_API + "/file/uploadFile";
    this.getincomeSelectlist();
  },
  methods: {
    //查询
    selectexpend() {
      this.invoiceQruey.pageNum = 1;
      this.getincomeSelectlist();
    },
    //重置
    upddlist() {
      this.invoiceQruey.pageNum = 1;
      this.invoiceQruey.number = null;
      this.invoiceQruey.code = null;
      this.invoiceQruey.category = null;
      this.invoiceQruey.type = null;
      this.invoiceQruey.status = null;
      this.getincomeSelectlist();
    },
    //添加发票
    Reimbursement() {
      this.isgetid = !this.isgetid;
      this.$refs.addTO.resetFields();
      this.fileList = this.fileList.filter(item => item.uid !== file.uid);
    },
    //发票的分页查询
    getincomeSelectlist() {
      queryBypageIncomeAdd(this.invoiceQruey)
        .then(res => {
          if (res.success) {
            this.total = res.data.total;
            res.data.list.forEach(e => {
              let fileNamepdf = e.filePath;
              let fileType = fileNamepdf.substring(
                fileNamepdf.lastIndexOf(".")
              );
              getFileUrl(e.filePath).then(res => {
                if (res.success) {
                  let url = res.data;
                  e.fileUrl = url;

                  if (fileType != ".pdf") {
                    this.srcList.push(url);
                  }
                }
              });
            });
            this.invoicegetList = res.data.list;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(error => {
          console.log(error);
          this.$message.error("查询发票数据失败");
        });
    },
    //换页
    handleCurrentChange(val) {
      this.invoiceQruey.pageNum = val;
      this.getincomeSelectlist();
    },
    //图片格式
    formatProtocolType(row) {
      //这里判断的是是否有文件
      if (row.filePath == null) {
        return false;
      } else {
        let fileNamepdf = row.filePath;
        let fileType = fileNamepdf.substring(fileNamepdf.lastIndexOf("."));
        if (fileType != ".pdf") {
          return true;
        } else {
          return false;
        }
      }
    },
    //时间处理
    getFroms(value) {
      var dt = new Date(value.time);
      let year = dt.getFullYear();
      let month = dt.getMonth() + 1;
      let date = dt.getDate();
      return `${year}年${month}月${date}日`;
    },
    //点击查看发票
    handlePreView(row) {
      const photopath = row.fileUrl;
      window.open(photopath, "_blank");
    },
    //时间处理 yyyy-MM-dd hh:mm:ss
    timestampToTime1() {
      var date = this.addTO.time;
      var Y = date.getFullYear() + "-";
      var M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var D =
        (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      var h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var m =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      var s =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      this.addTO.time = Y + M + D + h + m + s;
    },
    //发票提交页面的提交
    getlistForm() {
      if (this.fileTypeJpg == true) {
        this.$refs.addTO.validate(valid => {
          if (valid) {
            this.loading = true;
            this.addTO.userId = this.$store.getters.urId;
            this.addTO.companyId = this.$store.getters.companyId;
            insertList(this.addTO)
              .then(res => {
                if (res.success) {
                  //发票记录添加成功
                  //提交发票文件
                  this.proutlist.Id = res.data;
                  this.$refs.upload.submit();
                  this.$message.success(res.msg);
                } else {
                  this.loading = false;
                  this.$message.error(res.msg);
                }
              })
              .catch(e => {
                this.loading = false;
                this.$message.error("发票添加失败,检测是否重复");
              });
          }
        });
      } else {
        this.$message.warning("没有发票文件，无法提交");
      }
    },
    //数据清除
    delectdd() {
      this.$refs.addTO.resetFields();
    },
    //校验发票文件格式
    onChange(file) {
      const fileNamepdf = file.name;
      let fileType = fileNamepdf.substring(fileNamepdf.lastIndexOf("."));
      if (fileType == ".pdf" || fileType == ".png" || fileType == ".jpg") {
        this.fileTypeJpg = true;
      } else {
        this.fileTypeJpg = false;
        this.$message.warning("发票文件只能是pdf，png，jpg格式文件");
        this.$refs.upload.clearFiles();
      }
    },
    //清除发片文件
    delfile() {
      this.fileTypeJpg = false;
    },
    //文件上传成功
    fileSuccess(res) {
      this.loading = false;
      this.isgetid = true;
      this.getincomeSelectlist();
    },
    //发票的删除操作
    YesGet(row) {
      deleteexpen(row)
        .then(res => {
          if (res.success) {
            this.visible = false;
            this.$message({
              message: "发票删除成功",
              type: "success"
            });

            this.getincomeSelectlist();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(e => {
          console.log(e.msg);
          this.$message.error(e.msg);
        });
    },

    geterror() {
      this.loading = true;
    }
  }
};
</script>
<style scoped>
.container {
  padding: 10px;
}
.QueryInvoice .el-form-item {
  margin: 10px 15px;
}
.drawer .foot_yi {
  margin: 10px 10px;
  text-align: right;
}
</style>