<template>
  <view>
    <u-modal
      ref="uModal"
      :show="show"
      @confirm="confirm"
      :asyncClose="true"
      :showCancelButton="true"
      @cancel="onCancel"
      :confirmText="confirmText"
    >
      <view class="content">
        <!-- 整数类型 -->
        <block v-if="item.inputType == 'int'">
          <view class="title u-line-1">
            {{ item.funcname }}{{ item.params.unit || "" }}
          </view>
          <block v-if="item.inputType == 'int'">
            <u--input
              :focus="intFocus"
              v-model="value"
              :type="item.num_scale == 0 ? 'number' : 'digit'"
              :placeholder="item.showValue || item.params.lastvalue"
              border="surround"
            />
          </block>
          <view class="tips" v-if="item.paramValue">
            <u-icon name="info-circle-fill" color="#E2201A" />
            <text style="margin-left: 4px">
              有一条待更新记录，待更新值为：{{ item.paramValue
              }}{{ item.params.unit || "" }}
            </text>
          </view>
        </block>
        <!-- 布尔开关 -->
        <block v-else-if="item.inputType == 'switch'">
          <view class="title u-line-1">
            {{ item.funcname || "" }}{{ item.params.unit || "" }}
          </view>
          {{ switchTips }}
        </block>
        <!-- 步进器 -->
        <block v-else-if="item.inputType == 'step'">
          <view class="title u-line-1">
            {{ item.funcname }}{{ item.params.unit || "" }}
          </view>
          <!-- if 和 else 是因为有时候decimal-length设置为0不能点击加减 -->
          <u-number-box
            v-if="item.params.num_scale"
            :asyncChange="true"
            v-model="value"
            :min="item.params.num_minvalue || -2147483648"
            :max="item.params.num_maxvalue || 2147483647"
            :step="item.params.num_step"
            :decimal-length="item.params.num_scale"
            @change="stepChange"
            @focus="stepFocus"
            @blur="stepBlue"
            inputWidth="100"
          />
          <u-number-box
            v-else
            :asyncChange="true"
            v-model="value"
            :min="item.params.num_minvalue || -2147483648"
            :max="item.params.num_maxvalue || 2147483647"
            :step="item.params.num_step"
            @change="stepChange"
            @focus="stepFocus"
            @blur="stepBlue"
            inputWidth="100"
          />
          <view class="tips" v-if="item.paramValue">
            <u-icon name="info-circle-fill" color="#E2201A" />
            <text style="margin-left: 4px">
              有一条待更新记录，待更新值为：{{ item.paramValue
              }}{{ item.params.unit || "" }}
            </text>
          </view>
          <view class="tips">
            <u-icon name="info-circle-fill" color="#E2201A" />
            <text style="margin-left: 4px">
              受步长限制，手动输入会计算为最接近的合法值
            </text>
          </view>
        </block>
        <!-- 时段 -->
        <block v-else-if="item.inputType == 'dayParting'">
          <view class="title u-line-1">
            {{ item.funcname }}{{ item.params[item.key + "P"].unit || "" }}
          </view>
          <view class="day-parting">
            <picker
              mode="time"
              :value="item.params[item.key + 'T'].lastvalue"
              @change="changeT_T"
            >
              <view class="row">
                <view class="label"> 时间： </view>
                <view class="day-parting-row">
                  {{ item.params[item.key + "T"].lastvalue || "请选择时间" }}
                </view>
              </view>
            </picker>

            <view class="row" style="margin-top: 20px">
              <view class="label">压力：</view>
              <u--input
                :focus="dayPartingFocus"
                v-model="value"
                :type="
                  item.params[item.key + 'P'].num_scale == 0
                    ? 'number'
                    : 'digit'
                "
                :placeholder="item.params[item.key + 'P'].lastvalue || '请输入'"
                border="surround"
              />
            </view>
          </view>
        </block>
        <!-- 选择 -->
        <block v-else-if="item.inputType == 'radio'">
          <view class="title u-line-1">
            {{ item.funcname }}{{ item.params.unit || "" }}
          </view>
          <view class="select-box">
            <view
              class="item"
              @click="onSelected(op, item.inputType)"
              :class="op.value == item.params.lastvalue ? 'active' : ''"
              v-for="op in item.params.options"
              :key="op.value"
              hover-class="navigator-hover"
            >
              {{ op.label }}
            </view>
          </view>
        </block>
        <!-- 特殊选择 -->
        <block v-else-if="item.inputType == 'radioNum'">
          <view class="title u-line-1">
            {{ item.funcname }}{{ item.params.unit || "" }}
          </view>
          <view class="select-box">
            <view
              class="item"
              @click="onSelected(op, item.inputType)"
              :class="op.value == 1 ? 'active' : ''"
              v-for="op in item.params.options"
              :key="op.key"
              hover-class="navigator-hover"
            >
              {{ op.label }}
            </view>
          </view>
        </block>
        <!-- slot -->
        <block v-else-if="isSlot">
          <view class="title u-line-1">
            {{ item.funcname || "" }}
          </view>
          <slot />
        </block>
        <!-- 其他类型 -->
        <block v-else> 其他类型 </block>
        <view class="tips" v-if="toBeUpdated">
          <u-icon name="info-circle-fill" color="#E2201A" />
          <text style="margin-left: 4px">
            {{ toBeUpdated }}
          </text>
        </view>
        <view class="tips" v-if="tips">
          <u-icon name="info-circle-fill" color="#55AAFF" />
          <text style="margin-left: 4px">
            {{ tips }}
          </text>
        </view>
      </view>
    </u-modal>
  </view>
