<template>
  <div id="operate">
    <search-box-new
      class="search_box_page"
      ref="searchBox"
      :redIcon="false"
      :formData="formData"
      :formList="formList"
      @search="search"
      @init="init"
    />
    <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>
            {{
              formatPrice(
                statisticsData[item.prop],
                item.ch === "元" ? true : false
              )
            }}{{ item.ch }}
          </p>
        </div>
      </div>
    </div>
    <table-list
      rowKey="orderId"
      ref="tableList"
      :tableSets="tableSet"
      :tableData="tableData"
      :navText="navText"
      :loading="loading"
    >
      <template slot="customize">
        <el-checkbox
          v-if="false"
          style="margin-right: 10px"
          v-model="formData.check"
          :true-label="1"
          :false-label="0"
          >修改补款</el-checkbox
        >
        <el-button type="primary" size="small" @click="editCost"
          >成本设置</el-button
        >
        <el-button type="primary" size="small" @click="completeOrder(false, 1)"
          >完单确认</el-button
        >
        <el-button type="warning" size="small" @click="completeOrder(false, 0)"
          >完单取消</el-button
        >
        <el-button
          v-if="false"
          type="primary"
          size="small"
          @click="editRemarks(1)"
          >修改备注</el-button
        >
        <el-button size="small" @click="exportData" v-hasRole="derivePermission"
          >导出excel</el-button
        >
      </template>
      <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>
          订单金额：{{
            $methodsTools.decimalPoint(props.scope.row["orderPrice"])
          }}
        </div>
        <div>
          税前佣金：{{
            $methodsTools.decimalPoint(props.scope.row["pretaxBrokerage"])
          }}
        </div>
        <div>
          已收账款：{{
            $methodsTools.decimalPoint(props.scope.row["orderReceived"])
          }}
        </div>
        <div>
          申请退款：{{
            $methodsTools.decimalPoint(props.scope.row["orderRefund"])
          }}
        </div>
        <div>
          已退账款：{{
            $methodsTools.decimalPoint(props.scope.row["orderRefunded"])
          }}
        </div>
        <div>
          未收账款：{{
            $methodsTools.decimalPoint(props.scope.row["orderUncollected"])
          }}
        </div>
        <div style="color: red">
          (预计收款时间){{
            $methodsTools.onlyForma(props.scope.row["predictReceiveTime"])
          }}
        </div>
        <div>
          实际账款：{{
            $methodsTools.decimalPoint(props.scope.row["orderPractical"])
          }}
        </div>
        <div>
          <!-- 修改补款：{{$methodsTools.decimalPoint(props.scope.row[""])}} -->
        </div>
      </template>
      <template slot="inon" slot-scope="props">
        <div>
          成本（元）：{{
            $methodsTools.decimalPoint(props.scope.row["orderCost"])
          }}
        </div>
        <div>
          盈亏（元）：{{
            $methodsTools.decimalPoint(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, 1)"
          :disabled="disabledStatus(props.scope.row.commercialTenant)"
          >查看详情</el-button
        >
        <el-button
          v-if="orderFormShow(props.scope.row)"
          type="text"
          @click="handelClickCost(props.scope.row)"
          :disabled="disabledStatus(props.scope.row.commercialTenant)"
          >成本设置</el-button
        >
        <el-button
          type="text"
          @click="openDialog(props.scope.row, 2)"
          :disabled="
            (props.scope.row.orderFrom !== 3 &&
              props.scope.row.orderFrom !== 4) ||
            props.scope.row.checkStatus !== 0 ||
            disabledStatus(props.scope.row.commercialTenant)
          "
          >订单审核</el-button
        >
        <el-button
          v-if="orderFormShow(props.scope.row)"
          :disabled="props.scope.row.checkStatus !== 1"
          type="text"
          @click="handelClick(props.scope.row, 1)"
          >学员审核</el-button
        >
        <el-button
          v-if="orderFormShow(props.scope.row)"
          type="text"
          @click="handelClick(props.scope.row, 2)"
          :disabled="
            (props.scope.row.refundStatus !== 0 &&
              props.scope.row.refundStatus !== 2) ||
            disabledStatus(props.scope.row.commercialTenant) ||
            getRoles(props.scope.row.refundRoleId)
          "
          >退款审核</el-button
        >
        <el-button
          v-if="orderFormShow(props.scope.row)"
          type="text"
          @click="editRemarks(props.scope.row)"
          :disabled="disabledStatus(props.scope.row.commercialTenant)"
          >修改备注</el-button
        >
        <el-button
          v-if="orderFormShow(props.scope.row)"
          type="text"
          @click="seePZ(props.scope.row.attachmentList)"
          :disabled="disabledStatus(props.scope.row.commercialTenant)"
          >转账凭证</el-button
        >
        <el-button
          v-if="orderFormShow(props.scope.row)"
          type="text"
          :disabled="
            !(
              // props.scope.row.finishSign === 1 &&
              (props.scope.row.finishStatus === 0)
            ) || disabledStatus(props.scope.row.commercialTenant)
          "
          @click="completeOrder(props.scope.row.orderSn, 1)"
          >完单确认</el-button
        >
        <el-button
          v-if="orderFormShow(props.scope.row)"
          type="text"
          :disabled="
            props.scope.row.finishStatus !== 1 ||
            disabledStatus(props.scope.row.commercialTenant)
          "
          @click="completeOrder(props.scope.row.orderSn, 0)"
          >完单取消</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"
    ></dislog-set>
    <dislog-set-trainee
      :dialogVisible.sync="dialogVisibleTrainee"
      @search="search"
      :orderSn="orderSn"
    ></dislog-set-trainee>
    <remarks
      :dialogVisible.sync="remarksVisible"
      @search="search"
      :options="remarksOptions"
    ></remarks>
    <dislogOrderDetails
      :dialogVisible.sync="orderDialogVisible"
      :orderSn="orderSn"
      :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 "../../costSet/dislogOrganSet.vue";
import dislogSet from "../../components/refund/dislogSet.vue";
import dislogSetTrainee from "../../components/trainee/dislogSetTrainee.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: "Operate",
  components: {
    searchBoxNew,
    tableList,
    pagination,
    dislogSet,
    remarks,
    dislogOrderDetails,
    dislogSetCost,
    dislogSetTrainee,
    "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: "160px",
        custom: false,
        backFatherBtn: {
          status: false,
          title: "配置下单填选模板",
        },
        selectableStatus: true,
        selectableFunc: (row, rowIndex) => {
          if (row.commercialTenant === 1) {
            return false;
          } else {
            return true;
          }
        },
      },
      //搜索
      formList: [
        {
          prop: "educationTypeId",
          placeholder: "教育类型",
          scope: "educationType",
          schemeName: true,
        },
        {
          prop: "businessId",
          placeholder: "业务层次",
          scope: "businessLevel",
          edu: "educationTypeId",
        },
        {
          prop: "tenantId",
          placeholder: "所属机构",
          scope: "systemtenantlist",
        },
        {
          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: "finishStatus",
          placeholder: "完单状态",
          scope: "select",
          options: [
            { label: "已完单", value: 1 },
            { label: "未完单", value: 0 },
          ],
        },
        {
          prop: "orderOrg",
          placeholder: "输入订单来源",
        },
        {
          prop: "keyword",
          placeholder: "订单号/业务号/下单企业",
        },
        {
          prop: "userName",
          placeholder: "学员姓名",
        },
        {
          placeholder: "时间",
          prop1: "startTime",
          prop2: "endTime",
          placeholder1: "订单开始日期",
          placeholder2: "订单结束日期",
          scope: "moreDataPicker",
          Diszing: true,
        },
      ],
      formData: {
        pageSize: 10,
        pageNum: 1,
        checkStatus: 0,
        operationType: 1,
      },
      // 表单
      tableSet: [
        {
          label: "订单类型",
          prop: "",
          hidden: true,
        },
        {
          label: "业务类型",
          prop: "businessNames",
          hidden: true,
          scope: "solt",
          soltName: "type",
        },
        {
          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: "startTime",
          hidden: true,
          scope: "solt",
          soltName: "statusRoles",
        },
        {
          label: "学员状态",
          prop: "studentCheckStatus",
          scope: "isOptions",
          hidden: true,
          options: [
            {
              label: "待审核",
              value: 0,
            },
            {
              label: "已审核",
              value: 1,
            },
          ],
        },
        {
          label: "完单状态",
          prop: "finishStatus",
          scope: "isOptions",
          hidden: true,
          options: [
            { label: "已完单", value: 1 },
            { label: "未完单", value: 0 },
          ],
        },
        {
          label: "下单企业",
          prop: "purchaseOrg",
          hidden: true,
        },
        {
          label: "发票状态",
          prop: "invoiceStatus",
          hidden: true,
          scope: "isOptions",
          options: [
            {
              label: "未开票",
              value: 0,
            },
            {
              label: "已开票",
              value: 1,
            },
          ],
        },
        {
          label: "业务员备注",
          prop: "remark",
          hidden: false,
        },
        {
          label: "财务备注",
          prop: "financeRemark",
          hidden: false,
        },
      ],
      tableData: [], //表单数据
      total: 0, //一共多少条
      dialogVisible: false,
      dialogVisibleTrainee: false,
      remarksVisible: false,
      orderDialogVisible: false,
      id: "",
      statisticsData: {},
      remarksOptions: [],
      orderSn: null,
      ShowStatus: 0,
      dialogVisiblecost: false,
      tpId: "",
      type: null,
      orderInfo: {},
    };
  },
  created() {
    this.search();
    this.getStatistics(this.formData);
  },
  methods: {
    orderFormShow(row) {
      return row.orderFrom == 4 ? false : true;
    },
    getRoles(roleId) {
      if (
        (this.$store.state.user.rolesId?.length > 0 &&
          this.$store.state.user.rolesId.includes(roleId)) ||
        this.$store.state.user.rolesId.includes(1)
      ) {
        return false;
      } else {
        return true;
      }
    },
    disabledStatus(c) {
      if (c === 1) {
        return true;
      } else {
        return false;
      }
    },
    formatPrice(price, status) {
      return price?.toLocaleString(
        "zh-CN",
        (undefined,
        {
          minimumFractionDigits: status ? 2 : 0,
          maximumFractionDigits: status ? 4 : 0,
        })
      );
    },
    //退款状态
    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;
    },

    exportData() {
      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";
      }
      this.$api.systemtoporderexport(data).then((res) => {
        if (res.msg) {
          exportFn(res.msg, `导出数据`);
        } else {
          this.$message.error("导出失败");
        }
      });
    },

    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, type) {
      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: "操作成功!",
            });
            this.search(3);
          });
      };
      if (!orderSn && this.$refs.tableList.allCheckData.length === 0) {
        this.$message.error("请勾选数据");
        return;
      }
      if (
        this.$refs.tableList.allCheckData.every((i) => {
          if (type === 1) {
            return i.finishSign === 1 && i.finishStatus === 0;
          }
          if (type === 0) {
            return i.finishStatus === 1;
          }
        })
      ) {
        this.$confirm(type === 1 ? "确认" : "取消" + "完单状态?", "提示", {
          confirmButtonText: `${type === 1 ? "确认" : "取消"}完单`,
          cancelButtonText: "关闭",
          type: "warning",
          distinguishCancelAndClose: true,
        })
          .then(() => {
            A(type);
          })
          .catch((err) => {
            // if (err === "cancel") {
            //   A(0);
            // }
          });
      } else {
        this.$message.error("批量数据存在不允许操作数据，请联系管理员修复");
        return;
      }
    },
    handelClickCost(item) {
      this.dialogVisiblecost = true;
      this.type = 3;
      this.tpId = item.orderSn;
    },
    openDialog(data, e) {
      this.ShowStatus = e;
      this.orderInfo = data;
      this.orderSn = data.orderSn;
      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(datas) {
      var data = JSON.parse(JSON.stringify(datas));
      delete data.pageNum;
      delete data.pageSize;
      this.$api.systemtoporderstatistics(data).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, type) {
      // type = 1 学员 type = 2退款
      this.orderSn = data.orderSn;
      if (type == 1) {
        this.dialogVisibleTrainee = true;
      }
      if (type == 2) {
        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,
          checkStatus: 0,
          operationType: 1,
        };
        this.$nextTick(() => {
          this.$refs.tableList.clearMoreActive();
        });
      }
      if (v === 3) {
        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";
      }
      this.getStatistics(data);
      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>
.search_box_page {
  /deep/ .el-select {
    width: 120px;
  }
  /deep/ .el-form-item__content > .el-input {
    width: 190px;
  }
}
.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;
    background-color: rgb(243,249,255);
    padding: 4px;
    width: 170px;
    height: 60px;
    border-radius: 3px;
    display: flex;
    align-items: center;
    flex-shrink: 0;
    margin-right: 10px;
    margin-bottom: 10px;
    & > img {
      margin-left: 10px;
      width: 36px;
      height: 36px;
    }
    & > .right {
      flex: 1;
      padding-left: 4px;
      & > h4 {
        color: rgb(85, 85, 85);
        margin: 0;
        font-size: 12px;
      }
      & > p {
        font-size: 12px;
        color: #000;
        margin: 0;
      }
    }
  }
}
</style>
