<template>
  <div id="OrderManageList">
    <search-box-new
      ref="searchBox"
      :formData="formData"
      :formList="formList"
      @search="search"
      @init="init"
    />
    <div style="margin-bottom: 12px">
      <el-button type="primary" size="small" @click="editCost"
        >成本设置</el-button
      >
      <el-button
        v-if="false"
        type="primary"
        size="small"
        @click="completeOrder(false)"
        >完单确认</el-button
      >
      <el-button type="primary" size="small" @click="editRemarks(1)"
        >修改备注</el-button
      >
      <el-button size="small" @click="exportExcel()">导出excel</el-button>
    </div>
    <div class="dis_flex_order_li">
      <div class="list" v-for="(item, index) in ShowTabList" :key="index">
        <img :src="item.img" alt="" />
        <div class="right">
          <h4>
            {{ item.label }}：
            <span
              v-if="item.label === '盈亏' && statisticsData[item.prop] !== 0"
              ><span
                :style="
                  statisticsData[item.prop] > 0
                    ? 'color:rgb(99,93,247)'
                    : 'color:red'
                "
                >【{{ statisticsData[item.prop] > 0 ? "盈" : "亏" }}】</span
              ></span
            >
          </h4>
          <p>
            {{
              item.ch === "元"
                ? formatPrice(statisticsData[item.prop])
                : statisticsData[item.prop]
            }}{{ item.ch }}
          </p>
        </div>
      </div>
    </div>
    <table-list
      rowKey="orderId"
      ref="tableList"
      :tableSets="tableSet"
      :tableData="tableData"
      :navText="navText"
      :loading="loading"
    >
      <template slot="orderInfo" slot-scope="props">
        <div>机构名称：{{ props.scope.row["tenantName"] }}</div>
        <div>业务员：{{ props.scope.row["createUsername"] }}</div>
        <div>业务号：{{ props.scope.row["createNo"] }}</div>
        <div>订单来源：{{ props.scope.row["orderOrg"] }}</div>
        <div>
          订单日期：{{ $methodsTools.onlyForma(props.scope.row["buyTime"]) }}
        </div>
        <div>订单号：{{ props.scope.row["orderSn"] }}</div>
      </template>
      <template slot="orderPrice" slot-scope="props">
        <div>合同金额：{{ props.scope.row["orderPrice"] }}</div>
        <div>已收账款：{{ props.scope.row["orderReceived"] }}</div>
        <div>申请退款：{{ props.scope.row["orderRefund"] }}</div>
        <div>已退账款：{{ props.scope.row["orderRefunded"] }}</div>
        <div>未收账款：{{ props.scope.row["orderUncollected"] }}</div>
        <div style="color: red">
          (预计收款时间){{
            $methodsTools.onlyForma(props.scope.row["predictReceiveTime"])
          }}
        </div>
        <div>实际账款：{{ props.scope.row["orderPractical"] }}</div>
      </template>
      <template slot="inon" slot-scope="props">
        <div>成本（元）：{{ props.scope.row["orderCost"] }}</div>
        <div>盈亏（元）：{{ props.scope.row["orderProfit"] }}</div>
        <div v-if="props.scope.row['orderProfit']">
          <span
            :style="
              props.scope.row['orderProfit'] > 0
                ? 'color:rgb(99,93,247)'
                : 'color:red'
            "
          >
            【{{ props.scope.row["orderProfit"] > 0 ? "盈" : "亏" }}】</span
          >
        </div>
      </template>
      <template slot="statusRoles" slot-scope="props">
        <div>
          {{ refundStatus(props.scope.row["refundStatus"])
          }}<span style="color: red" v-if="props.scope.row['refundName']"
            >({{ props.scope.row["refundName"] }})</span
          >
        </div>
      </template>
      <template slot="type" slot-scope="props">
        <div v-for="(item, index) in props.scope.row['businessNames']">
          {{ item }}
        </div>
      </template>
      <template slot="btn" slot-scope="props">
        <el-button type="text" @click="openDialog(props.scope.row)"
          >查看详情</el-button
        >
        <el-button type="text" @click="handelClickCost(props.scope.row)"
          >成本设置</el-button
        >
        <el-button
          type="text"
          @click="openDialog(props.scope.row, 1)"
          :disabled="
            props.scope.row.orderFrom !== 3 || props.scope.row.checkStatus === 3
          "
          >订单审核</el-button
        >
        <el-button
          type="text"
          @click="handelClick(props.scope.row)"
          :disabled="
            props.scope.row.refundStatus !== 0 &&
            props.scope.row.refundStatus !== 2
          "
          >退款审核</el-button
        >
        <el-button type="text" @click="editRemarks(props.scope.row)"
          >修改备注</el-button
        >
        <el-button type="text" @click="seePZ(props.scope.row.attachmentList)"
          >转账凭证</el-button
        >
        <el-button
          v-if="false"
          type="text"
          @click="completeOrder(props.scope.row.orderSn)"
          >完单确认</el-button
        >
      </template>
    </table-list>
    <pagination
      :total="total"
      :pageSize.sync="formData.pageSize"
      :currentPage.sync="formData.pageNum"
      @search="search"
    />
    <el-image-viewer
      v-if="showViewer"
      :on-close="
        () => {
          showViewer = false;
        }
      "
      :url-list="imgList"
    >
    </el-image-viewer>
    <dislog-set
      :dialogVisible.sync="dialogVisible"
      @search="search"
      :type="2"
      :orderSn="orderSn"
      :checkRoleName="orderInfo.refundName"
    ></dislog-set>
    <remarks
      :dialogVisible.sync="remarksVisible"
      @search="search"
      :options="remarksOptions"
    ></remarks>
    <dislogOrderDetails
      :dialogVisible.sync="orderDialogVisible"
      :orderSn="orderSn"
      :orderFrom="orderFrom"
      :ShowStatus="ShowStatus"
      @search="search"
    ></dislogOrderDetails>
    <dislog-set-cost
      :dialogVisible.sync="dialogVisiblecost"
      :tpId="tpId"
      :type="type"
      @search="search"
    ></dislog-set-cost>
  </div>
