<template>
  <div class="root">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="add-ruleForm">
      <el-form-item label="收费组名称" prop="billName">
        <el-input v-model="ruleForm.billName"/>
      </el-form-item>
      <el-form-item label="收费组说明" prop="billExplain">
        <el-input v-model="ruleForm.billExplain"/>
      </el-form-item>
      <el-form-item label="截止时间" prop="endDate">
        <el-date-picker
          v-model="ruleForm.endDate"
          type="date"
          value-format="timestamp"
          placeholder="选择日期"/>
      </el-form-item>
      <div>
        <span>
          <el-upload
            :on-success="successUpload"
            :limit="1"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload"
            :data="ruleForm"
            :action="uploadUrl"
            name="file"
            class="upload-demo"
            multiple>
            <el-button slot="trigger" size="large" type="primary">选取文件并预览</el-button>
          </el-upload>
          如果还未制作账单，请先下载账单模板，按规则填写费用后再上传
          <el-button type="primary" size="small" icon="el-icon-download" @click="downloadExcel">下载模板</el-button>
        </span>
      </div>
      <span style="color: #99a9bf; font-size: 13px;">如果想修改下表的内容，请重新下载excel模板填写金额后上传，系统会直接删除下表所有旧数据，以新的excel内容为准</span>
      <el-table
        :data="list"
        border
        style="width: 100%; margin-top: 20px;">
        <el-table-column
          prop="id"
          type="index"
          label="选择"
          align="center"/>
        <el-table-column
          prop="name"
          label="房屋信息"
          align="center"
          width="180">
          <template slot-scope="scope">{{ showAddress(scope.row) }}</template>
        </el-table-column>
        <!--<el-table-column-->
          <!--prop="ownerName"-->
          <!--label="户主姓名"/>-->
        <el-table-column
          prop="billExplain"
          align="center"
          label="收费说明"/>
        <el-table-column
          align="center"
          label="收费金额(元)">
          <template slot-scope="scope">{{ showPayPrice(scope.row.payPrice) }}</template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="listQuery.pageNum"
        :page-sizes="[10, 20, 40, 100]"
        :page-size="listQuery.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
      <span style="color: #99a9bf;font-size: 13px;">点击发送后账单会发送给对应家庭，家庭中的成员都可以查看到他们家的收费项，缴费成功无法线上退款，只能线下当面退款，请先保存为草稿，核对无误后再发送账单给住户</span>
      <el-form-item style="margin-top: 20px;">
        <el-button @click="submitForm('ruleForm', 2)">保存草稿</el-button>
        <el-button type="primary" @click="submitForm('ruleForm', 0)">发送账单</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from 'vuex'
import waves from '@/directive/waves' // Waves directive
import { parseTime } from '@/utils'