</template>
<script>
import currency from "../../utils/currency";
export default {
  name: "My_input",
  props: {
    customMethod: {
      type: Function,
    },
  },
  data() {
    return {
      show: false,
      item: {},
      tips: "",
      toBeUpdated: "",
      intFocus: false,
      dayPartingFocus: false,
      value: "",
      confirmText: "确定",
      loading: false,
      stepIsCalculate: false,
      stagingMethod: null,
      isSlot: false,
      switchTips: "",
      checkBeforeSending: null,
    };
  },
  methods: {
    /**
     * @param item.inputType int:数字 step:步进器 radio:单选 switch:开关 dayParting:分时段
     */
    openInput(item, isSlot = false, replenish = {}) {
      this.replenish = replenish;
      try {
        this.item = JSON.parse(JSON.stringify(item));
      } catch (error) {
        console.log("item JSON.parse 失败");
        this.item = item;
      }
      this.switchTips = "";
      this.show = true;
      let tips = "",
        toBeUpdated = "";
      this.confirmText = "确定";
      this.isSlot = isSlot;
      if (!isSlot) {
        let params = item.params;
        if (item.inputType == "int") {
          this.value = "";
          this.intFocus = false;
          if (params.num_minvalue || params.num_maxvalue)
            tips += `输入范围：${params.num_minvalue || 0} ~ ${
              params.num_maxvalue || "∞"
            }`;
          if (params.num_scale) tips += ` 保留${params.num_scale}位小数`;
          if (params.num_step) tips += ` 增量${params.num_step || 0}`;
          if (tips && params.unit) tips += ` 单位${params.unit}`;
          setTimeout(() => {
            this.intFocus = true;
          }, 300);
        } else if (item.inputType == "switch") {
          let paramValue = item.paramValue + "";
          if (paramValue.length && paramValue != item.params.lastvalue) {
            this.confirmText = "取消修改";
            this.switchTips = `查询到“${
              item.funcname
            }”有待更新记录，待更新值为“${
              params.options.find((v) => v.value == item.paramValue).label
            }”;您可通过“${this.confirmText}”按钮取消待更新请求`;
          } else {
            this.confirmText = "切换";
            console.log("paramValue", item.paramValue);
            this.switchTips = `是否将“${item.funcname}”${this.confirmText}为:“${
              params.options.find(
                (v) =>
                  v.value !=
                  (String(item.paramValue).length
                    ? item.paramValue
                    : item.params.lastvalue)
              ).label
            }”`;
          }
        } else if (item.inputType == "dayParting") {
          this.value = item.params[item.key + "p"] || "";
          this.dayPartingFocus = false;
          toBeUpdated =
            item.paramValue.time || item.paramValue.value
              ? `查询到一条待更新指令，更新内容为：时间${item.paramValue.time
                  .split("_")
                  .join(":")},压力${item.paramValue.value}MPA`
              : "";
          let p = item.params[item.key + "P"];
          if (p.num_minvalue || p.num_maxvalue)
            tips += `输入范围：${p.num_minvalue || 0} ~ ${
              p.num_maxvalue || "∞"
            }`;
          if (p.num_scale) tips += ` 保留${p.num_scale}位小数`;
          if (p.num_step) tips += ` 增量${p.num_step || 0}`;
          if (tips && p.unit) tips += ` 单位${p.unit}`;
          setTimeout(() => {
            this.dayPartingFocus = true;
          }, 300);
        } else if (item.inputType == "radio") {
          let paramValue = item.paramValue + "";
          if (paramValue.length && paramValue != item.params.lastvalue) {
            toBeUpdated = `查询到“${item.funcname}”有待更新记录，待更新值为“${
              params.options.find((v) => v.value == item.paramValue).label
            }”`;
          }
        }
        if (item.inputType == "radioNum") {
          if (item.paramValue)
            toBeUpdated = `查询到“${item.funcname}”有待更新记录，待更新值为“${item.paramValue}”`;
        } else if (item.inputType == "step") {
          this.value = params.lastvalue;
          /* if (this.value > params.num_maxvalue) this.value = params.num_maxvalue;
                    if (this.value < params.num_minvalue) this.value = params.num_minvalue; */
          if (params.num_minvalue || params.num_maxvalue)
            tips += `输入范围：${params.num_minvalue || 0} ~ ${
              params.num_maxvalue || "∞"
            }`;
          if (params.num_scale) tips += ` 保留${params.num_scale}位小数`;
          if (params.num_step) tips += ` 增量${params.num_step || 0}`;
          if (tips && params.unit) tips += ` 单位${params.unit}`;
          setTimeout(() => {
            this.intFocus = true;
          }, 300);
        } else if (item.inputType == "step") {
          this.isSlot = true;
        } else {
          console.log(item);
        }
      }
      this.tips = tips;
      this.toBeUpdated = toBeUpdated;
    },
    onSelected(option, mode) {
      if (mode == "radio") {
        this.item.params.lastvalue = option.value;
      } else if (mode == "radioNum") {
        this.item.params.options = this.item.params.options.map((v) => {
          v.value = v.key == option.key ? 1 : 0;
          return v;
        });
        this.$Http.changeOptions &&
          this.$Http.changeOptions(this.item.params.options);
      }
    },
    stepChange(e) {
      if (!this.stepIsCalculate) this.value = e.value;
    },
    stepFocus(e) {
      this.stepIsCalculate = true;
    },
    stepBlue(e) {
      const { num_step, num_scale, num_maxvalue, num_minvalue } =
        this.item.params;
      this.value = currency(
        currency(e.value, {
          increment: num_step,
          precision: num_scale,
        }).format()
      ).value;
      if (num_minvalue != "" && this.value < num_minvalue)
        this.value = num_minvalue - 0;
      if (num_maxvalue != "" && this.value > num_maxvalue)
        this.value = num_maxvalue - 0;
      this.stepIsCalculate = false;
      if (this.stagingMethod) this.confirm();
    },
    /* 时段修改 */
    changeT_T(e) {
      this.item.params[this.item.key + "T"].lastvalue = e.detail.value;
    },
    submitBreak(content) {
      uni.showToast({
        title: content + "",
        icon: "none",
      });
      this.$refs.uModal.loading = false;
    },
    confirm() {
      if (this.loading) return;
      if (this.isSlot) return this.$emit("customMethod", "confirm");
      let item = this.item,
        params = item.params,
        value = "";
      if (item.inputType == "int" || item.inputType == "step") {
        value = this.value - 0;
        // if (value == 0) return this.submitBreak("还未输入值");
        if (params.num_scale != 0) value = value.toFixed(params.num_scale);
        if (params.num_minvalue && value - 0 < params.num_minvalue - 0)
          return this.submitBreak("输入值小于最低范围");
        if (params.num_maxvalue && value - 0 > params.num_maxvalue - 0)
          return this.submitBreak("输入值大于最大范围");
      } else if (item.inputType == "switch") {
        let value = item.paramName;
        try {
          if (item.changeItem.length) {
          }
        } catch (error) {
          item.changeItem = [];
        }
        if (item.changeItem.length) {
          item.changeItem.forEach(
            (key) => (value[key] = value[key] == 1 ? 0 : 1)
          );
        } else {
          for (const key in value) {
            value[key] = value[key] == 1 ? 0 : 1;
          }
        }
        // value = params.options.find(v => v.value != (String(item.paramValue).length ? item.paramValue : item.params.lastvalue)).value
        return this.submit(item.w_functionid, value);
      } else if (item.inputType == "dayParting") {
        value = this.value - 0;
        // if (value == 0) return this.submitBreak("还未输入值");
        let p = item.params[item.key + "P"];
        if (p.num_scale != 0) value = value.toFixed(p.num_scale);
        if (p.num_minvalue && value - 0 > p.num_minvalue - 0)
          return this.submitBreak("输入值小于最低范围");
        if (p.num_maxvalue && value - 0 < p.num_maxvalue - 0)
          return this.submitBreak("输入值大于最大范围");
        return this.submit(item.w_functionid, {
          [item.key + "P"]: value,
          [item.key + "T"]: params[item.key + "T"].lastvalue
            .split(":")
            .join("_"),
        });
      } else if (item.inputType == "radio") {
        value = params.lastvalue;
      } else if (item.inputType == "radioNum") {
        value = { ...this.replenish };
        params.options.forEach((v) => (value[`${v.key}`] = v.value));
        return this.submit(item.w_functionid, value);
      }
      this.submit(item.w_functionid, {
        [item.paramName]: value,
      });
    },
    onCancel() {
      this.$refs.uModal.loading = false;
      this.show = false;
      this.checkBeforeSending = null;
    },
    async submit(w_functionid, params) {
      console.log("提交", w_functionid, params);
      if (this.checkBeforeSending) {
        this.$refs.uModal.loading = false;
        this.checkBeforeSending(w_functionid, params);
        return;
      }
      if (this.stepIsCalculate) {
        this.stagingMethod = true;
        return;
      } else {
        this.stagingMethod = false;
      }
      this.loading = true;
      let res = await this.$Http.setControlItem(w_functionid, params);
      this.loading = false;
      if (res) {
        this.show = false;
        this.stepIsCalculate = null;
        setTimeout(() => {
          // this.item = null;
        }, 200);
      } else {
        this.$refs.uModal.loading = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.content {
  width: 100%;

  /* 边框 */
  .day-parting-row {
    display: flex;
    align-items: center;
    flex: 1;
    width: 0;
    border: 1px solid #dadbde;
    border-radius: 4px;
    padding: 6px 9px;
    height: 35px;
    font-size: 14px;
    box-sizing: border-box;
  }

  .title {
    text-align: center;
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 20px;
  }

  .tips {
    display: flex;
    color: #666;
    font-size: 10px;
    margin-top: 6px;
    align-items: center;

    /deep/.u-icon {
      .u-icon__icon {
        font-size: 12px !important;
      }
    }
  }

  /* 分时控制 */
  .day-parting {
    .row {
      display: flex;
      align-items: center;

      .label {
        width: 50px;
      }
    }
  }

  /* 选择样式 */
  .select-box {
    display: flex;
    flex-wrap: wrap;

    .item {
      font-size: 12px;
      padding: 2px 6px;
      border-radius: 4px;
      border: 1px solid #333;
      margin-right: 5px;
      margin-bottom: 5px;
    }

    .active {
      // font-weight: bold;
      color: #fff;
      background: #052e5d;
    }
  }

  /deep/.u-input {
    .uni-input-input {
      font-size: 12px;
    }
  }

  /* 步进器样式 */
  /deep/ .u-number-box__minus,
  /deep/.u-number-box__plus {
    height: 30px !important;
    width: 40px !important;
  }

  /deep/ .u-number-box__input {
    height: 30px !important;
    width: 100px !important;
  }
}
</style>