<template>
  <div class="app-container">
    <!-- Start 列表页面 -->
    <div v-show="viewState == 1">
      <button-bar view-title="开票管理" ref="btnbar" :btndisabled="btndisabled" @btnhandle="btnHandle"/>
      <div class="main-content">
        <div class="searchcon">
          <el-button size="small" class="searchbtn" @click="clicksearchShow">{{ searchxianshitit }}</el-button>
          <div v-show="isSearchShow" class="search">
            <el-form ref="listQueryform" :inline="true" :model="listQuery" label-width="100px" class="tab-header">
              <el-form-item label="开票单位">
                <el-input v-model="listQuery.params.invoiceTitle" placeholder="" clearable style="width: 150px"/>
              </el-form-item>
              <el-form-item label="开票类型">
                <el-select v-model="listQuery.params.invoiceTypeKey" placeholder="请选择" clearable style="width: 150px">
                  <el-option v-for="item in invoiceType_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"/>
                </el-select>
              </el-form-item>
              <el-form-item label="合同编号">
                <el-input v-model="listQuery.params.contractNo" placeholder="" clearable style="width: 150px"/>
              </el-form-item>
              <el-form-item label="客户名称">
                <el-input v-model="listQuery.params.customerName" placeholder="" clearable style="width: 150px"/>
              </el-form-item>
              <el-form-item label="车架号">
                <el-input v-model="listQuery.params.vinNo" placeholder="" clearable style="width: 150px"/>
              </el-form-item>
              <el-form-item label="发票状态">
                <el-select v-model="listQuery.params.billingStateKey" placeholder="请选择" clearable style="width: 150px">
                  <el-option v-for="item in state_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"/>
                </el-select>
              </el-form-item>
              <el-form-item label="移交状态">
                <el-select v-model="listQuery.params.transferStateKey" placeholder="请选择" clearable style="width: 150px">
                  <el-option v-for="item in invoiceState_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"/>
                </el-select>
              </el-form-item>
              <el-form-item label="开票名称">
                <el-input v-model="listQuery.params.invoicingName" placeholder="" clearable style="width: 150px"/>
              </el-form-item>
              <el-form-item label="发票代码">
                <el-input v-model="listQuery.params.invoiceCode" placeholder="" clearable style="width: 150px"/>
              </el-form-item>
              <el-form-item label="开票日期">
                <el-date-picker v-model="listQuery.params.createStartTime" type="date" clearable value-format="yyyy-MM-dd" placeholder="选择日期" style="width: 150px"/>
                <span style="padding: 0 8px">至</span>
                <el-date-picker v-model="listQuery.params.createEndTime" type="date" clearable value-format="yyyy-MM-dd" placeholder="选择日期" style="width: 150px"/>
              </el-form-item>
            </el-form>
            <div class="btn" style="text-align: center;">
              <el-button type="primary" icon="el-icon-search" @click="handleFilter" size="small">查询</el-button>
              <el-button type="primary" icon="el-icon-refresh" @click="handleReset" size="small">重置</el-button>
            </div>
          </div>
        </div>
        <div class="listtop">
          <div class="tit">发票列表</div>
          <pageye v-show="list.length > 0" :total="listQuery.total" :page.sync="listQuery.current" :limit.sync="listQuery.size" class="pagination" @pagination="getList"/>
        </div>
        <div class="">
          <el-table :key="tableKey" v-loading="listLoading" :data="list" border style="width: 100%;" @selection-change="handleSelectionChange">
            <el-table-column fixed width="50" type="selection" align="center"/>
            <el-table-column fixed width="60" label="序号" type="index" :index="indexMethod" align="center"/>
            <el-table-column fixed label="操作" width="100" align="center">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="toInfo(scope.row)">查看</el-button>
              </template>
            </el-table-column>
            <el-table-column label="发票状态" width="100px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.billingState }}</span>
              </template>
            </el-table-column>
            <el-table-column label="交接状态" width="100px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.transferState }}</span>
              </template>
            </el-table-column>
            <el-table-column label="业务状态" width="100px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.businessState }}</span>
              </template>
            </el-table-column>
            <el-table-column label="开票单位" align="center" width="200px">
              <template slot-scope="scope">
                <span>{{ scope.row.invoiceTitle }}</span>
              </template>
            </el-table-column>
            <el-table-column label="开票类型" align="center" width="200px">
              <template slot-scope="scope">
                <span>{{ scope.row.invoiceType }}</span>
              </template>
            </el-table-column>
            <el-table-column label="合同编号" header-align="center" align="left" width="150px">
              <template slot-scope="scope">
                <span>{{ scope.row.contractNo }}</span>
              </template>
            </el-table-column>
            <el-table-column label="客户名称" align="center" width="100px">
              <template slot-scope="scope">
                <span>{{ scope.row.customerName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="车架号" align="center" width="100px">
              <template slot-scope="scope">
                <span>{{ scope.row.vinNo }}</span>
              </template>
            </el-table-column>
            <el-table-column label="开票名称" align="center" width="120px">
              <template slot-scope="scope">
                <span>{{ scope.row.invoicingName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="开票金额" align="center" width="120px">
              <template slot-scope="scope">
                <span>{{ scope.row.invoiceAmount }}</span>
              </template>
            </el-table-column>
            <el-table-column label="开票日期" align="center" width="120px">
              <template slot-scope="scope">
                <span>{{ scope.row.createTime }}</span>
              </template>
            </el-table-column>
            <el-table-column label="发票代码" align="center" width="120px">
              <template slot-scope="scope">
                <span>{{ scope.row.invoiceCode }}</span>
              </template>
            </el-table-column>
            <el-table-column label="发票号" align="center" min-width="120px">
              <template slot-scope="scope">
                <span>{{ scope.row.invoiceNo }}</span>
              </template>
            </el-table-column>
            <el-table-column label="发票图片" align="center" width="100px" class-name="small-padding">
              <template slot-scope="scope">
                <el-button size="mini" v-show="scope.row.witMatUrl !== ''" type="primary" @click="handleGetCheck(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pages">
          <!-- 翻页 -->
          <pagination v-show="list.length > 0" :total="listQuery.total" :page.sync="listQuery.current" :limit.sync="listQuery.size" class="pagination" @pagination="getList"/>
        </div>
      </div>
    </div>
    <!-- End 列表页面 -->
    <billingmanagementAdd v-show="viewState == 2" ref="divAdd" @doback="reseaState" @reloadlist="getList"/>
    <billingmanagementInfo v-show="viewState == 3" ref="divInfo" @doback="reseaState"/>
    <!-- 照片弹窗 -->
    <el-dialog :append-to-body="true" :visible.sync="dialogImgVisible">
      <el-image style="width: 178px;height: 178px;padding-left: 5px" v-for="(item,index) in srcList" :key="index" :src="item" :preview-src-list="srcList"></el-image>
    </el-dialog>

    <el-dialog :append-to-body="true" :visible.sync="dialogFileVisible">
      <el-form :model="formobj" ref="form_obj" :rules="rules" class="formadd">
        <el-row style="border: 1px solid #E0E3EB">
          <el-col :span="6" class="tleftb">
            <span><span class="icon">*</span>移交日期</span>
          </el-col>
          <el-col :span="18">
            <el-form-item prop="transferTime">
              <el-date-picker v-model="formobj.transferTime" type="date" clearable value-format="yyyy-MM-dd" placeholder="选择日期"/>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="tleftb">
            <span><span class="icon">*</span>接收人</span>
          </el-col>
          <el-col :span="18">
            <el-form-item prop="recipient">
              <el-select v-model="formobj.recipient" placeholder="请选择" @change="changeRecipient" clearable>
                <el-option v-for="item in user_list" :key="item.userSid" :label="item.userName" :value="item.userName"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="handleConfirm">确定</el-button>
        <el-button size="small" @click="dialogFileVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listPage, cancellation, saveOrUpdate } from '@/api/anruifinmanagement/fininvoiceapply'
import { getOrgSidByPath, typeValues, getButtonPermissions, getGressionUserList } from '@/api/jichuxinxi/dictcommons'
import Pagination from '@/components/pagination'
import pageye from '@/components/pagination/pageye'
import ButtonBar from '@/components/ButtonBar'
import billingmanagementAdd from './billingmanagementAdd'
import billingmanagementInfo from './billingmanagementInfo'

export default {
  name: 'KaiPiaoGuanLi',
  components: {
    Pagination,
    pageye,
    ButtonBar,
    billingmanagementAdd,
    billingmanagementInfo
  },
  data() {
    return {
      btndisabled: false,
      viewState: 1,
      btnList: [
        {
          type: 'primary',
          size: 'small',
          icon: 'edit',
          btnKey: 'toEdit',
          btnLabel: '编辑'
        },
        {
          type: 'primary',
          size: 'small',
          icon: '',
          btnKey: 'doHandover',
          btnLabel: '移交'
        },
        {
          type: 'danger',
          size: 'small',
          icon: '',
          btnKey: 'doCancellation',
          btnLabel: '作废'
        },
        {
          type: 'info',
          size: 'small',
          icon: 'cross',
          btnKey: 'doClose',
          btnLabel: '关闭'
        }
      ],
      isSearchShow: false,
      searchxianshitit: '显示查询条件',
      dialogImgVisible: false,
      dialogFileVisible: false,
      // 查询条件 -----------
      tableKey: 0,
      list: [],
      sids: [],
      nodeState_list: [],
      srcList: [],
      invoiceType_list: [],
      state_list: [],
      invoiceState_list: [],
      user_list: [],
      FormLoading: false,
      listLoading: false,
      listQuery: {
        params: {
          invoiceTitle: '',
          invoiceTypeKey: '',
          contractNo: '',
          customerName: '',
          vinNo: '',
          billingStateKey: '',
          transferStateKey: '',
          invoicingName: '',
          invoiceCode: '',
          createStartTime: '',
          createEndTime: '',
          createOrgSid: '',
          orgSidPath: ''
        },
        current: 1,
        size: 10,
        total: 0
      },
      formobj: {
        recipient: '',
        recipientSid: '',
        showTransfer: true,
        transferTime: '',
        sid: ''
      },
      rules: {
        transferTime: [{ required: true, message: '移交日期不能为空', trigger: 'blur' }],
        recipient: [{ required: true, message: '接收人不能为空', trigger: 'change' }]
      }
    }
  },
  created() {
    // 初始化变量
    this.init()
    // this.getList()
  },
  mounted() {
    getButtonPermissions({ userSid: window.sessionStorage.getItem('userSid'), url: this.$route.path, type: 0 }).then((res) => {
      if (res.success) {
        for (var i = 0; i < res.data.length; i++) {
          for (var k = 0; k < this.btnList.length; k++) {
            if (res.data[i].buttonId === this.btnList[k].btnKey) {
              this.btnList.splice(k, 1)
            }
          }
        }
        this.$refs['btnbar'].setButtonList(this.btnList)
      }
    })
  },
  methods: {
    // 搜索条件效果
    clicksearchShow() {
      this.isSearchShow = !this.isSearchShow
      if (this.isSearchShow) {
        this.searchxianshitit = '隐藏查询条件'
      } else {
        this.searchxianshitit = '显示查询条件'
      }
    },
    btnHandle(btnKey) {
      console.log('XXXXXXXXXXXXXXX    ' + btnKey)
      switch (btnKey) {
        case 'toEdit':
          this.toEdit()
          break
        case 'doHandover':
          this.doHandover()
          break
        case 'doCancellation':
          this.doCancellation()
          break
        case 'doClose':
          this.doClose()
          break
        default:
          break
      }
    },
    init() {
      typeValues({ type: 'invoiceType' }).then((resp) => {
        if (resp.success) {
          this.invoiceType_list = resp.data
        }
      })
      typeValues({ type: 'transferState' }).then((resp) => {
        if (resp.success) {
          this.invoiceState_list = resp.data
        }
      })
      typeValues({ type: 'billingState' }).then((resp) => {
        if (resp.success) {
          this.state_list = resp.data
        }
      })
      getOrgSidByPath({ orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((res) => {
        if (res.success) {
          this.listQuery.params.createOrgSid = res.data
          getGressionUserList({ userSid: window.sessionStorage.getItem('userSid'), orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((resp) => {
            if (resp.success) {
              this.user_list = resp.data
            }
          })
          this.getList()
          console.log(this.listQuery.params.createOrgSid)
        }
      })
    },
    // 序号
    indexMethod(index) {
      var pagestart = (this.listQuery.current - 1) * this.listQuery.size
      var pageindex = index + 1 + pagestart
      return pageindex
    },
    // 获取数据sid
    handleSelectionChange(row) {
      const aa = []
      const bb = []
      row.forEach(element => {
        aa.push(element.sid)
        bb.push({
          billingState: element.billingState,
          transferState: element.transferState
        })
      })
      this.sids = aa
      this.nodeState_list = bb
      console.log('获取sids数组', this.sids)
    },
    // 查询列表信息
    getList() {
      this.listLoading = true
      this.listQuery.params.orgSidPath = window.sessionStorage.getItem('defaultOrgPath')
      listPage(this.listQuery).then((response) => {
        console.log('列表查询结果：', response)
        this.listLoading = false
        if (response.success) {
          this.list = response.data.records
          this.listQuery.total = response.data.total
        } else {
          this.list = []
          this.listQuery.total = 0
        }
      })
    },
    // 查询按钮
    handleFilter() {
      this.listQuery.current = 1
      this.getList()
    },
    handleReset() {
      this.listQuery = {
        params: {
          invoiceTitle: '',
          invoiceTypeKey: '',
          contractNo: '',
          customerName: '',
          vinNo: '',
          billingStateKey: '',
          transferStateKey: '',
          invoicingName: '',
          invoiceCode: '',
          createStartTime: '',
          createEndTime: '',
          createOrgSid: '',
          orgSidPath: ''
        },
        current: 1,
        size: 10,
        total: 0
      }
      this.init()
    },
    toEdit() {
      if (this.sids.length === 1) {
        if (this.nodeState_list.length > 0) {
          for (var i = 0; i < this.nodeState_list.length; i++) {
            if (this.nodeState_list[i].billingState === '作废' || this.nodeState_list[i].billingState === '已开票') {
              this.$message({ showClose: true, type: 'error', message: '因选择的记录中包含作废或已开票的,操作失败' })
              return
            }
          }
        }
        this.viewState = 2
        this.$refs['divAdd'].showEdit(this.sids[0])
      } else {
        this.$message({ showClose: true, type: 'error', message: '请选择一条记录进行编辑操作' })
        return
      }
    },
    doHandover() {
      if (this.sids.length === 1) {
        if (this.nodeState_list[0].billingState === '已开票' && this.nodeState_list[0].transferState === '未移交') {
          var nowDate = new Date()
          var date = {
            year: nowDate.getFullYear(),
            month: nowDate.getMonth() + 1,
            day: nowDate.getDate()
          }
          var dayDate = date.year + '-' + (date.month >= 10 ? date.month : '0' + date.month) + '-' + (date.day >= 10 ? date.day : '0' + date.day)
          this.formobj = {
            recipient: '',
            recipientSid: '',
            showTransfer: true,
            transferTime: dayDate,
            sid: ''
          }
          this.dialogFileVisible = true
        } else {
          this.$message({ showClose: true, type: 'error', message: '请选择发票状态为已开票且交接状态为未移交的进行移交操作' })
          return
        }
      } else {
        this.$message({ showClose: true, type: 'error', message: '请选择一条记录进行移交操作' })
        return
      }
    },
    changeRecipient(value) {
      const choose = this.user_list.filter((item) => item.userName === value)
      this.formobj.recipientSid = choose[0].userSid
    },
    handleConfirm() {
      this.formobj.sid = this.sids[0]
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          saveOrUpdate(this.formobj).then((resp) => {
            if (resp.success) {
              this.$message({ showClose: true, type: 'success', message: '移交成功' })
              this.getList()
              this.dialogFileVisible = false
            }
          })
        }
      })
    },
    doCancellation() {
      if (this.sids.length === 0) {
        this.$message({ showClose: true, type: 'error', message: '请选择至少一条记录进行作废操作' })
        return
      }
      if (this.nodeState_list.length > 0) {
        for (var i = 0; i < this.nodeState_list.length; i++) {
          if (this.nodeState_list[i].billingState === '作废') {
            this.$message({ showClose: true, type: 'error', message: '因选择的记录中包含作废的,操作失败' })
            return
          }
        }
      }
      const tip = '请确认是否作废所选 ' + this.sids.length + ' 条记录?'
      this.$confirm(tip, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        cancellation(this.sids).then(resp => {
          loading.close()
          if (resp.success) {
            this.$message({ type: 'success', message: resp.msg, showClose: true })
            this.getList()
          }
        }).catch(e => {
          loading.close()
        })
      }).catch(() => {})
    },
    toInfo(row) {
      this.viewState = 3
      this.$refs['divInfo'].showInfo(row)
    },
    handleGetCheck(row) {
      this.dialogImgVisible = true
      this.srcList = row.filePaths
    },
    reseaState() {
      this.viewState = 1
    },
    doClose() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.go(-1)
    }
  }
}
</script>
<style scoped>
.upload_img {
  display: inline-block;
  padding-left: 10px;
}

</style>
