<template>
  <div class="m-container">
    <h2>
      <div class="squrt"></div>
      销售列表
    </h2>
    <div class="m-core">
      <!-- 搜索类型 -->
      <save-form
        :inline="true"
        class="searchForm"
        :model="searchForm"
        @submit="search"
        @reset="onReSet"
      >
        <el-form-item>
          <el-input
            v-model.trim="searchForm.search"
            placeholder="请输入流水号、订单号"
            clearable
            type="text"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            placeholder="学生姓名"
            clearable
            type="text"
            v-model.trim="searchForm.userName"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model.trim="searchForm.goodsName"
            placeholder="请输入商品名称"
            clearable
            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 selects.branchs"
              :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="searchForm.orderDate"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="销售开始日期"
            end-placeholder="销售结束日期"
            :picker-options="{ firstDayOfWeek: 1 }"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button native-type="submit" type="danger">搜索</el-button>
          <el-button native-type="reset" type="primary">重置</el-button>
        </el-form-item>
      </save-form>
      <div
        class="newBand"
        @click="onOrderExport"
        v-permission="'export/exportSellOrders'"
      >
        报表导出
      </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="交易流水号"
          >
            <template slot-scope="scope">
              <div>
                <copy-text>{{ scope.row.transNo }}</copy-text>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="orderNo" label="订单号" width="180px">
            <template slot-scope="scope">
              <div>
                <copy-text>{{ scope.row.orderNo }}</copy-text>
              </div>
            </template>
          </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="商品名称" width="200px">
            <template slot-scope="scope">
              <div>
                <copy-text>{{ scope.row.goodsName }}</copy-text>
              </div>
            </template>
          </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="学员姓名">
            <template slot-scope="scope">
              <div>
                <copy-text>{{ scope.row.userName }}</copy-text>
              </div>
            </template>
          </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="所属分部">
            <template slot-scope="scope">
              <div>
                <copy-text>{{ scope.row.organName }}</copy-text>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="schoolName" label="所属学校">
            <template slot-scope="scope">
              <div>
                <copy-text>{{ scope.row.schoolName }}</copy-text>
              </div>
            </template>
          </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="退货后该销售金额将退还到学员账户余额"
                @confirm="() => 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
          sync
          :total.sync="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">
            <remote-search
              :commit="'setEducations'"
              v-model="form.eduTeacherId"
            />
          </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";
import { getTimes } from "@/utils";
import cleanDeep from 'clean-deep'
export default {
  components: { pagination },
  name: "backMoney",
  data() {
    return {
      paymentChannelStatus: paymentChannelStatus,

      refundVisible: false,
      detail: {},
      searchForm: {
        search: "",
        goodsName: "",
        cooperationOrganId: "",
        organIdList: [],
        userName: "",
        orderDate: [],
      },
      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() {
    this.$store.dispatch("setBranchs");
    getCooperation({ rows: 1000 }).then((res) => {
      if (res.code == 200) {
        this.cooperations = res.data.rows;
      }
    });

    if (this.searchForm.orderDate?.length < 1) {
      var now = new Date();
      var startDate = dayjs().format("YYYY-MM-DD");
      var endDate = dayjs().format("YYYY-MM-DD");
      this.searchForm.orderDate = [];
      this.searchForm.orderDate.push(startDate);
      this.searchForm.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 { orderDate, ...rest } = this.searchForm;
      let params = {
        ...rest,
        page: this.pageInfo.page,
        rows: this.pageInfo.limit,
        ...getTimes(orderDate, ["startTime", "endTime"]),
      };

      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;
        }
      });
    },

    onReSet() {
      this.searchForm = {
        startTime: null,
        endTime: null,
        organIdList: [],
        search: "",
        goodsName: [],
        cooperationOrganId: "",
        orderDate:[dayjs().format("YYYY-MM-DD"), dayjs().format("YYYY-MM-DD")]
      };
      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,
              });
            });
          } else {
            this.$message.error(res.msg)
          }
        });
    },
    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 { orderDate, ...rest } = this.searchForm;
      let params = {
        ...rest,
        page: this.pageInfo.page,
        rows: this.pageInfo.limit,
        ...getTimes(orderDate, ["startTime", "endTime"]),
      };
      Export(
        this,
        {
          url: "/api-web/export/exportSellOrders",
          fileName:`销售列表导出.xls`,
          params:cleanDeep( {
            ...params,
            organIdList: [...this.searchForm.organIdList].join(),
          }),
        },
        "是否确认导出报表？"
      );
    },
  },
};
</script>
<style lang="scss">
</style>
