<template>
  <div class="m-container">
    <h2>
      <div class="squrt"></div>销售列表
    </h2>
    <div class="m-core">
      <!-- 搜索类型 -->
      <el-form :inline="true"
               class="searchForm"
               v-model.trim="searchForm">

        <el-form-item>
          <el-input v-model.trim="searchForm.search"
                    placeholder="请输入流水号、订单号"
                    type="text"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input placeholder="学生姓名"
                    type="text"
                    v-model.trim="searchForm.userName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model.trim="searchForm.goodsName"
                    placeholder="请输入商品名称"
                    type="text"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select multiple
                     collapse-tags
                     v-model="searchForm.organIdList"
                     clearable
                     filterable
                     placeholder="请选择所属分部">
            <el-option v-for="(item,index) in organList"
                       :key="index"
                       :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select clearable
                     filterable
                     placeholder="请选择所属学校"
                     v-model="searchForm.cooperationOrganId">
            <el-option v-for="(item,index) in cooperations"
                       :key="index"
                       :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item>
          <el-select clearable filterable placeholder="请选择销售类型" v-model="searchForm.saleType">
            <el-option label="1" value="1"></el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item>
          <el-select clearable filterable placeholder="请选择交易方式" v-model="searchForm.paymentChannel">
            <el-option v-for="item in paymentChannelStatus" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-date-picker style="width:410px;"
                          v-model.trim="orderDate"
                          type="daterange"
                          value-format="yyyy-MM-dd"
                          @change="searchOrderDate"
                          range-separator="至"
                          start-placeholder="销售开始日期"
                          end-placeholder="销售结束日期"
                          :picker-options="{ firstDayOfWeek: 1 }">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="search"
                     type="danger">搜索</el-button>
          <el-button @click="onReSet"
                     type="primary">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="newBand"
           @click="onOrderExport"
           v-permission="{child: 'export/exportSellOrders', parent: '/salesList'}">报表导出</div>
      <!-- 列表 -->
      <div class="tableWrap">
        <el-table :data='tableList'
                  style="width: 100%"
                  :header-cell-style="{background:'#EDEEF0',color:'#444'}">
          <el-table-column align='center'
                           width="150"
                           prop="transNo"
                           label="交易流水号"></el-table-column>
          <el-table-column align='center'
                           prop="orderNo"
                           label="订单号"></el-table-column>
          <el-table-column align='center'
                           prop="sellTime"
                           label="销售日期">
            <template slot-scope="scope">
              {{scope.row.sellTime | dateForMinFormat}}
            </template>
          </el-table-column>
          <el-table-column align='center'
                           prop="type"
                           label="销售类型">
            <template slot-scope="scope">{{ scope.row.type | saleType }}</template>
          </el-table-column>
          <el-table-column align='center'
                           prop="goodsName"
                           label="商品名称"></el-table-column>
          <el-table-column align='center'
                           prop="num"
                           label="数量"></el-table-column>
          <el-table-column align='center'
                           width="100"
                           prop="expectAmount"
                           label="应付金额(元)">
            <template slot-scope="scope">
              <div>
                {{scope.row.expectAmount|moneyFormat}}
              </div>
            </template>
          </el-table-column>
          <el-table-column align='center'
                           width="100"
                           prop="balanceAmount"
                           label="余额支付(元)">
            <template slot-scope="scope">
              <div>
                {{scope.row.balanceAmount|moneyFormat}}
              </div>
            </template>
          </el-table-column>
          <el-table-column align='center'
                           width="100"
                           prop="actualAmount"
                           label="现金支付(元)">
            <template slot-scope="scope">
              <div>
                {{scope.row.actualAmount|moneyFormat}}
              </div>
            </template>
          </el-table-column>
          <el-table-column align='center'
                           width="100"
                           prop="sellCost"
                           label="销售成本(元)">
            <template slot-scope="scope">{{ (scope.row.sellCost * scope.row.num)| moneyFormat}}</template>
          </el-table-column>
          <el-table-column align='center'
                           prop="userName"
                           label="学员姓名"></el-table-column>
          <!-- <el-table-column align='center' prop="remark" label="退费说明"></el-table-column> -->
          <el-table-column align='center'
                           prop="paymentChannel"
                           label="交易方式">
            <template slot-scope="scope">{{ scope.row.paymentChannel | paymentChannelStatus }}</template>
          </el-table-column>
          <el-table-column align='center'
                           prop="merNo"
                           label="收款账户"></el-table-column>
          <el-table-column align='center'
                           prop="accountType"
                           label="账户类型">
            <template slot-scope="scope">{{ scope.row.accountType | accountTypeFormat }}</template>
          </el-table-column>
          <el-table-column align='center'
                           prop="stockType"
                           label="扣减库存">
            <template slot-scope="scope">{{ scope.row.stockType | stockTypeFormat }}</template>
          </el-table-column>
          <el-table-column align='center'
                           prop="organName"
                           label="所属分部"></el-table-column>
          <el-table-column align='center'
                           prop="schoolName"
                           label="所属学校"></el-table-column>
          <el-table-column align='center'
                           prop="eduTeacher"
                           label="乐团主管"></el-table-column>
          <el-table-column align='center'
                           prop="receiveStatus"
                           label="确认收货">
            <template slot-scope="scope">{{ scope.row.receiveStatus | receiveFormat }}</template>
          </el-table-column>
          <el-table-column align='center'
                           prop="status"
                           label="状态">
            <template slot-scope="scope">{{scope.row.status === 1 ? '已退货': ''}}</template>
          </el-table-column>
          <el-table-column align='center'
                           fixed="right"
                           width="150px"
                           label="操作">
            <template slot-scope="scope">
              <el-button @click="onBackMoney(scope.row)"
                         v-permission="'sellOrder/update'"
                         type="text">修改成本</el-button>
              <el-popconfirm title="退货后该销售金额将退还到学员账户余额"
                             @onConfirm="() => refund({id: scope.row.id})"
                             v-if="scope.row.status === 0"
                             v-permission="'sellOrder/refund'">
                <el-button type="text"
                           slot="reference">退费</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <pagination :total="pageInfo.total"
                    :page.sync="pageInfo.page"
                    :limit.sync="pageInfo.limit"
                    :page-sizes="pageInfo.page_size"
                    @pagination="getList" />
      </div>
      <el-dialog title="退费"
                 width="400px"
                 :visible.sync="refundVisible"
                 @close="refundVisible = false">
        <el-form :model="refundForm"
                 :rules="refundRules"
                 ref="refundform">
          <el-form-item label="退费金额"
                        prop="money"
                        label-width="100px">
            <el-input v-model="refundForm.money"
                      type="number"
                      placeholder="请输入退费金额" />
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="refundVisible = false">取消</el-button>
          <el-button type="primary"
                     @click="submitRefund">确认</el-button>
        </span>
      </el-dialog>
      <el-dialog title="修改成本"
                 :visible.sync="backStatus"
                 @close="onFormClose('ruleForm')"
                 width="500px">
        <el-form :model="form"
                 :rules="rules"
                 ref="ruleForm">
          <el-form-item label="交易流水号"
                        :label-width="formLabelWidth">
            {{ detail.transNo }}
          </el-form-item>
          <el-form-item label="订单号"
                        :label-width="formLabelWidth">
            {{ detail.orderNo }}
          </el-form-item>
          <el-form-item label="销售日期"
                        :label-width="formLabelWidth">
            {{ detail.sellTime | dateForMinFormat }}
          </el-form-item>
          <el-form-item label="学员姓名"
                        :label-width="formLabelWidth">
            {{ detail.userName }}
          </el-form-item>
          <el-form-item label="所属分部"
                        :label-width="formLabelWidth">
            {{ detail.organName }}
          </el-form-item>
          <el-form-item label="所属学校"
                        :label-width="formLabelWidth">
            {{ detail.schoolName }}
          </el-form-item>
          <el-form-item label="商品名称"
                        :label-width="formLabelWidth">
            {{ detail.goodsName }}
          </el-form-item>
          <!-- <el-form-item label="商品型号" :label-width="formLabelWidth">
            {{ form.name }}
          </el-form-item> -->
          <el-form-item label="应付金额(元)"
                        :label-width="formLabelWidth">
            {{ detail.expectAmount }}
          </el-form-item>
          <el-form-item label="单件成本(元)"
                        prop="amount"
                        :label-width="formLabelWidth">
            <!-- <el-input autocomplete="off"></el-input> -->
            <el-autocomplete v-model="form.sellCost"
                             class="inline-input"
                             :fetch-suggestions="querySearch"
                             placeholder="请输入成本"></el-autocomplete>
          </el-form-item>
          <el-form-item label="乐团主管"
                        :label-width="formLabelWidth">
            <el-select v-model.trim="form.eduTeacherId"
                       filterable
                       clearable
                       placeholder="请选择乐团主管">
              <el-option v-for="(item,index) in educationList"
                         :key="index"
                         :value="item.userId"
                         :label="item.userName"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="backStatus = false">取消</el-button>
          <el-button type="primary"
                     @click="onTeachingSubmit('ruleForm', 'DONE')">确认</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import pagination from '@/components/Pagination/index'
