<template>
  <view class="automation">
    <custom-card>
      <block slot="backText">自动控制</block>
    </custom-card>
    <view
      class="automation-content"
      :class="{ 'automation-content-rever': activeIndex === 1 }"
    >
      <view class="automation-header">
        <view
          class="automation-header-item"
          :class="{ 'automation-header-item-active': activeIndex === 0 }"
          @click="clickHeaderItem(0)"
          >灌溉
          <view
            :class="
              activeIndex == '0'
                ? 'automation-header-item-icon'
                : 'automation-header-item-icon-bottom'
            "
          ></view>
        </view>
        <view
          class="automation-header-item"
          @click="clickHeaderItem(1)"
          :class="{ 'automation-header-item-active': activeIndex === 1 }"
          >水肥
          <view
            :class="
              activeIndex == '1'
                ? 'automation-header-item-icon'
                : 'automation-header-item-icon-bottom'
            "
          ></view>
        </view>
      </view>
      <view class="automation-body">
        <rotation-items
          :formData="formData"
          :tktype="tktype"
          @formDataHandler="updateFormData"
        />
        <view class="automation-body-title">灌区选择</view>
        <rotation-bottom
          :activeIndex="activeIndex"
          :irrigatedAreaList="irrigatedAreaList"
          :alreadyList="alreadyList"
          @updateList="updateListHandler"
          :tktype="tktype"
        />
      </view>
    </view>
    <view class="automation-footer">
      <view class="automation-footer-left">
        已选<text class="automation-footer-left-num">{{ selectNum }}</text
        >个灌区
      </view>
      <view class="automation-footer-right" @click="immediateExecution"
        >立即执行</view
      >
    </view>
  </view>
