<template>
  <div class="apply_container">
    <info-list :list_arr="module_arr">
      <apply-form
        :formInline="formInline"
        ref="apply_info"
        slot="apply_info"
      ></apply-form>
      <service-list
        ref="apply_service"
        slot="apply_service"
        :service_arr="service_arr"
      ></service-list>
    </info-list>

    <div class="footout">
      <span
        class="applybtn"
        @click="sub_service()"
      >提交申请</span>
      <div class="count_money">
        <!-- <p>
          费用总计:&nbsp;&nbsp;&nbsp; <span>{{ all_cost }}</span><span>金币</span>
        </p> -->
        <p>
          <span>共{{ service_arr.length }}项服务</span>
          <!-- <span>|&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;账户余额: {{ now_money }}金币</span> -->
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import infoList from "@/components/infoList";
import applyForm from "@/components/shop-car-apply/apply_form";
import serviceList from "@/components/shop-car-apply/service_list";
export default {
  props: {},
  components: {
    infoList,
    applyForm,
    serviceList
  },
  data() {
    return {
      formInline: {
        depart: "",
        preson: "",
        phone: "",
        date:[],
        sqly: '',
      },
      all_cost: 0,
      now_money: 0,
      module_arr: [
        {
          title: "服务申请",
          type: "solt",
          solt_name: "apply_info"
        },
        {
          title: "申请的服务",
          type: "solt",
          solt_name: "apply_service"
        }
      ],
      post_arr: [],
      service_arr: [
        // {
        //     img:'http://b-ssl.duitang.com/uploads/item/201705/09/20170509165713_NiHaG.jpeg',
        //     title:'水路货物周转量情况水路货物周转量情况',
        //     tips:[
        //         {
        //             tip:'Map Service',
        //             type:'nor'
        //         },
        //         {
        //             tip:'共享',
        //             type:'share'
        //         },
        //     ],
        //     type:'基础数据服务',
        //     auth:'贵州省交通运输厅',
        //     size:'规格：访问次数：20/日，访问量：100/日',
        //     applytype:'申请方式：按月',
        //     num:1,
        //     isMg:false,
        //     tableurl:'applydata',
        // },
        // {
        //     img:'http://b-ssl.duitang.com/uploads/item/201705/09/20170509165713_NiHaG.jpeg',
        //     title:'水路货物周转量情况水路货物周转量情况',
        //     tips:[
        //         {
        //             tip:'Map Service',
        //             type:'nor'
        //         },
        //         {
        //             tip:'敏感',
        //             type:'mg'
        //         },
        //     ],
        //     type:'基础数据服务',
        //     auth:'贵州省交通运输厅',
        //     size:'规格：访问次数：20/日，访问量：100/日',
        //     applytype:'申请方式：按月',
        //     num:1,
        //     isMg:true,
        //     tableurl:'applydata',
        // },
      ],
      share_arr: [
        "",
        {
          name: "共享",
          val: "share"
        },
        {
          name: "受限",
          val: "limit"
        },
        {
          name: "敏感",
          val: "mg"
        }
      ],
      temp_sub_arr: []
    };
  },
  watch: {},
  computed: {},
  created() {
    if (this.$route.query.service_id) {
      this.get_one_service(this.$route.query);
    } else if (this.$route.query.app_id) {
      this.get_one_app(this.$route.query);
    } else {
      // console.log(JSON.parse(window.sessionStorage.getItem("shoppingCart")));
      var temp_arr = [];
      JSON.parse(window.sessionStorage.getItem("shoppingCart")).forEach(e => {
        temp_arr.push(e.id);
      });
      this.get_car_list(temp_arr);
    }
    this.get_account_money();
  },
  mounted() {},
  methods: {
    get_account_money() {
      this.$http.get(`/apaas/backmgt/user/myAccount`).then(res => {
        if (res.data.success) {
          this.now_money = res.data.data.account_balance || 0;
        }
      });
    },
    get_one_app(app_data) {
      this.$http
        .get(`/apaas/serviceapp/v3/shopcart/appinfo?app_id=${app_data.app_id}`)
        .then(response => {
          console.log(response);
          let data = response.data.data;
          if (response.data.success && data) {
            //应用
            this.post_arr = [data];
            this.post_arr[0].app_id = parseInt(app_data.app_id);
            this.post_arr[0].spec_id = parseInt(app_data.spec_id);
            this.post_arr[0].duration_method = parseInt(app_data.duration_unit);
            this.post_arr[0].duration = parseInt(app_data.duration);
            this.post_arr[0].id = "";
            this.service_arr.push({});
            this.service_arr[0]["img"] = data.logo;
            this.service_arr[0]["title"] = data.app_name;
            this.service_arr[0]["type"] = data.type_name;
            this.service_arr[0]["auth"] = data.org_name;
            this.service_arr[0]["size"] =
              "应用镜像部署权限：" + data.price + "金币/月";
            this.service_arr[0]["applytype"] = "申请方式：" + "月";
            this.service_arr[0]["num"] = `${app_data.duration}个月`;
            this.service_arr[0]["count"] =
              app_data.duration * parseFloat(data.price) + "金币";
            this.service_arr[0]["isMg"] = false;
            this.service_arr[0]["isapp"] = true;
            console.log(data, this.service_arr);
            this.all_cost = app_data.duration * parseFloat(data.price);
            this.service_arr[0]["fbsj"] = data.create_date;
          }
        });
    },
    get_one_service(service_data) {
      this.$http
        .get(
          `/apaas/serviceapp/v3/shopcart/serviceinfo?service_id=${service_data.service_id}`
        )
        .then(response => {
          console.log(response);
          let data = response.data.data;
          if (response.data.success && data) {
            //服务
            this.post_arr = [data];
            this.post_arr[0].service_id = parseInt(service_data.service_id);
            this.post_arr[0].spec_id = parseInt(service_data.spec_id);
            this.post_arr[0].duration_method = parseInt(
              service_data.duration_unit
            );
            this.post_arr[0].duration = parseInt(service_data.duration);
            this.post_arr[0].id = "";
            let objs = {};
            objs.img = data.cover;
            objs.title = data.name;
            objs.type = data.data_service_type1_name;
            objs.fbsj = data.create_time;
            objs.tips = [
              {
                tip: this.share_arr[data.openness].name,
                type: this.share_arr[data.openness].val
              }
            ];
            objs.auth = data.organization_name;
            objs.size = "";
            objs.count = "";
            let request_spcs_info = data.request_spcs_info || [];
            request_spcs_info.forEach(el => {
              if (service_data.spec_id == el.id) {
                let size = "";
                let count = "";
                if (el.spcs_type == 1) {
                  size = `计次收费：${el.money}金币/${el.spcs_count}次`;
                  objs.num = "不限时长";
                  count = el.money;
                } else {
                  size = `${el.money}金币/月`;
                  objs.num = service_data.duration + "个月";
                  count = service_data.duration * el.money;
                }
                objs.size = size;
                objs.count = count + "金币";
                this.all_cost = count;
              }
            });
            objs.applytype = "申请方式：" + "月";
            objs.isMg = data.openness == 3;
            if (data.data_service_type1 != 36) {
              objs.data = JSON.parse(data.res_fields);
            }
            objs.isapp = false;
            this.service_arr = [objs];
            console.log(objs, this.service_arr);
          } else {
            this.$message.error(response.data.errMsg);
          }
        })
        .catch(() => {});
    },
    deal_data(data) {
      data.forEach(e => {
        if (e.selected) {
          e.selected = 1;
        } else {
          e.selected = 0;
        }
        if (e.children && e.children.length) {
          this.deal_data(e.children);
        }
      });
    },
    abc() {
      return new Promise((resolve, reject) => {
        this.$refs.apply_info.$refs.ruleForm.validate(valid => {
          console.log(valid);
          if (valid) {
            flag = true;
          } else {
            flag = false;
          }
        });
        console.log(res);
        if (res) {
          resolve(res);
        } else {
          reject(res);
        }
      });
    },
    sub_service() {
      // if (parseFloat(this.all_cost) > parseFloat(this.now_money)) {
      //   this.$message.error("余额不足，请进行充值");
      //   return;
      // }
      let formInline = this.$refs.apply_info.formInline;
      let flag = null;
      this.$refs.apply_info.$refs.ruleForm.validate(valid => {
        console.log(valid);
        if (valid) {
          var phone_ruler = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
          if (!phone_ruler.test(formInline.phone)) {
            this.$message.error("输入正确号码");
            return;
          }
          let request_start_time = formInline.date[0] || ''
          let request_end_time = formInline.date[1] || ''
          var temp = {
            apply_part: {
              o_name: formInline.preson,
              o_mobile: formInline.phone,
              request_start_time: request_start_time,
              request_end_time: request_end_time,
              reason_application: formInline.sqly
            },
            carts: []
          };
          var temp1 = this.$refs.apply_service.$refs.apply_service_state;
          this.post_arr.forEach((e, idx) => {
            if (e.service_id) {
              temp.carts.push({
                id: e.id,
                service_id: e.service_id,
                duration: e.duration,
                spec_id: e.spec_id,
                duration_method: e.duration_method,
                is_subscribe: e.is_subscribe,
                app_id: 0,
                scene: temp1[idx].sceneinput,
                apply_file: temp1[idx].fileList,
                apply_fields: []
              });
              // 判断表格ref是否存在
              this.temp_sub_arr = temp1[idx].$refs.apply_service_state_table
                ? temp1[idx].$refs.apply_service_state_table.metaData
                : [];
              this.deal_data(this.temp_sub_arr);
              temp.carts[temp.carts.length - 1][
                "apply_fields"
              ] = this.temp_sub_arr;
            } else {
              temp.carts.push({
                id: e.id,
                service_id: 0,
                duration: e.duration,
                spec_id: e.spec_id,
                duration_method: e.duration_method,
                is_subscribe: e.is_subscribe,
                app_id: e.app_id,
                scene: this.$refs.apply_service.$refs.apply_service_state[idx]
                  .sceneinput,
                apply_file: ""
              });
            }
          });
          for (let index = 0; index < temp.carts.length; index++) {
            const e = temp.carts[index];
            // 若表格数据长度不为0，执行以下
            if (e.service_id && e.apply_fields.length != 0) {
              if (e.apply_fields[0].selected == 0) {
                this.$message.error("请选择所需参数");
                return;
              }
            }
          }
          this.$http
            .post(`/apaas/serviceapp/v3/shopcart/apply`, temp)
            .then(response => {
              console.log(response);
              if (response.data.success) {
                this.$store.commit("setMenuCartState");
                this.$message.success("申请成功");
                this.$router.replace("/shop/service_application_successfully");
              } else {
                this.$message.error(response.data.errMsg);
              }
            })
            .catch(() => {
              this.$message.error("申请失败");
            });
        } else {
          this.$message.error("请完善服务申请");
          return;
        }
      });
    },
    get_car_list(car_arr) {
      this.service_arr = [];
      this.post_arr = [];
      var temp_cost = 0;
      this.$http
        .get(`/apaas/serviceapp/v3/shopcart/list`)
        .then(response => {
          console.log(response);
          let data = response.data.data.valid;
          data.forEach(e => {
            if (car_arr.indexOf(e.id) == -1) {
              return;
            }
            this.post_arr.push(e);
            this.service_arr.push({});
            let l = this.service_arr.length - 1;
            if (e.app_id) {
              //应用
              this.service_arr[l]["img"] = e.application.logo;
              this.service_arr[l]["title"] = e.application.app_name;
              this.service_arr[l]["type"] = e.application.type_name;
              this.service_arr[l]["auth"] = e.application.org_name;
              this.service_arr[l]["size"] =
                "应用镜像部署权限：" + e.application.price + "金币/月";
              this.service_arr[l]["applytype"] = "申请方式：月";
              this.service_arr[l]["num"] = `${e.duration}个月`;
              this.service_arr[l]["count"] =
                e.duration * parseFloat(e.application.price) + "金币";
              this.service_arr[l]["isMg"] = false;
              this.service_arr[l]["isapp"] = true;
              temp_cost = this.floatAdd(
                temp_cost,
                e.duration * parseFloat(e.application.price)
              );
            } else {
              //服务
              this.service_arr[l]["img"] = e.service.cover;
              this.service_arr[l]["title"] = e.service.name;
              this.service_arr[l]["type"] = e.service.data_service_type1_name;
              this.service_arr[l]["tips"] = [
                {
                  tip: this.share_arr[e.service.openness].name,
                  type: this.share_arr[e.service.openness].val
                }
              ];
              this.service_arr[l]["auth"] = e.service.organization_name;
              this.service_arr[l]["size"] = "";
              this.service_arr[l]["count"] = "";

              let spcs_type_1 = e.service.request_spcs_info.spcs_type_1 || [];
              let spcs_type_2 = e.service.request_spcs_info.spcs_type_2 || [];
              spcs_type_1.forEach((el, ind) => {
                if (e.spec_id == el.id) {
                  this.service_arr[l][
                    "size"
                  ] = `计次收费：${el.money}金币/${el.spcs_count}次`;
                  this.service_arr[l]["num"] = "不限时长";
                  this.service_arr[l]["count"] = e.duration * el.money + "金币";
                  temp_cost = this.floatAdd(temp_cost, e.duration * el.money);
                }
              });
              spcs_type_2.forEach((el, ind) => {
                if (e.spec_id == el.id) {
                  this.service_arr[l]["size"] = `时长收费：${el.money}金币/月`;
                  this.service_arr[l]["num"] = `${e.duration}个月`;
                  this.service_arr[l]["count"] = e.duration * el.money + "金币";
                  temp_cost = this.floatAdd(temp_cost, e.duration * el.money);
                }
              });

              this.service_arr[l]["applytype"] = "申请方式：月";
              this.service_arr[l]["isMg"] = e.service.openness == 3;
              this.service_arr[l]["data"] = e.service.res_fields
                ? JSON.parse(e.service.res_fields)
                : [];
              console.log(this.service_arr[l]["data"]);
              this.service_arr[l]["isapp"] = false;
            }
          });
          this.all_cost = temp_cost;
          // this.service_arr =
        })
        .catch(response => {});
    },
    floatAdd(arg1, arg2) {
      let r1, r2, m, c;

      try {
        r1 = arg1.toString().split(".")[1].length;
      } catch (e) {
        r1 = 0;
      }

      try {
        r2 = arg2.toString().split(".")[1].length;
      } catch (e) {
        r2 = 0;
      }

      c = Math.abs(r1 - r2);
      m = Math.pow(10, Math.max(r1, r2));
      if (c > 0) {
        let cm = Math.pow(10, c);
        if (r1 > r2) {
          arg1 = Number(arg1.toString().replace(".", ""));
          arg2 = Number(arg2.toString().replace(".", "")) * cm;
        } else {
          arg1 = Number(arg1.toString().replace(".", "")) * cm;
          arg2 = Number(arg2.toString().replace(".", ""));
        }
      } else {
        arg1 = Number(arg1.toString().replace(".", ""));
        arg2 = Number(arg2.toString().replace(".", ""));
      }
      return (arg1 + arg2) / m;
    }
  }
};
</script>

<style scoped>
.apply_container {
  width: 1200px;
  margin: 0 auto;
  overflow: hidden;
}
.footout {
  width: 100%;
  height: 84px;
  background-color: rgba(255, 255, 255, 1);
  box-shadow: 0px 3px 6px 0px rgba(244, 247, 252, 1);
  border-radius: 12px;
  padding: 20px;
  text-align: right;
  margin: 20px 0;
}
.applybtn {
  color: rgba(252, 239, 214, 1);
  width: 200px;
  height: 44px;
  line-height: 44px;
  text-align: center;
  float: right;
  background-color: rgba(229, 102, 0, 1);
  border-radius: 8px;
  margin-left: 20px;
  cursor: pointer;
}
.count_money {
  float: right;
  /* margin-top: -10px; */
  height: 44px;
  line-height: 44px;
}
.count_money p {
  font-size: 14px;
  color: #58617a;
}
</style>
