<template>
  <div v-if="hasAuth">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-card class="box-card">
        <div slot="header" class="header clearfix">
          <span>基本信息</span>
        </div>

        <el-form-item label="订单编号">
          <div class="order-number">
            <span>{{form.orderNo ? form.orderNo : '未生成'}}</span>
          </div>
        </el-form-item>

        <el-form-item label="订单用户" prop="uid">
          <el-input v-model="form.uid" placeholder="请输入用户uid"></el-input>
        </el-form-item>

        <el-form-item label="订单名称" prop="productTitle">
          <el-input v-model="form.productTitle" placeholder="请输入订单名称，尽量遵循命名规则"></el-input>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单类型" prop="productType">
              <el-select
                v-model="form.productTypeName"
                placeholder="请选择订单类型"
                @change="productTypeChange"
              >
                <el-option
                  v-for="item in productTypes"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交易类型" prop="orderType">
              <el-select
                v-model="form.orderTypeName"
                placeholder="请选择交易类型"
                @change="orderTypeChange"
              >
                <el-option
                  v-for="item in orderTypes"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单金额" prop="price">
              <el-input v-model="form.price" placeholder="请输入实际金额"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收支类型">
              <el-radio v-model="radio" label="1" disabled>收入</el-radio>
              <el-radio v-model="radio" label="2" disabled>支出</el-radio>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12" style="display: none;">
            <el-form-item label="交易方式" prop="channel">
              <el-select v-model="form.channelName" placeholder="请选择支付方式" @change="channelChange">
                <el-option
                  v-for="item in channels"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付编码">
              <el-input v-model="form.outOrderId" placeholder="请输入支付编号，选填"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="box-card">
        <div slot="header" class="header clearfix">
          <span>其他信息(选填)</span>
        </div>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目ID" prop="productId">
              <el-input v-model.number="form.productId" placeholder="请输入项目ID"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联订单" prop="originOrderNo">
              <el-input v-model="form.originOrderNo" placeholder="请输入平台订单编号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="外部备注" prop="publicComment">
          <el-input v-model="form.publicComment" placeholder="请输入用户可见的备注信息"></el-input>
        </el-form-item>

        <el-form-item label="内部备注" prop="privateComment">
          <quill-editor
            :options="editorOption"
            v-model="form.privateComment"
            ref="myQuillEditor"
            class="editer"
          ></quill-editor>
          <input type="file" hidden accept=".jpg, .png" ref="fileBtn" @change="handleChange" />
        </el-form-item>
      </el-card>

      <el-form-item>
        <el-button class="save-btn" type="primary" @click="saveSubmit()">保存</el-button>
        <el-button class="cancel-btn" @click="cancelSubmit()">取消</el-button>
      </el-form-item>

      <el-form-item>
        <el-button v-if="hasSave" class="comfirm-btn" type="primary" @click="confirmSubmit()">确认提交订单</el-button>
        <el-button v-else class="comfirm-btn" type="info">确认提交订单</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    let checkPrice = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入订单金额"));
      } else if (isNaN(value) || value > 100000) {
        return callback(new Error("请输入实际金额0-10万元"));
      } else {
        callback();
      }
    };
    let checkProductId = (rule, value, callback) => {
      if (isNaN(value)) {
        return callback(new Error("请输入数字"));
      } else {
        callback();
      }
    };
    let checkOriginOrderNo = (rule, value, callback) => {
      const reg = /^[0-9a-zA-Z]+$/;
      if (value && !reg.test(value)) {
        return callback(new Error("请输入数字和字母"));
      } else {
        callback();
      }
    };
    return {
      hasAuth:1,
      action: "",
      id: "",
      form: {
        uid: "",
        productTitle: "",
        productType: "",
        orderType: "",
        price: "",
        channel: "admin_confirm",
        outOrderId: "",
        productId: "",
        originOrderNo: "",
        publicComment: "",
        privateComment: "",
        orderNo: "",
        status: "",
        productTypeName: "",
        orderTypeName: "",
        channelName: "",

      },
      saveData: {},
      rules: {
        uid: [{ required: true, message: "请输入用户uid", trigger: "blur" }],
        productTitle: [
          { required: true, message: "请输入订单名称", trigger: "blur" },
          { max: 25, message: "订单名称最多输入25个字", trigger: "blur" }
        ],
        productType: [
          { required: true, message: "请选择订单类型", trigger: "change" }
        ],
        orderType: [
          { required: true, message: "请选择交易类型", trigger: "change" }
        ],
        price: [{ validator: checkPrice, trigger: "blur" }],
        channel: [
          { required: true, message: "请选择交易方式", trigger: "change" }
        ],
        originOrderNo: [{ validator: checkOriginOrderNo, trigger: "blur" }],
        productId: [{ validator: checkProductId, trigger: "blur" }],
        publicComment: [
          { max: 50, message: "外部备注最多输入50个字", trigger: "blur" }
        ],
        privateComment: [
          { required: true, message: "请输入内部备注", trigger: "blur" },
          {
            max: 10000,
            message: "内部备注最多输入10000个字符",
            trigger: "blur"
          }
        ]
      },
      orderTypes: [],
      productTypes: [],
      channels: [],
      orderState: [],
      hasSave: false,
      radio: "1",
      editorOption: {
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"], // toggled buttons
            ["blockquote", "code-block"],
            [{ header: 1 }, { header: 2 }], // custom button values
            [{ list: "ordered" }, { list: "bullet" }],
            [{ script: "sub" }, { script: "super" }], // superscript/subscript
            [{ indent: "-1" }, { indent: "+1" }], // outdent/indent
            [{ direction: "rtl" }], // text direction
            [{ size: ["small", false, "large", "huge"] }], // custom dropdown
            [{ header: [1, 2, 3, 4, 5, 6, false] }],
            [{ font: [] }],
            ["clean"], // remove formatting button
            ["link", "image"]
          ],
          imageResize: {}
        }
      }
    };
  },
  // computed: {
  //   radio() {
  //     if (this.form.orderType === 2 || this.form.orderType === 5 || this.form.orderType === 8) {
  //       this.radio = "1"
  //     } else if (this.form.orderType === 9) {
  //       this.radio = "2"
  //     } else {
  //       this.radio = "3"
  //     }
  //   }
  // },
  watch: {
    "form.orderType": {
      handler() {
        if (
          this.form.orderType === 2 ||
          this.form.orderType === 5 ||
          this.form.orderType === 8
        ) {
          this.radio = "1";
        } else if (this.form.orderType === 9) {
          this.radio = "2";
        } else {
          this.radio = "3";
        }
      }
    }
  },
  mounted() {
    this.$post("/api/admin/order/has_auth").then(res=>{
      //console.log(res);
      if (res.status===0){
        this.hasAuth = 0;
      }
    });
    if (this.$refs.myQuillEditor) {
      this.$refs.myQuillEditor.quill
        .getModule("toolbar")
        .addHandler("image", this.imgHandler);
    }
    const type = this.$route.query.type;
    if (type === "create") {
      this.action = "create";
      this.getAllChoice();
    } else if (type === "edit") {
      this.action = "create";
      this.id = this.$route.query.id;
      this.hasSave = true;
      this.getAllChoice();
      this.getOrder();
    }
  },
  methods: {
    async getAllChoice() {
      let res = await this.$post("/api/admin/order/get_all_choice", {
        action: this.action
      });
      if (res) {
        console.log(res);
        const allChoice = res.data;
        this.orderTypes = allChoice.order_types;
        this.productTypes = allChoice.product_types;
        this.channels = allChoice.channels;
        this.orderState = allChoice.order_state;
      }
    },
    async getOrder() {
      let res = await this.$post("/api/admin/order/get", {
        order_no: this.id
      });
      if (res) {
        if (res.status === 1 && res.data) {
          const data = res.data;
          this.id=data.id;
          this.form.uid = data.uid || "";
          this.form.productTitle = data.product_title || "";
          this.form.productType = data.product_type || "";
          this.form.orderType = data.order_type || "";
          this.form.price = data.price.replace("-", "") || "";
          this.form.channel = data.channel || "admin_confirm";
          this.form.outOrderId = data.out_order_id || "";
          this.form.productId = data.product_id || "";
          this.form.originOrderNo = data.origin_order_no || "";
          this.form.publicComment = data.public_comment || "";
          this.form.privateComment = data.private_comment || "";
          this.form.orderNo = data.order_no || "";
          this.form.status = data.status || "";
          this.form.productTypeName = data.product_type_name || "";
          this.form.orderTypeName = data.order_type_name || "";
          this.form.channelName = data.channel_name || "";
          console.log(this.form);
        }
      }
    },
    async saveOrder() {
      const data = {
        id: this.id,
        uid: this.form.uid,
        product_title: this.form.productTitle,
        product_type: this.form.productType,
        product_id:this.form.productId,
        order_type: this.form.orderType,
        price: this.form.price,
        channel: this.form.channel,
        out_order_id: this.form.outOrderId,
        origin_order_no: this.form.originOrderNo,
        public_comment: this.form.publicComment,
        private_comment: this.form.privateComment
      };
      this.saveData = data;
      let res = await this.$post("/api/admin/order/create", data);
      if (res) {
        if (res.status === 1) {
          this.id = res.data.id;
          this.saveData.id = res.data.id;
          this.form.orderNo = res.data.order_no;
          this.hasSave = true;
          this.$message({
            message: "保存成功",
            type: "success"
          });
        } else if (res.status === -2) {
          this.$message({
            message: `当前订单用户的账户余额不足(可用余额${res.data.can_use}元)，操作失败!`,
            type: "error"
          });
        } else if (res.info) {
          console.log(res.info);
        }
      }
    },
    async confirmOrder() {
      const data = {
        id: this.id,
        uid: this.form.uid,
        product_title: this.form.productTitle,
        product_type: this.form.productType,
        product_id:this.form.productId,
        order_type: this.form.orderType,
        price: this.form.price,
        channel: this.form.channel,
        out_order_id: this.form.outOrderId,
        origin_order_no: this.form.originOrderNo,
        public_comment: this.form.publicComment,
        private_comment: this.form.privateComment
      };
      const confirmData = data;
      const saveData = this.saveData;
      const isConfirm = true;
      for (const key in confirmData) {
        if (confirmData[key] !== saveData[key]) {
          console.log(confirmData[key], saveData[key]);
          this.$message({
            message: "与保存订单不一致，请先保存订单！",
            type: "warning"
          });
          return;
        }
      }
      let res = await this.$post("/api/admin/order/confirm_order", data);
      if (res) {
        if (res.status === 1) {
          this.$message({
            message: "提交成功",
            type: "success"
          });
          setTimeout(() => {
            this.$router.push("/main/artificial_orders");
          }, 1000);
        } else if (res.info) {
          console.log(res.info);
        }
      }
    },
    saveSubmit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.saveOrder();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    confirmSubmit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$confirm(
            `确认提价订单后，${this.form.uid}的账户将${this.form.orderTypeName}${this.form.price}元 ，交易方式为${this.form.channelName}，请您再次确认操作！`,
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }
          )
            .then(() => {
              this.confirmOrder();
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消提交"
              });
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    cancelSubmit() {
      this.$router.push("/main/artificial_orders");
    },
    productTypeChange() {
      const productTypeObject = this.productTypes.find(element => {
        return element.name === this.form.productTypeName;
      });
      this.form.productType = productTypeObject.id;
    },
    orderTypeChange() {
      const orderTypeObject = this.orderTypes.find(element => {
        return element.name === this.form.orderTypeName;
      });
      this.form.orderType = orderTypeObject.id;
    },
    channelChange() {
      const channelObject = this.channels.find(element => {
        return element.name === this.form.channelName;
      });
      this.form.channel = channelObject.id;
    },

    imgHandler(state) {
      if (state) {
        //触发input的单击 ，fileBtn换成自己的
        this.$refs.fileBtn.click();
      }
    },
    handleChange(e) {
      const files = e.target.files;
      if (!files) {
        return;
      }
      const file = files[0];
      // if (file.size / 1024 > 500) {
      //   this.$message.error("图片大小不得超过500k，请重新选择");
      //   return false;
      // }
      console.log(file);
      const formData = new FormData();
      formData.append("file", file);
      formData.append("original_filename", file.name);
      console.log(formData);
      this.$axios
        .$post("/upload_image", formData, {
          headers: { "Content-Type": "multipart/form-data" }
        })
        .then(res => {
          console.log(res);
          const index = this.myQuillEditor.selection.savedRange.index;
          this.myQuillEditor.insertEmbed(index, "image", res.filename);
          // this.$emit(
          //   "change",
          //   this.content + `<img src="${res.filename}" alt="${file.name}"/>`
          // );
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.box-card {
  margin-bottom: 10px;
  width: 100%;
}

.header {
  font-size: 24px;
  color: #222222;
  font-weight: 600;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.order-number {
  display: flex;
  align-items: center;
}

.order-number span:first-child {
  flex: 1;
  font-size: 14px;
  color: #999999;
}

.order-number span:nth-child(2) {
  font-size: 14px;
  color: #999999;
}

.order-status {
  display: block;
  margin-left: 7px;
  padding: 0 2px;
  height: 22px;
  line-height: 22px;
  border: 1px solid #3c95ff;
  font-size: 12px;
  color: #308eff;
}

.el-select {
  width: 100%;
}

.editer {
  width: 100%;
  height: 600px;
  padding: 0 0 50px;
}

.save-btn {
  width: 100px;
  height: 40px;
}

.cancel-btn {
  margin-left: 10px;
  width: 100px;
  height: 40px;
}

.comfirm-btn {
  width: 210px;
  height: 40px;
}
</style>
