<template>
  <div class="app-container arrears-reminder">
    <el-form inline>
      <el-form-item>
        <el-select v-model="param.CustomerId" placeholder="客户" clearable filterable>
          <el-option v-for="(item, index) in customers" :key="item.CustomerNumber + index"
            :label="`${item.CompanyName}(${item.CustomerNumber})`" :value="item.Id" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="getSellRoles">
        <el-select v-model="param.SealId" placeholder="业务员" clearable filterable>
          <el-option
            v-for="(item, index) in salesmanUser"
            :key="`${item.Id}_${index}`"
            :label="item.NickName"
            :value="item.Id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="param.OwningWarehouse" placeholder="所属仓库" clearable>
          <el-option
            v-for="item in owningWarehouseTypes"
            :key="item.Value"
            :label="item.Name"
            :value="item.Value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <div class="block">
          <el-date-picker
            v-model="param.CreateTime"
            type="daterange"
            range-separator="~"
            value-format="yyyy-MM-dd"
            start-placeholder="问题产生日期"
            end-placeholder="问题结束日期"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <el-select placeholder="重新收货标识" clearable v-model="param.CanReceiver">
          <el-option :value="true" label="可重新收货"></el-option>
          <el-option :value="false" label="不可重新收货"></el-option>
        </el-select>
      </el-form-item>
      <el-button type="primary" icon="el-icon-search" :loading="loading" @click="search">搜索</el-button>
      <el-button type="danger" icon="el-icon-refresh" :loading="loading" @click="reset">重置</el-button>
      <el-button icon="el-icon-download" @click="onExport">导出</el-button>
    </el-form>
    <div>
      <el-table border v-loading="loading" :data="paginatedData" :close-on-click-modal="false">
        <el-table-column prop="Abbreviation" label="客户" :min-width="110" />
        <el-table-column prop="NickName" label="业务员" :width="95" />
        <el-table-column prop="QtyAsArrears" label="问题件数" :width="90" />
        <el-table-column prop="TransferWarehouseQty" label="转运件数" :width="90" >
          <template slot-scope="scope">
          <el-button type="link" @click="showDetail(scope.row)">
          {{ scope.row.TransferWarehouseQty }}
          </el-button>
        </template>
        </el-table-column>


        <el-table-column prop="FeeSumAsArrears" label="问题件费用" :width="100" />
        <el-table-column prop="CustomerBalance" label="客户余额" :width="100" />
        <el-table-column prop="ExpectBalance" label="预计余额" :width="100" />
        <el-table-column prop="LastTimeAsArrears" label="问题最后产生时间" :width="156">
          <template slot-scope="scope">
            {{ scope.row.LastTimeAsArrears | getLastTimeAsArrearsTime }}
          </template>
        </el-table-column>
        <el-table-column prop="LastTimeAsRecharge" label="最后充值时间" :width="152" />
        <el-table-column prop="LastFeeAsRecharge" label="最后充值金额" :width="105" />
        <el-table-column prop="LastTimeAsOpenReceipt" label="临时收货时间" :width="156" />
        <!-- <el-table-column prop="OrderTime" label="完成时间" :formatter="colFormatDate" /> -->
        <el-table-column prop="LastFeeAsOpenReceipt" label="临时收货金额" :width="105" />
        <el-table-column prop="CanReceiver" label="可重新收货" :width="95">
          <template slot-scope="scope">
            <el-tag :type="scope.row.CanReceiver ? 'success' : 'danger'">
              {{ scope.row.CanReceiver ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="OwningWarehouse" label="扫描仓库" :width="90" :show-overflow-tooltip="true" />
        <el-table-column prop="LastOperName" label="扫描人" :width="85" />
        <el-table-column prop="LastNoticeTime" label="最后通知时间" :width="152" />
        <el-table-column label="操作" :width="90">
          <template slot-scope="scope">
            <el-button @click="notice(scope.row)" :loading="scope.row.noticeLoading" size="mini">
              通知
            </el-button>
          </template>
        </el-table-column>

        <!-- <el-table-column label="操作" :width="100" fixed="right">
          <template slot-scope="{ row }">
            <el-button size="mini" type="success" @click="hanleDownloadDetail(row)">下载明细</el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <div class="page-warp">
        <el-pagination
          :page-sizes="[20, 50, 80, 100]"
          :current-page="PageIndex"
          :page-size="PageSize"
          background layout="prev, pager, next ,total ,jumper, sizes, slot"
          :total="total"
          @current-change="pagerSearch"
          @size-change="sizeChange" />
      </div>
    </div>
    <el-dialog
      title="转运明细"
      :visible.sync="dialogDetail"
    >
    <div class="page-warp">
        <el-table border v-loading="detailLoading" :data="dialogDetails.slice((detailPageIndex-1)*detailPageSize,detailPageIndex*detailPageSize)">
          <el-table-column prop="StrOperDate" label="操作日期" :width="120" />

          <el-table-column prop="CustomerOrderNo" label="客户单号" :width="180" />
          <el-table-column prop="TransferNumber" label="转单号" :width="180" />
          <el-table-column prop="TrackingNumber" label="跟踪号" :width="180" />
          <el-table-column prop="SystemNo" label="系统单号" :width="180" />
          <el-table-column prop="StrOriWarehouse" label="来源仓" :width="120" />
          <el-table-column prop="StrToWarehouse" label="目地仓" :width="120" />
          <el-table-column prop="CreateUserName" label="操作人" :width="120" />
        </el-table>
        <el-pagination
          :page-sizes="[20, 50, 80, 100]"
          :current-page="detailPageIndex"
          :page-size="detailPageSize"
          background layout="prev, pager, next ,total ,jumper, sizes, slot"
          :total="detailTotal"
          @current-change="detailPagerSearch"
          @size-change="detailSizeChange" />
      </div>
    </el-dialog>
  </div>
</template>
<script>
import colFormatDate from '@/utils/columnFormat'
import { _getCountries, _getCustomers, _getOwningWarehouseTypes } from '@/api/baseInfo'
import { _getSalesmanUsers } from '@/api/customer'
import { _queryFinanceGetArrears, _outDownloadArrearsData,_sendArrearsFile,_getTransferWarehouseLogs } from '@/api/finance/financeReport';
import { addDays, DateFormat } from '@/api/timehelp';
import { mapGetters } from "vuex";

export default {
  name: 'ArrearsReminder',
  data: function () {
    return {
      loading: false,
      dialogDetails:[],
      dialogDetail:false,
      detailPageIndex:1,
      detailPageSize:20,
      detailTotal:0,
      customers: [],
      salesmanUser: [],
      owningWarehouseTypes: [],
      createDate: [],
      detailLoading:false,
      tableList: [
        // {
        //   Status: 2,
        //   Abbreviation: '张三',
        //   LastTimeAsArrears: '2024/5/22 19:00:00',
        //   LastTimeAsRecharge: '2024/5/22 19:00:00',
        //   LastTimeAsOpenReceipt: '2024/5/22 19:00:00',
        // }
      ],
      canReceiverList: [
        { value: true, label: '是' },
        { value: false, label: '否' },
      ],
      param: {
        CustomerId: null,
        SealId: null,
        OwningWarehouse: null,
        CanReceiver: null,
        CreateTime: [],
      },
      PageIndex: 1,
      PageSize: 20,
      total: 0
    }
  },
  filters: {
    getLastTimeAsArrearsTime(datetimeStr) {
      if(!datetimeStr) return ''
      const list = datetimeStr.split('.')
      return list.length > 0 ? list[0] : datetimeStr
    }
  },
  computed: {
    ...mapGetters(["roles"]),
    // 销售按钮
    getSellRoles() {
      if(this.roles.length === 0) return false
      const systemIs = this.roles.some((item) => item.includes('系统管理员'))
      if (systemIs) return systemIs
      const salesIs = this.roles.some((item) => item.includes('销售'))
      return !salesIs
    },
    paginatedData() {
      const start = (this.PageIndex - 1) * this.PageSize;
      const end = this.PageIndex * this.PageSize;
      return this.tableList.slice(start, end);
    }
  },
  created() {
    _getCustomers().then((resp) => {
      this.customers = resp
    })
    _getSalesmanUsers().then((response) => {
      this.salesmanUser = response
    })
    _getOwningWarehouseTypes().then((response) => {
      this.owningWarehouseTypes = response
    })
    const end = addDays(new Date(), 1)
    const start = addDays(end, -30)
    this.param.CreateTime = [
      DateFormat(start, 'yyyy-MM-dd'),
      DateFormat(end, 'yyyy-MM-dd')
    ]
  },
  watch: {
    tableList: {
      handler(newData) {
        this.total = newData.length;
      },
      immediate: true
    }
  },
  methods: {

    colFormatDate,
    detailPagerSearch(newPage){
      this.detailPageIndex =newPage
    },
    showDetail(qm){
      this.dialogDetail =true;
      this.detailLoading=true;
      var that=this;
      _getTransferWarehouseLogs({
        CreateTime:that.param.CreateTime,
        customerId:qm.CustomerId,
        LastOperUserId:qm.LastOperUserId
      }).catch(r=>{
        this.$alert(r, '异常提示', {
          confirmButtonText: '确定',
        });
      }).then(r=>{
        debugger
        this.dialogDetails = r;
        this.detailTotal = r.length;
      }).finally(r=>{
        this.detailLoading=false;
      })
    },
    detailSizeChange(newSize){
      this.detailPageSize =newSize
      this.detailPageIndex = 1;

    },
    pagerSearch(newPage) {
      this.PageIndex = newPage;
    },
    sizeChange(newSize) {
      this.PageSize = newSize;
      this.PageIndex = 1;
    },
    notice(data){
      const that=this;
      this.$set(data, 'noticeLoading', true)
      _sendArrearsFile({
        CreateTime:that.param.CreateTime,
        customerId:data.CustomerId
      }).then(res=>{
        if (res && res.code === 200) {
          this.$message({
            message: '通知成功',
            type: 'success'
          })
        } else {
          const message = res.message || res.Message || res.Error
          this.$alert(message, '异常提示', {
            confirmButtonText: '确定',
          });
        }
      }).catch(r=>{
        this.$alert(r, '异常提示', {
          confirmButtonText: '确定',
        });
      }).finally(() => {
        this.$set(data, 'noticeLoading', false)
      });
    },
    search() {
      const that = this
      const isFlag = that.getIsCreateTime()
      if (isFlag) {
        return
      }
      that.loading = true
      _queryFinanceGetArrears(that.param).then(
        (resp) => {
          this.tableList = resp
          that.loading = false
        }).catch(r=>{
        this.$alert(r, '异常提示', {
          confirmButtonText: '确定',
        });
      }).finally(() => {
        that.loading = false
      })
    },
    // 重置
    reset() {
      const end = addDays(new Date(), 1)
      const start = addDays(end, -6)
      this.param.PageIndex = 1
      this.param.PageSize = 100
      this.param.CreateTime = [DateFormat(start, 'yyyy-MM-dd'),DateFormat(end, 'yyyy-MM-dd')]
      this.param.CustomerId = null
      this.param.SealId = null
      this.param.OwningWarehouse = null
      this.param.CanReceiver = false
      this.search()
    },
    // 导出
    onExport() {
      const that = this
      const isFlag = that.getIsCreateTime()
      if (isFlag) {
        return
      }
      _outDownloadArrearsData(that.param)
    },
    getIsCreateTime() {
      const that = this
      if (!that.param.CreateTime || that.param.CreateTime.length === 0) {
        this.$message({
          message: '时间范围不能为空！',
          type: 'warning'
        })
        return true
      }
      return false
    }
  }
}
</script>
<style scoped>
.arrears-reminder .item-type {
  display: inline-flex;
  width: 180px;
}
.arrears-reminder .page-warp {
padding-top: 8px;
}
</style>