</template>
<script>
import rotationItems from './components/rotationItems.vue';
import rotationBottom from './components/rotationBottom.vue';
export default {
  name: 'automation',
  data() {
    return {
      activeIndex: 0,
      devBid: '',
      devName: '',
      devStatus: '',
      irrigatedAreaList: [],
      alreadyList: [],
      formData: {
        lgjg: '',
        fqcx: '',
        fhcx: '',
        lgcs: 1,
      },
      tktype: 1,
      selectNum: 0,
    };
  },
  components: {
    rotationBottom,
    rotationItems,
  },
  watch: {
    alreadyList: {
      handler(val) {
        this.selectNum = 0;
        val.forEach((item) => {
          if (item.isChecked) {
            this.selectNum++;
          }
        });
      },
      deep: true,
      immediate: true,
    },
  },
  onLoad(options) {
    this.devBid = options.devBid;
    this.devName = options.devName;
    this.devStatus = options.devStatus;

    // 检测是否有运行中的任务
    this.getRunStatus().then((hasRunningTask) => {
      if (hasRunningTask) {
        setTimeout(() => {
          uni.redirectTo({
            url: `/pages/cb/shuifeizs/rotationflow?devBid=${this.devBid}&devName=${this.devName}&devStatus=${this.devStatus}`,
          });
        }, 1000);
      } else {
        this.getdeviceSfStatus();
        this.getAlreadyList();
      }
    });
  },
  methods: {
    updateListHandler(list) {
      this.alreadyList = list;
    },
    updateFormData(options) {
      this.formData[options.key] = options.value;
    },
    async getAlreadyList() {
      const res = await this.$myRequest({
        url: '/api/v2/iot/mobile/device/sf/group/already/list/',
        method: 'post',
        data: {
          devBid: this.devBid,
        },
      });

      console.log(res, '-------------------- get already list');
      res?.forEach((item) => {
        item.isChecked = false;
      });
      this.alreadyList = res;
    },
    async getdeviceSfStatus() {
      const res = await this.$myRequest({
        url: '/api/v2/iot/mobile/device/sf/status/',
        method: 'post',
        data: {
          devBid: this.devBid,
        },
      });
      this.dataList = [];
      this.irrigatedAreaList = [];
      this.alreadyfertilizerBucketList = [];

      console.log('get device sf status', res);
      res.forEach((item) => {
        if (item.sfType === '7') {
          this.irrigatedAreaList.push(item);
        }
      });
    },
    clickHeaderItem(index) {
      this.activeIndex = index;
      this.tktype = index == 0 ? 1 : 2;
    },
    // 获取运行状态
    async getRunStatus() {
      try {
        const res = await this.$myRequest({
          url: '/api/v2/iot/mobile/device/sf/zsrf/task/run/status/',
          method: 'post',
          data: {
            devBid: this.devBid,
          },
        });
        console.log(res, 'resresresres');

        return Promise.resolve(res.status && res.status / 1 === 1);
      } catch (error) {
        return Promise.resolve(false);
      }
    },
    // iot/mobile/device/sf/zsrf/task/ctl/
    async postTaskCtl(payload) {
      // loading
      uni.showLoading({
        title: '正在执行',
      });
      console.log(payload, 'payloadpayload');
      const res = await this.$myRequest({
        url: '/api/v2/iot/mobile/device/sf/zsrf/task/ctl/',
        method: 'post',
        data: payload,
        header: {
          'Content-Type': 'application/json',
        },
      });
      uni.hideLoading();
      console.log(res, 'resresres');
      if (res?.code === '000000') {
        uni.showToast({
          title: '操作成功',
        });
        setTimeout(() => {
          uni.redirectTo({
            url: `/pages/cb/shuifeizs/rotationflow?devBid=${this.devBid}&devName=${this.devName}&devStatus=${this.devStatus}`,
          });
        }, 1000);
      } else {
        uni.showToast({
          icon: 'none',
          title: res.msg,
        });
      }
    },
    immediateExecution() {
      console.log(this.formData, 'formDataformDataformData');
      if (!this.formData['lgjg']) {
        uni.showToast({
          title: '请输入轮灌间隔时间',
          icon: 'none',
        });
        return;
      }
      if (this.tktype == 2 && !this.formData['fqcx']) {
        uni.showToast({
          title: '请输入肥前水时间',
          icon: 'none',
        });
        return;
      }
      if (this.tktype == 2 && !this.formData['fhcx']) {
        uni.showToast({
          title: '请输入肥后水时间',
          icon: 'none',
        });
        return;
      }
      if (this.tktype == 2 && !this.formData['sfmode']) {
        uni.showToast({
          title: '请选择模式',
          icon: 'none',
        });
        return;
      }
      if (this.selectNum === 0) {
        uni.showToast({
          title: '请选择灌区',
          icon: 'none',
        });
        return;
      }
      const fqList = [];
      for (let i = 0; i < this.alreadyList.length; i++) {
        const item = this.alreadyList[i];
        if (item.isChecked && !item.ti) {
          uni.showToast({
            title: `请输入${item.sfDisplayname || item.sfName}的时长`,
            icon: 'none',
          });
          return;
        } else if (item.isChecked && this.tktype == 2 && !item.pfCode) {
          uni.showToast({
            title: `请输入${item.sfDisplayname || item.sfName}的配方`,
            icon: 'none',
          });
          return;
        }
        if (item.isChecked) {
          fqList.push({
            fqCode: item.sfCode,
            ti: item.ti || '',
            pfCode: item.pfCode || '',
          });
        }
      }
      const payload = {
        devBid: this.devBid,
        tktype: this.tktype,
        tkid: 0,
        status: 1,
        ...this.formData,
        fqList,
        sfmode: this.tktype !== 1 ? this.formData.sfmode || 1 : '',
      };
      this.postTaskCtl(payload);
    },
  },
};
</script>
<style scoped lang="scss">
uni-page-body,
uni-page-wrapper {
  position: relative;
  height: 100%;
}
.automation {
  background: linear-gradient(180deg, #ffffff00 0%, #fff 23.64%, #fff 100%),
    linear-gradient(102deg, #bfeadd 6.77%, #b8f1e7 40.15%, #b9eef5 84.02%);
  width: 100%;
  height: calc(100% - 100rpx);
  overflow: hidden;
  .automation-content {
    border-bottom: none;
    border-radius: 16rpx 16rpx 0 0;
    position: relative;
    overflow: hidden;
    &::before {
      position: absolute;
      content: '';
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: url('https://webstaticimg.oss-cn-hangzhou.aliyuncs.com/bigdata_app/newindex/controlbg.png')
        no-repeat;
      background-size: cover;
    }
  }
  .automation-content-rever {
    border-bottom: none;
    border-radius: 16rpx 16rpx 0 0;
    position: relative;
    &::before {
      position: absolute;
      content: '';
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: url('https://webstaticimg.oss-cn-hangzhou.aliyuncs.com/bigdata_app/newindex/controlbg.png')
        no-repeat;
      background-size: cover;
      transform: rotateY(180deg);
      transform-origin: center center;
    }
  }
  .automation-header {
    width: 100%;
    display: flex;
    .automation-header-item {
      width: 50%;
      height: 80rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 36rpx;
      color: #687a74;
      text-align: center;
      font-family: 'Source Han Sans CN VF';
      font-size: 32rpx;
      font-weight: 400;
      position: relative;
    }
    .automation-header-item-active {
      color: #042118;
      text-align: center;
      font-family: 'Source Han Sans CN VF';
      font-size: 32rpx;
      font-weight: 500;
      position: relative;
    }
    .automation-header-item-icon {
      width: 28rpx;
      height: 4rpx;
      border-radius: 4rpx;
      background-color: #14a478;
      position: absolute;
      bottom: 0;
    }
    .automation-header-item-icon-bottom {
      background-color: transparent;
    }
  }
  .automation-body {
    height: calc(100vh - 250rpx);
    overflow: hidden;
    .automation-body-title {
      position: relative;
      color: #042118;
      font-family: 'Source Han Sans CN VF';
      font-size: 28rpx;
      font-weight: 500;
      margin: 48rpx 32rpx 16rpx 32rpx;
    }
  }
  .automation-footer {
    position: fixed;
    width: 100%;
    padding: 16rpx 0;
    background: #fff;
    box-shadow: 0 -4rpx 8rpx 0 #0000001a;
    bottom: 0;
    height: 80rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .automation-footer-left {
      width: 50%;
      margin-left: 32rpx;
      color: #9ba6a3;
      font-family: 'Source Han Sans CN VF';
      font-size: 28rpx;
      font-weight: 400;
      .automation-footer-left-num {
        color: #14a478;
        text-align: center;
        font-family: 'Source Han Sans CN VF';
        font-size: 28rpx;
        font-style: normal;
        font-weight: 700;
        margin: 0 8rpx;
      }
    }
    .automation-footer-right {
      width: 224rpx;
      border-radius: 16rpx;
      background-color: #14a478;
      color: #ffffff;
      text-align: center;
      font-family: 'Source Han Sans CN VF';
      font-size: 32rpx;
      font-weight: 400;
      padding: 16rpx 0;
      margin-right: 32rpx;
    }
  }
}
</style>