</template>

<script>
import { exportFn } from "@/utils/index.js";
import dislogSetCost from "../cost/dislogSet.vue";
import dislogSet from "../components/refund/dislogSet.vue";
import remarks from "../components/remarks.vue";
import searchBoxNew from "@/components/searchBoxNew";
import tableList from "@/components/tableList";
import pagination from "@/components/pagination";
import dislogOrderDetails from "../components/dislogOrderDetails.vue";
export default {
  name: "OrderManageList",
  components: {
    searchBoxNew,
    tableList,
    pagination,
    dislogSet,
    remarks,
    dislogOrderDetails,
    dislogSetCost,
    "el-image-viewer": () =>
      import("element-ui/packages/image/src/image-viewer"),
  },
  data() {
    return {
      showViewer: false,
      imgList: [],
      ShowTabList: [
        {
          label: "盈亏",
          prop: "orderProfitTotal",
          img: require("@/assets/images/盈亏@2x.png"),
          price: "1200000000",
          ch: "元",
        },
        {
          label: "合同金额",
          prop: "orderPriceTotal",
          img: require("@/assets/images/合同金额@2x.png"),
          price: "1200000000",
          ch: "元",
        },
        {
          label: "已收账款",
          prop: "orderReceivedTotal",
          img: require("@/assets/images/已收款@2x.png"),
          price: "1200000000",
          ch: "元",
        },
        {
          label: "已退账款",
          prop: "orderRefundedTotal",
          img: require("@/assets/images/已退款@2x.png"),
          price: "1200000000",
          ch: "元",
        },
        {
          label: "未收账款",
          prop: "orderUncollectedTotal",
          img: require("@/assets/images/未收款@2x.png"),
          price: "1200000000",
          ch: "元",
        },
        {
          label: "实际账款",
          prop: "practicalPriceTotal",
          img: require("@/assets/images/实际款@2x.png"),
          price: "1200000000",
          ch: "元",
        },
        {
          label: "成本金额",
          prop: "orderCostTotal",
          img: require("@/assets/images/成本金额@2x.png"),
          price: "1200000000",
          ch: "元",
        },
        {
          label: "订单人数",
          prop: "orderUserNum",
          img: require("@/assets/images/订单人数@2x.png"),
          price: "16102",
          ch: "个",
        },
        {
          label: "订单数",
          prop: "orderNum",
          img: require("@/assets/images/订单数@2x.png"),
          price: "16201",
          ch: "个",
        },
      ],
      loading: false, //当前表单加载是否加载动画
      navText: {
        title: "订单管理",
        index: 0,
        ch: "条",
        num: true,
        choice: true,
        addHide: true,
        openCheckMore: true,
        changeWidth: "100px",
        custom: false,
        backFatherBtn: {
          status: false,
          title: "配置下单填选模板",
        },
      },
      //搜索
      formList: [
        {
          prop: "roleId",
          placeholder: "角色分类",
          scope: "select",
          options: [
            { label: "会计", value: 0 },
            { label: "财务", value: 1 },
            { label: "出纳", value: 2 },
          ],
        },
        // {
        //   prop: "businessFullName",
        //   placeholder: "业务分类",
        //   scope: "select",
        //   options: [
        //     { label: "学校业务", value: 1 },
        //     { label: "办证质询", value: 2 },
        //   ],
        // },
        {
          prop: "educationTypeId",
          placeholder: "教育类型",
          scope: "educationType",
          schemeName: true,
        },
        {
          prop: "businessId",
          placeholder: "业务层次",
          scope: "businessLevel",
          edu: "educationTypeId",
        },
        {
          prop: "checkStatus",
          placeholder: "审核状态",
          scope: "select",
          options: [
            { label: "待审核", value: 0 },
            { label: "已通过", value: 1 },
            { label: "未通过", value: 2 },
            { label: "已撤销", value: 3 },
          ],
        },
        {
          prop: "refundStatus",
          placeholder: "退款状态",
          scope: "select",
          options: [
            { label: "待审核", value: 0 },
            { label: "正常", value: 1 },
            { label: "未退款", value: 2 },
            { label: "已完成", value: 3 },
            { label: "未通过", value: 4 },
            { label: "支付中", value: 5 },
            { label: "支付失败", value: 6 },
          ],
        },
        {
          prop: "creditStatus",
          placeholder: "账款状态",
          scope: "select",
          options: [
            { label: "已结清", value: 1 },
            { label: "未结清", value: 0 },
          ],
        },
        {
          prop: "invoiceStatus",
          placeholder: "开票状态",
          scope: "select",
          options: [
            { label: "已开票", value: 1 },
            { label: "未开票", value: 0 },
          ],
        },
        {
          placeholder: "时间",
          prop1: "startTime",
          prop2: "endTime",
          placeholder1: "开始日期",
          placeholder2: "结束日期",
          scope: "moreDataPicker",
          Diszing: true,
        },
        {
          prop: "orderSn",
          placeholder: "订单号",
        },
        {
          prop: "userCard",
          placeholder: "身份号",
        },
      ],
      formData: {
        pageSize: 10,
        pageNum: 1,
      },
      // 表单
      tableSet: [
        {
          label: "订单信息",
          prop: "name",
          hidden: true,
          scope: "solt",
          soltName: "orderInfo",
          width: "300px",
        },
        {
          label: "订单金额（元）",
          prop: "posterTempName",
          hidden: true,
          scope: "solt",
          soltName: "orderPrice",
        },
        {
          label: "投入产出",
          prop: "posterTempName1",
          hidden: true,
          scope: "solt",
          soltName: "inon",
        },
        {
          label: "审核状态",
          prop: "checkStatus",
          scope: "isOptions",
          hidden: true,
          options: [
            {
              label: "待审核",
              value: 0,
            },
            {
              label: "已通过",
              value: 1,
            },
            {
              label: "未通过",
              value: 2,
            },
            {
              label: "已撤销",
              value: 3,
            },
          ],
        },
        {
          label: "学员审核状态",
          prop: "studentCheckStatus",
          scope: "isOptions",
          hidden: true,
          options: [
            {
              label: "待审核",
              value: 0,
            },
            {
              label: "已审核",
              value: 1,
            },
          ],
        },
        {
          label: "退款状态",
          prop: "startTime",
          hidden: true,
          scope: "solt",
          soltName: "statusRoles",
        },
        {
          label: "下单企业",
          prop: "orderOrg",
          hidden: true,
        },
        {
          label: "业务类型",
          prop: "businessNames",
          hidden: true,
          scope: "solt",
          soltName: "type",
        },
        {
          label: "发票状态",
          prop: "invoiceStatus",
          hidden: true,
          scope: "isOptions",
          options: [
            {
              label: "未开票",
              value: 0,
            },
            {
              label: "已开票",
              value: 1,
            },
          ],
        },
        {
          label: "备注",
          prop: "remark",
          hidden: true,
        },
      ],
      tableData: [], //表单数据
      total: 0, //一共多少条
      dialogVisible: false,
      remarksVisible: false,
      orderDialogVisible: false,
      id: "",
      statisticsData: {},
      remarksOptions: [],
      orderSn: null,
      orderFrom: null,
      ShowStatus: false,
      dialogVisiblecost: false,
      tpId: "",
      type: null,
      orderInfo: {},
    };
  },
  created() {
    this.search();
    this.getStatistics();
  },
  methods: {
    formatPrice(price) {
      return price?.toLocaleString(
        "zh-CN",
        (undefined, { minimumFractionDigits: 2, maximumFractionDigits: 4 })
      );
    },
    //退款状态
    refundStatus(i) {
      var str = "";
      switch (i) {
        case 0:
          str = "待审核";
          break;
        case 1:
          str = "正常";
          break;
        case 2:
          str = "未退款";
          break;
        case 3:
          str = "已完成";
          break;
        case 4:
          str = "未通过";
          break;
        case 5:
          str = "支付中";
          break;
        case 6:
          str = "支付失败";
          break;
        default:
          break;
      }
      return str;
    },
    exportExcel() {
      var b = 1;
      var a = "0,1";
      if (this.$refs.tableList.allCheckData.length === 0) {
        this.$message.error("请勾选数据");
        return;
      }
      this.$api
        .systemtoporderexport({
          orderSnList: this.$refs.tableList.allCheckData.map((i) => i.orderSn),
        })
        .then((res) => {
          exportFn(res.msg, `导出数据`);
        });
    },

    editCost() {
      if (this.$refs.tableList.allCheckData.length === 0) {
        this.$message.error("请勾选数据");
        return;
      }
      this.dialogVisiblecost = true;
      this.type = 4;
      this.tpId = this.$refs.tableList.allCheckData
        .map((i) => i.orderSn)
        .toString();
    },
    completeOrder(orderSn) {
      let A = (status) => {
        this.$api
          .systemtoporderfinish({
            finishStatus: status,
            orderSnList: orderSn
              ? [orderSn]
              : this.$refs.tableList.allCheckData.map((i) => i.orderSn),
          })
          .then((res) => {
            this.$message({
              type: "success",
              message: "操作成功!",
            });
          });
      };
      if (!orderSn && this.$refs.tableList.allCheckData.length === 0) {
        this.$message.error("请勾选数据");
        return;
      }
      this.$confirm("确定已完单吗?", "提示", {
        confirmButtonText: "确定完单",
        cancelButtonText: "取消完单",
        type: "warning",
        distinguishCancelAndClose: true,
      })
        .then(() => {
          A(1);
        })
        .catch((err) => {
          if (err === "cancel") {
            A(0);
          }
        });
    },
    handelClickCost(item) {
      this.dialogVisiblecost = true;
      this.type = 3;
      this.tpId = item.orderSn;
    },
    openDialog(data, e) {
      if (e === 1) {
        this.ShowStatus = true;
      } else {
        this.ShowStatus = false;
      }
      this.orderInfo = data;
      this.orderSn = data.orderSn;
      this.orderFrom = data.orderFrom;
      this.orderDialogVisible = true;
    },
    seePZ(ary) {
      if (ary?.length > 0) {
        this.imgList = ary.map((item) => item.attachmentUrl);
        this.showViewer = true;
      } else {
        this.$message.warning("暂无转账凭证");
        this.imgList = [];
        return;
      }
    },
    getStatistics() {
      this.$api.systemtoporderstatistics().then((res) => {
        this.statisticsData = res.data || {};
      });
    },
    editRemarks(item) {
      if (item === 1) {
        if (this.$refs.tableList.allCheckData.length === 0) {
          this.$message.error("请勾选数据");
          return;
        }
        this.remarksOptions = this.$refs.tableList.allCheckData;
        this.remarksVisible = true;
      } else {
        this.remarksOptions = [item];
        this.remarksVisible = true;
      }
    },
    handelClick(data) {
      this.orderSn = data.orderSn;
      this.dialogVisible = true;
    },
    changeStatus(val) {
      console.log(val);
    },
    batchDel() {
      let len = this.$refs.tableList.allCheckData.length;
      if (!len) {
        return this.$message.warning("请先勾选模板");
      }
      const ids = this.$refs.tableList.allCheckData.map((item) => item.id);
    },
    handelDel(id) {
      this.$confirm("此操作将删除该模板, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$api.editUser(id).then((res) => {
            if (res.code === 200) {
              this.$message.success("删除成功");
              this.search();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    search(v) {
      this.loading = true;
      if (this.type === 4) {
        this.$refs.tableList.clearMoreActive();
        this.type = null;
      }
      if (v === 2) {
        this.formData = {
          pageSize: 10,
          pageNum: 1,
        };
        this.$nextTick(() => {
          this.$refs.tableList.clearMoreActive();
        });
      }
      var data = JSON.parse(JSON.stringify(this.formData));
      if (data.roleId === 0 || data.roleId === 1) {
        data.refundStatusList = "0,3,4";
      }
      if (data.roleId === 2) {
        data.refundStatusList = "2,3";
      }
      if (this.formData.startTime) {
        data.startTime = parseInt(data.startTime / 1000);
      }
      if (this.formData.endTime) {
        data.endTime = parseInt(data.endTime / 1000);
      }
      this.$api
        .systemtoporderlist(data)
        .then((res) => {
          this.tableData = res.rows;
          this.total = res.total;
          this.navText.index = res.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    init() {
      this.search(2);
    },
  },
};
</script>

<style lang="scss" scoped>
.cell > .el-button + .el-button {
  margin-left: 0px;
}
.dis_flex_order_li {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  & > .list {
    user-select: none;
    cursor: pointer;
    transition: all 0.3s;
    box-shadow: 0px 0px 4px 1px rgba(0, 0, 0, 0.2);
    &:hover {
      transform: scale(1.04);
    }
    width: 136px;
    height: 44px;
    border-radius: 6px;
    display: flex;
    align-items: center;
    flex-shrink: 0;
    margin-right: 10px;
    margin-bottom: 10px;
    & > img {
      margin-left: 2px;
      width: 40px;
      height: 40px;
    }
    & > .right {
      flex: 1;
      padding-left: 4px;
      & > h4 {
        color: #000;
        margin: 0;
        font-size: 12px;
      }
      & > p {
        font-size: 12px;
        color: red;
        margin: 0;
      }
    }
  }
}
</style>