export default {
  computed: {
    ...mapState('role', {
      menuList: s => s.menuList
    })
  },
  data() {
    return {
      uploadUrl: process.env.BASE_API + '/bill/uploadExcel/get',
      ruleForm: {
        billName: '',
        billExplain: '',
        endDate: '',
        billStatus: '' // 缴费状态  0：未缴费  1：已线上缴费 2：已线下缴费
      },
      rules: {
        billName: [
          { required: true, message: '请输入收费组名称', trigger: 'blur' }
        ],
        billExplain: [
          { required: true, message: '请输入收费组说明', trigger: 'blur' }
        ],
        endDate: [
          { required: true, message: '请输入截止时间', trigger: 'blur' }
        ]
      },
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      listQuery: { // 查询
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      list: [], // 数据
      tempList: [], // 临时数据
      files: '' // 文件
    }
  },
  created() {
    this.getMenuList()
  },
  methods: {
    ...mapMutations('role', {
    }),
    ...mapActions('role', [
      'FetchMenuList',
      'AddRoleInfo'
    ]),
    getList() { // 计算分页数据
      const tempList = this.tempList
      const list = []
      let counNum = 0
      for (let t = (this.listQuery.pageNum - 1) * this.listQuery.pageSize; t < tempList.length; t++) {
        if (counNum === this.listQuery.pageSize) {
          break
        }
        list.push(tempList[t])
        counNum++
      }

      // for (const i in tempList) {
      //   list.push(tempList[i])
      // }
      return list
    },
    beforeUpload(file) {
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      if (!extension && !extension2) {
        this.$message.warning('上传文件只能是 xls、xlsx格式!')
        return
      }
      this.files = file
      return true // 返回false不会自动上传
    },
    successUpload(response, file, fileList) { // 上传成功时
      const resCode = response.code
      if (resCode === '1') {
        this.$message.error(response.message)
        return
      }
      this.tempList = response.data.list
      this.total = response.data.total
      this.list = this.getList()
      console.log(response)
    },
    handleExceed(files, fileList) {
      console.log('只能选择一个文件')
    },
    submitForm(formName, status) { // 提交
      // const sysDate = new Date().getTime()
      // if (this.ruleForm.endDate < sysDate) {
      //   this.$message.error('截止时间, 不能小于当前时间!')
      //   return
      // }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ruleForm.billStatus = status
          // const data = this.ruleForm
          // data.files = this.files
          const formData = new FormData()
          formData.append('billExplain', this.ruleForm.billExplain)
          formData.append('billName', this.ruleForm.billName)
          formData.append('endDate', this.ruleForm.endDate)
          formData.append('billStatus', this.ruleForm.billStatus)
          formData.append('file', this.files)
          this.$store.dispatch('bill/BillUploadExcelAdd', formData).then(res => {
            const resCode = res.code
            if (resCode === '0') {
              this.$message.success(res.message)
              this.$router.push({ name: 'bill-index' })
              return
            }
            this.$message.error(res.message)
          }).catch(() => {
            console.log('BillUploadExcelAdd error')
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    addInvoice(status) { // 保存
      this.ruleForm.billStatus = status
      const data = this.ruleForm
      data.files = this.files
      this.$store.dispatch('BillUploadExcelAdd', data).then(res => {
        const resCode = res.code
        if (resCode === '1') {
          this.$message.error(res.message)
          return
        }
        this.$message.success(res.message)
      }).catch(() => {
        console.log('BillUploadExcelAdd error')
      })
    },
    showPayPrice(payPrice) { //  转换金额
      if (payPrice === null) {
        return ''
      }
      const price = payPrice / 100
      return price
    },
    getMenuList() {
      this.FetchMenuList().then(() => {
      }).catch(() => {
        console.log('get list error')
      })
    },
    resetForm(formName) { // 重置
      this.$refs[formName].resetFields()
      this.$refs.tree.setCheckedKeys([])
      this.ruleForm.roleName = ''
      this.ruleForm.description = ''
    },
    addRole() {
      // 加载框
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.AddRoleInfo(this.ruleForm).then((res) => {
        if (res.code === '0') {
          this.$message({
            message: res.message,
            type: 'success'
          })
          this.$router.push({ name: 'role-index' })
          loading.close()
          return
        }
        this.$message.error(res.message)
        loading.close()
      }).catch(() => {
        loading.close()
        console.log('error addRole')
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.listQuery.pageSize = val
      this.list = this.getList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.listQuery.pageNum = val
      this.list = this.getList()
    },
    showAddress(obj) { // 显示地址
      let str = ''
      if (obj.phase !== null) {
        str += obj.phase
      }
      if (obj.building !== null) {
        str += obj.building
      }
      if (obj.unit !== null) {
        str += obj.unit
      }
      if (obj.level !== null) {
        str += obj.level
      }
      if (obj.roomNo !== null) {
        str += obj.roomNo
      }
      return str
    },
    downloadExcel() {
      this.$store.dispatch('bill/BillDownloadExcel').then(res => {
        const url = window.URL.createObjectURL(new Blob([res]))
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', '缴费单模板.xls')
        document.body.appendChild(link)
        link.click()
      }).catch(() => {
        console.log('error BillDownloadExcel')
      })
    }
  }
}
</script>

<style scoped>
.add-ruleForm{
  width: 800px;
  margin-left: auto;
  margin-right: auto;
  margin-top: 50px;
}
</style>
