<template>
  <div>
    <el-form :inline="true" ref="ruleForm">
      <div class="lookTitle">申请信息</div>
      <el-form-item label="申请人" label-width="80px">
        <div style="width: 180px">
          <p v-if="form.operator && form.operator.username">
            {{ form.operator.username }}
          </p>
        </div>
      </el-form-item>
      <el-form-item label="申请时间" label-width="80px">
        <div style="width: 180px">{{ form.createTime }}</div>
      </el-form-item>
    </el-form>
    <el-form :model="form" ref="ruleForm">
      <div class="lookTitle">基本信息</div>
      <el-form-item
        label="所属分部"
        :rules="[{ required: true, message: '请选择分部', trigger: 'change' }]"
        prop="routeOrganId"
        :label-width="formLabelWidth"
      >
        <!--    -->
        <el-select
          v-model.trim="form.routeOrganId"
          :disabled="!isAdd"
          @change="changeOrgin"
          style="width: 100% !important"
        >
          <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
        label="所属学校"
        prop="schoolId"
        :label-width="formLabelWidth"
      >
        <!--    @change="checkSchool" -->
        <el-select
          v-model="form.schoolId"
          :disabled="!isAdd"
          style="width: 100% !important"
        >
          <el-option
            v-for="(item, index) in cooperationList"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 订单类型 -->
      <el-form-item
        label="订单类型"
        prop="insertOrderType"
        :label-width="formLabelWidth"
      >
        <el-radio-group v-model="insertOrderType" :disabled="!isAdd">
          <el-radio :label="1">个人订单</el-radio>
          <el-radio :label="2">学校订单</el-radio>
          <el-radio :label="3">其它订单</el-radio>
        </el-radio-group>
      </el-form-item>
          <el-form-item
            label="缴费单号"
            prop="calenderId"
            v-if="insertOrderType == 2 || insertOrderType == 3"
            :label-width="formLabelWidth"
             :rules="[{pattern:/^[0-9]*$/,message:'请输入正确的缴费单号',trigger: 'blur'}]"
          >
            <el-input
              v-model.trim="form.calenderId"
              :disabled="!isAdd"
              placeholder="请输入缴费单号"
            ></el-input>
          </el-form-item>
      <el-form-item
        label="学员编号"
        prop="userId"
        v-if="insertOrderType == 1 || insertOrderType == 3"
        :label-width="formLabelWidth"
      >
        <el-input
          v-model.trim="form.userId"
          :disabled="!isAdd"
          placeholder="请输入学员编号"
        ></el-input>
      </el-form-item>
      <div class="lookTitle">交易信息</div>
      <el-form-item
        label="交易流水号"
        :rules="[
          { required: true, message: '请输入流水号', trigger: 'change' },
        ]"
        prop="transNo"
        :label-width="formLabelWidth"
      >
        <el-input
          placeholder="请输入交易流水号"
          type="text"
          :disabled="!isAdd"
          v-model.trim="form.transNo"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="收款账户"
        prop="merNo"
        :rules="[
          { required: true, message: '请输入收款账户', trigger: 'change' },
        ]"
        :label-width="formLabelWidth"
      >
        <el-input
          placeholder="请输入收款账户"
          type="text"
          :disabled="!isAdd"
          v-model.trim="form.merNo"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="交易日期"
        :rules="[
          { required: true, message: '请选择交易日期', trigger: 'change' },
        ]"
        prop="payTime"
        :label-width="formLabelWidth"
      >
        <el-date-picker
          style="width: 100%"
          :disabled="!isAdd"
          v-model="form.payTime"
          type="datetime"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择交易日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="收入类型"
        :label-width="formLabelWidth"
        :rules="[
          { required: true, message: '请选收入类型', trigger: 'change' },
        ]"
        prop="applyType"
      >
        <el-select
          class="multiple"
          style="width: 100% !important"
          v-model.trim="form.applyType"
          filterable
          clearable
          :disabled="!isAdd"
          placeholder="请选择收入类型"
        >
          <el-option
            v-for="(item, index) in orderServerList"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="销售金额"
        prop="saleAmount"
        :rules="[
          { required: true, message: '请输入销售金额', trigger: 'change' },
        ]"
        v-if="form.applyType == 'SELL'"
        :label-width="formLabelWidth"
      >
        <el-input
          v-model="form.saleAmount"
          @mousewheel.native.prevent
          type="number"
          :disabled="!isAdd"
          placeholder="请输入销售金额"
        />
      </el-form-item>
      <el-form-item
        label="服务金额"
        v-if="form.applyType == 'SERVICE'"
        :rules="[
          { required: true, message: '请输入服务金额', trigger: 'change' },
        ]"
        prop="serviceAmount"
        :label-width="formLabelWidth"
      >
        <el-input
          type="number"
          @mousewheel.native.prevent
          :disabled="!isAdd"
          v-model="form.serviceAmount"
          placeholder="请输入收入金额"
        />
      </el-form-item>

      <div v-if="form.applyType == 'SELL'">
        <div v-for="(goodsList, index) in form.goodsList" :key="index">
          <el-form-item
            :label="'商品名称' + (index + 1)"
            :label-width="formLabelWidth"
            class="setWidth"
            :prop="'goodsList.' + index + '.id'"
            :rules="[
              { required: true, message: '请选择商品', trigger: 'change' },
            ]"
          >
            <el-select
              v-model.trim="goodsList.id"
              filterable
              :disabled="!isAdd"
              placeholder="请选择商品"
            >
              <el-option
                v-for="(item, index) in shopList"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            class="setWidth"
            style="margin-right: 10px"
            :prop="'goodsList.' + index + '.number'"
          >
            <!--  :rules="validAmount" <el-input-number style="width: 160px;" v-model="goodsList.number" placeholder="商品数量"></el-input-number> -->
            <el-input
              type="age"
              style="width: 160px"
              :disabled="!isAdd"
              clearable
              placeholder="请输入商品数量"
              @mousewheel.native.prevent
              v-model.number="goodsList.number"
            ></el-input>
          </el-form-item>
          <el-button
            icon="el-icon-minus"
            :disabled="!isAdd"
            v-if="form.goodsList.length > 1 && auditStatus == 'REJECT'"
            circle
            @click.prevent="removeGoodsList(goodsList)"
          ></el-button>
          <el-button
            icon="el-icon-plus"
            :disabled="!isAdd"
            v-if="auditStatus == 'REJECT'"
            @click.prevent="addGoodsList"
            circle
            style="margin-left: 5px"
          ></el-button>
        </div>
      </div>
      <div class="lookTitle">其它</div>
      <el-form-item
        label="提交备注"
        :label-width="formLabelWidth"
        :rules="[
          { required: true, message: '请输入提交备注', trigger: 'change' },
        ]"
      >
        <el-input
          placeholder="请输入备注"
          :disabled="!isAdd"
          v-model.trim="form.memo"
          type="textarea"
          :rows="3"
        ></el-input>
      </el-form-item>
      <!-- &&auditStatus != 'REJECT' -->
      <el-form-item
        label="审核备注"
        v-if="auditStatus != 'ING'"
        :label-width="formLabelWidth"
      >
        <el-input
          placeholder="请输入备注"
          :disabled="true"
          v-model.trim="form.auditComment"
          type="textarea"
          :rows="3"
        ></el-input>
      </el-form-item>
    </el-form>
    <div class="lookTitle" v-if="auditStatus == 'ING'" v-permission="'routeOrder/auditOutOrder'">审核意见</div>
    <el-form :model="submitForm" v-if="auditStatus == 'ING'" ref="submitForm" v-permission="'routeOrder/auditOutOrder'">
      <el-form-item
        prop="memo"
        :rules="[
          { required: true, message: '请输入审核意见', trigger: 'blur' },
        ]"
      >
        <el-input
          type="textarea"
          :rows="4"
          v-model="submitForm.memo"
        ></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {
  getRouteOrderInfo,
  auditOutOrder,
  updateRouteOrder,
} from "@/api/orderManager";
import { orderServerList } from "@/utils/searchArray";
import { getCooperation } from "@/api/buildTeam";
export default {
  props: ["orderId", "shopList", "isLook"],
  data() {
    return {
      formLabelWidth: "100px",
      form: {
        routeOrganId: null,
        transNo: null,
        type: "OTHER",
        merNo: null,
        actualAmount: null,
        memo: null,
        payTime: null,
        serviceAmount: null,
        goodsAmount: null,
        schoolId: null,
        goodsList: [
          {
            id: null,
            number: null,
          },
        ],
        applyType: null,
        userId: "",
        auditComment: "",
        calenderId:''
      },
      isAdd: !this.isLook,
      insertOrderType: 1, // 订单类型  1 个人订单 2 学校订单 2 其它订单
      cooperationList: [],
      submitForm: {
        memo: "",
      },
      auditStatus: "",
      orderServerList: orderServerList,
      clearSchool: false,
    };
  },
  mounted() {
    if (this.orderId) {
      getRouteOrderInfo({ id: this.orderId }).then((res) => {
        if (res.code == 200) {
          let orderInfo = res.data;
          this.form = {
            createTime: orderInfo.createTime,
            operator: orderInfo.operator,
            routeOrganId: orderInfo.routeOrganId,
            transNo: orderInfo.transNo,
            type: "OTHER",
            merNo: orderInfo.merNo,
            actualAmount: orderInfo.actualAmount,
            memo: orderInfo.memo,
            payTime: orderInfo.payTime,
            serviceAmount: orderInfo.serviceAmount,
            saleAmount: orderInfo.saleAmount,
            schoolId: orderInfo.schoolId,
            userId: orderInfo.userId ? orderInfo.userId : "",
            auditComment: orderInfo.auditComment,
            applyType: orderInfo.saleAmount ? "SELL" : "SERVICE",
            calenderId:orderInfo.calenderId?orderInfo.calenderId:''
          };
          this.auditStatus = orderInfo.auditStatus;
          this.$set(
            this.form,
            "goodsList",
            this.getShopList(orderInfo.goodsJson)
          );
          this.changeOrgin(orderInfo.routeOrganId);
          if(orderInfo.userId && !res.data.calenderId) {
            this.insertOrderType = 1
          } else if(res.data.calenderId && !orderInfo.userId) {
            this.insertOrderType = 2
          } else {
            this.insertOrderType = 3
          }
          this.clearSchool = true;
        }
      });
    }
    // 获取分部
     this.$store.dispatch("setBranchs");
  },
  methods: {
    changeOrgin(val) {
      if (val) {
        if (this.clearSchool) {
          this.$set(this.form, "schoolId", null);
        }
        getCooperation({ rows: 9999, organId: val }).then((res) => {
          if (res.code === 200) {
            this.cooperationList = res.data.rows;
          }
        });
      }
    },
    getShopList(str) {
      let arr = [];
      try {
        const obj = JSON.parse(str);

        // id: item.goodsId, number: item.num
        for (let i in obj) {
          arr.push({ id: parseInt(i), number: obj[i] });
        }
      } catch {}
      return arr.length > 0
        ? arr
        : [
            {
              id: null,
              number: null,
            },
          ];
    },
    auditOutOrder(status) {
      const that = this;
      this.$refs.submitForm.validate((res) => {
        if (res) {
          auditOutOrder({
            auditStatus: status,
            memo: this.submitForm.memo,
            studentPaymentRouteOrderId: this.orderId,
          }).then((res) => {
            if (res.code == 200) {
              this.$message.success("审核成功");
              that.$emit("getList");
              return;
            }
          });
        }
      });
    },
    removeGoodsList(item) {
      const index = this.form.goodsList.indexOf(item);
      if (index !== -1) {
        this.form.goodsList.splice(index, 1);
      }
    },
    addGoodsList() {
      this.form.goodsList.push({
        id: null,
        number: null,
      });
    },
    submitReaet() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let form = JSON.parse(JSON.stringify(this.form));
          if (!form.saleAmount && !form.serviceAmount) {
            this.$message.error("请输入销售收入或服务收入");
            return;
          }
          form.applyType == "SELL"
            ? (form.serviceAmount = 0)
            : (form.saleAmount = 0);
          if (!form.saleAmount) {
            form.goodsList = null;
          }
          let goodsJson = {};
          for (let i in form.goodsList) {
            goodsJson[form.goodsList[i]["id"]] = form.goodsList[i]["number"];
          }
          form.goodsJson =
            form.applyType == "SERVICE" ? null : JSON.stringify(goodsJson);
          form.id = this.orderId;
          form.auditStatus = "ING";
          if(this.insertOrderType == 1) {
            form.calenderId = null
          } else if(this.insertOrderType == 2) {
            form.userId = null
          }
          updateRouteOrder(form).then((res) => {
            if (res.code == 200) {
              this.$message.success("修改成功");
              this.$emit("getList");
              return;
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.lookTitle {
  height: 40px;
  line-height: 40px;
  font-weight: bold;
  background-color: rgb(237, 238, 240);
  padding: 0 20px;
  margin-bottom: 20px;
}
.setWidth {
  display: inline-block;
}
</style>
