<template>
  <el-card class="box-card">
    <el-form :model="queryParams" ref="queryForm" :inline="true" @submit.native.prevent>
      <el-form-item label="客户:" prop="subsidiaryName">
        <el-input v-model="queryParams.subsidiaryName" placeholder="请输入客户名称" size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="收款时间:">
        <el-col :span="11">
          <el-date-picker
            type="month"
            placeholder="请选择开始年月"
            v-model="queryParams.strTime"
            value-format="yyyy-MM"
            size="small"
            style="width: 100%"
            @change="handleQuery"
          ></el-date-picker>
        </el-col>
        <el-col class="line" :span="2" style="text-align: center">至</el-col>
        <el-col :span="11">
          <el-date-picker
            type="month"
            placeholder="请选择结束年月"
            v-model="queryParams.endTime"
            value-format="yyyy-MM"
            size="small"
            style="width: 100%"
            @change="handleQuery"
          ></el-date-picker>
        </el-col>
      </el-form-item>
      <el-form-item>
        <el-button size="small" @click="handleQuery" class="searchBtn">搜索</el-button>
        <el-button size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" style="margin-bottom: 10px">
      <el-col :span="1.5">
        <el-button type="primary" size="mini" @click="handleAdd" v-db-click>充值</el-button>
      </el-col>
    </el-row>

    <el-table :data="tableList" :cell-style="{ padding: '0' }" :row-style="{ height: '35px' }" v-loading="loading" header-row-class-name="tableHeader">
      <el-table-column label="客户" prop="subsidiaryName" />
      <el-table-column label="月度" prop="monthly" />
      <el-table-column label="收款金额" align="right">
        <template slot-scope="scope">
          <span>{{ moneyFormat(scope.row.amount, 2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作时间" align="center" prop="createTime" width="140" />
      <el-table-column label="操作" align="center" width="140">
        <template slot-scope="scope">
          <el-button type="text" @click="clickRemove(scope.row)" v-db-click>删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 入账明细 -->
    <el-dialog title="入账明细" v-if="open" :visible.sync="open" width="40%" append-to-body>
      <el-form ref="ruleForm" :model="form" :rules="formRules" label-width="100px">
        <el-form-item label="客户:" prop="subsidiaryId">
          <el-select v-model="form.subsidiaryId" placeholder="请选择客户" size="small" style="width: 100%">
            <el-option v-for="item in companyList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="月度:" prop="monthly">
          <el-date-picker type="month" placeholder="请选择月度" v-model="form.monthly" value-format="yyyy-MM" size="small" style="width: 100%" />
        </el-form-item>
        <el-form-item label="收款金额:" prop="amount">
          <el-input-number
            size="small"
            style="width: 100%"
            placeholder="请输入收款金额"
            v-model="form.amount"
            :controls="false"
            :min="0"
            :max="999999999"
            :precision="2"
          />
        </el-form-item>
        <el-form-item label="附件上传:">
          <el-upload
            :action="action"
            :headers="{ 'Blade-Auth': token }"
            :before-upload="beforeUpload"
            :on-success="fileSuccess"
            :on-remove="fileRemove"
            multiple
            :on-preview="onPreview"
            :on-progress="onProgressTest"
          >
            <el-button size="mini" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <div style="width: 100%; text-align: center">
          <el-button type="primary" @click="clickSubmit" size="small" v-db-click>确 认</el-button>
          <el-button size="small" @click="open = false">取 消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </el-card>
</template>

<script>
import * as API from '@/api/shengde/subsidiary/bill/bill'
import { mapGetters } from 'vuex'

export default {
  name: 'subCompanyBill',
  data() {
    return {
      action: process.env.VUE_APP_ACTION_URL,
      pathPrefix: process.env.VUE_APP_IMG_URL,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        subsidiaryName: '',
        monthly: '',
        strTime: '',
        endTime: '',
      },
      loading: false,
      tableList: [],
      total: 0,
      open: false,
      form: {
        subsidiaryId: '',
        monthly: '',
        amount: undefined,
        att: [],
      },
      formRules: {
        subsidiaryId: [{ required: true, message: '请选择客户', trigger: 'change' }],
        monthly: [{ required: true, message: '请选择月度', trigger: ['change', 'blur'] }],
        amount: [{ required: true, message: '请输入收款金额', trigger: 'blur' }],
      },
      companyList: [],
    }
  },
  created() {
    API.getSubsidiaryList({ pageNum: 1, pageSize: 9999 }).then((res) => {
      this.companyList = this.companyList.concat(res.data.data.records)
    })
  },
  mounted() {
    this.getList()
  },
  computed: mapGetters(['token']),
  methods: {
    getList() {
      this.loading = true
      API.getBillManagementList(this.queryParams).then(
        (res) => {
          this.tableList = res.data.data.records
          this.total = res.data.data.total
          this.loading = false
        },
        (err) => {
          console.log('getBillManagementList: ' + err)
          this.loading = false
        }
      )
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.strTime = ''
      this.queryParams.endTime = ''
      this.handleQuery()
    },
    handleAdd() {
      this.form = {
        subsidiaryId: '',
        monthly: '',
        amount: undefined,
        att: [],
      }
      this.open = true
    },
    clickRemove(row) {
      this.$confirm('是否确认删除此条数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          API.billManagementDelete({ id: row.id, subsidiaryId: row.subsidiaryId }).then(() => {
            this.msgSuccess('删除成功!')
            this.getList()
          })
        })
        .catch(() => {})
    },
    conversion(data) {
      var attachments = []
      if (data && data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          if (data[i].response && data[i].response.data && data[i].response.data) {
            data[i].response.data.details.busiType = 38
            attachments.push(data[i].response.data.details)
          } else {
            data[i].busiType = 38
            attachments.push(data[i])
          }
        }
      }
      return attachments
    },
    clickSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.form.att = this.conversion(this.form.att)
          API.billManagementSave(this.form).then(() => {
            this.msgSuccess('提交完成')
            this.open = false
            this.getList()
          })
        }
      })
    },
    beforeUpload(file) {
      const isLt50M = file.size / 1024 / 1024 < 50
      if (!isLt50M) {
        this.$message.error('上传文件大小不能超过50MB!')
      }
      return isLt50M
    },
    fileSuccess(response, file, fileList) {
      this.form.att = fileList
    },
    fileRemove(file, fileList) {
      this.form.att = fileList
    },
    onPreview(file) {
      if (file.response) {
        window.open(this.pathPrefix + file.response.data.details.path, '_blank')
      } else {
        window.open(this.pathPrefix + file.path, '_blank')
      }
    },
    onProgressTest(event, file, fileList) {
      let index = 0
      // 只有fileList 跟file 里面的uid是唯一的互相对应的
      fileList.forEach((v, i) => {
        if (v.uid === file.uid) {
          index = i
        }
      })
      // 获取动态的进度
      let percent = parseInt(event.percent)
      this.$nextTick(() => {
        setTimeout(() => {
          if (percent >= 99) {
            // 当动态的进度超过99就获取dom 让值一直显示99直到上传成功
            let dom = document.getElementsByClassName('el-upload-list__item')[index]
            let progressText = dom.getElementsByClassName('el-progress__text')
            if (progressText && progressText.length) {
              progressText[0].style.opacity = 0
              progressText[0].innerText = '99%'
              progressText[0].style.opacity = 1
            }
          }
        })
      })
    },
  },
}
</script>

<style lang="scss" scoped>
* {
  font-size: 12px;
}
.box-card {
  height: calc(100vh - 110px);
  overflow-y: auto;
}
.searchBtn {
  background: #20b2aa;
  color: #fff;
  border: 1px solid #20b2aa;
}
::v-deep {
  .el-input__inner {
    border-radius: 1px;
  }
  .el-button--small {
    border-radius: 1px;
  }
  .tableHeader th {
    background-color: #edf0f5;
    height: 35px;
    padding: 0;
  }
  .el-input-number {
    .el-input__inner {
      text-align: left !important;
    }
  }
}
</style>