import { getSellOrder, updateSellOrder, refundSellOrder } from '@/api/orderManager'
import { getEmployeeOrgan, getCooperation, findEducationUsers } from '@/api/buildTeam'
import { paymentChannelStatus } from '@/utils/searchArray'
import { Export } from '@/utils/downLoadFile'
import dayjs from 'dayjs'
export default {
  components: { pagination },
  name: 'backMoney',
  data () {
    return {
      paymentChannelStatus: paymentChannelStatus,
      orderDate: null,
      refundVisible: false,
      detail: {},
      searchForm: {
        search: '',
        goodsName: '',
        cooperationOrganId: '',
        startTime: null,
        endTime: null,
        organIdList: [],
        userName: ''
      },
      tableList: [],
      organList: [],
      educationList: [],
      pageInfo: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50] // 选择限制显示条数
      },
      backStatus: false,
      formLabelWidth: '150px',
      form: {
        id: null,
        sellCost: null,
        eduTeacherId: null
      },
      rules: {
        sellCost: [{ required: true, message: '请输入金额', trigger: 'input' }],
      },
      refundForm: {
        money: null,
      },
      refundRules: {
        money: [{ required: true, message: '请输入退费金额', trigger: 'blur' }],
      },
      cooperations: [],
      restaurants: [],
    }
  },
  mounted () {
    getEmployeeOrgan().then(res => {
      if (res.code == 200) {
        this.organList = res.data;
      }
    })
    findEducationUsers().then(res => {
      if (res.code == 200) {
        this.educationList = res.data;
      }
    });
    getCooperation({ 'rows': 1000, })
      .then(res => {
        if (res.code == 200) {
          this.cooperations = res.data.rows;
        }
      })
    var now = new Date();
    var startDate = dayjs().format('YYYY-MM-DD');
    var endDate = dayjs().format('YYYY-MM-DD');
    this.orderDate = [];
    this.orderDate.push(startDate)
    this.orderDate.push(endDate)
    this.getList()
  },
  methods: {
    search () {
      this.pageInfo.page = 1;
      this.getList()
    },
    onTeachingSubmit (formName, status) { // 添加数据
      this.$refs[formName].validate((valid) => {
        if (valid) {
          updateSellOrder(this.form).then(res => {
            if (res.code == 200) {
              this.$message.success('操作成功')
              this.backStatus = false
              this.getList()
            } else {
              this.$message.error(res.msg)
            }
          })
        } else {
          return false;
        }
      })
    },
    getList () {
      let params = this.searchForm
      params.rows = this.pageInfo.limit
      params.page = this.pageInfo.page
      this.searchOrderDate(this.orderDate)
      getSellOrder({
        ...params,
        organIdList: [...this.searchForm.organIdList].join()
      }).then(res => {
        let result = res.data
        if (res.code == 200) {
          this.tableList = result.rows
          this.pageInfo.total = result.total
        }
      })
    },
    searchOrderDate (value) {
      if (value) {
        this.searchForm.startTime = value[0]
        this.searchForm.endTime = value[1]
      } else {
        this.searchForm.startTime = null
        this.searchForm.endTime = null
      }
    },
    onReSet () {
      this.orderDate = null
      this.searchForm = {
        startTime: null,
        endTime: null,
        organIdList: [],
        search: '',
        goodsName: [],
        cooperationOrganId: '',
      }
      this.getList()
    },
    querySearch (queryString, cb) {
      let restaurants = []
      try {
        const json = JSON.parse(this.detail.sellCost2)
        restaurants = [{ value: String(json.sellCost || '') }, { value: String(json.SellCost2 || '') }].filter(item => !!item)
      } catch (error) { }
      // this.createFilter(queryString)
      // let results = queryString ? restaurants.filter((restaurant) => {
      //   return restaurant && restaurant.value && String(restaurant.value).indexOf(queryString) === 0
      // }) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(restaurants);
    },
    onFormClose (formName) { // 关闭弹窗重置验证
      this.$refs[formName].clearValidate()
    },
    refund (data) {
      refundSellOrder(data)
        .then(res => {
          this.getList()
          this.$message.success('退费成功')
        })
        .catch(res => {
          if (res.code === 100) {
            this.$confirm(res.msg, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then(() => {
                this.refund({
                  ...data,
                  reTry: true
                })
              })
          }
        })
    },
    openRefund (row) {
      this.refundVisible = true
      this.detail = row
    },
    submitRefund () {

    },
    onBackMoney (row) { // 退费
      this.backStatus = true
      this.detail = row
      this.form = {
        id: row.id,
        sellCost: String(row.sellCost),
        eduTeacherId: row.eduTeacherId ? row.eduTeacherId : null
      }
      // applyRefundAudit()
    },
    onOrderExport () {
      let params = this.searchForm
      params.rows = this.pageInfo.limit
      params.page = this.pageInfo.page
      this.searchOrderDate(this.orderDate)
      Export(this, {
        url: '/api-web/export/exportSellOrders',
        params: {
          ...params,
          organIdList: [...this.searchForm.organIdList].join()
        }
      }, '是否确认导出报表？')
    }
  }
}
</script>
<style lang="scss">
</style>
