<template>
  <view>
    <view class="custom-pop-head">
      <view class="left" @click="$emit('show', false)">取消</view>
      <view class="title">{{ investigationDetailTitle }}</view>
      <view class="right" @click="investigationDetailHandle">确认</view>
    </view>
    <view class="box" style="max-height: 800rpx; overflow-y: auto">
      <view
        class="investigation-item"
        v-for="(item, index) in investigationDetailList"
        :key="index"
        style="width: 96%; padding: 0"
      >
        <view
          class="detail-item"
          v-if="item.type === 'number' || item.type === '1'"
        >
          <uni-forms-item
            :label="item.name"
            label-width="450rpx"
            style="display: flex; align-items: center"
          >
            <u-input
              placeholder="请输入"
              border="none"
              v-model="item.standar"
              inputAlign="right"
              type="number"
            >
              <u-text
                :text="item.unit"
                slot="suffix"
                margin="0 3px 0 0"
                type="tips"
              ></u-text>
            </u-input>
          </uni-forms-item>
        </view>
        <view
          class="detail-item"
          v-else-if="item.type === 'text' || item.type === '2'"
        >
          <uni-forms-item
            :label="item.name"
            label-width="450rpx"
            style="display: flex; align-items: center"
          >
            <u-input
              placeholder="请输入"
              border="none"
              v-model="item.standar"
              inputAlign="right"
            />
          </uni-forms-item>
        </view>
        <view
          class="detail-item"
          v-else-if="item.type === 'check' || item.type === '3'"
        >
          <uni-forms-item
            :label="item.name"
            label-width="450rpx"
            style="display: flex; align-items: center"
          >
            <u-checkbox
              v-model="item.standar"
              :customStyle="{ justifyContent: 'space-between' }"
              :name="'sdfs'"
            />
          </uni-forms-item>
        </view>
        <view
          class="detail-item"
          v-else-if="item.type === 'upload' || item.type === '4'"
        >
          <uni-forms-item
            :label="item.name"
            label-position="top"
            label-width="450rpx"
            style="display: flex; align-items: center"
          />
          <u-upload
            :fileList="item.fileList"
            @afterRead="(e) => afterRead(e, item)"
            @delete="(e) => deletePic(e, item)"
            name="1"
            :maxCount="1"
          ></u-upload>
        </view>
      </view>
      <view class="investigation-item" style="width: 96%; padding: 0">
        <view class="detail-item">
          <uni-forms-item
            label="隐患描述"
            label-position="top"
            label-width="200px"
          />
          <u-textarea
            placeholder="请输入"
            border="none"
            v-model="formData.hdDesc"
          />
        </view>
      </view>
      <view class="investigation-item" style="width: 96%; padding: 0">
        <view class="detail-item">
          <uni-forms-item
            label="隐患图片"
            label-position="top"
            label-width="200px"
          />
          <u-upload
            :fileList="fileList"
            @afterRead="(e) => afterRead2(e, 'fileList')"
            @delete="(e) => deletePic2(e, 'fileList')"
            name="1"
            :maxCount="1"
          ></u-upload>
        </view>
      </view>
      <view class="investigation-item" style="width: 96%; padding: 0">
        <view class="detail-item">
          <uni-forms-item
            label="补充信息"
            label-position="top"
            label-width="200px"
          />
          <u-textarea
            placeholder="请输入"
            border="none"
            v-model="formData.hdInfo"
          />
        </view>
      </view>
    </view>
    <view class="blank" />
  </view>
</template>

<script>
export default {
  // 组件
  components: {},
  props: {
    sid: {
      type: String,
      default: "01",
    },
    json: {
      type: Object,
      default: {},
    },
    businessId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      // 公用的js
      $: this.$,
      investigationSelect: null,
      investigationList: [],
      showInvestigationDetail: false,
      investigationDetailTitle: "",
      investigationDetailList: [],
      formData: {
        // bigCategory: '',
        // smallCategory: '',
        // hdTerm: '',
        hdPic: "",
        hdDesc: "",
        hdInfo: "",
      },
      fileList: [],
    };
  },
  // 页面加载
  onLoad(e) {
    // this.getData()
  },
  mounted() {
    console.log(this.json);
    if (this.json.extraConfigs) {
      this.investigationDetailList = this.json.extraConfigs.map((item) => {
        if (!item.fileList) {
          item.fileList = [];
        }
        switch (
          item.type
          // case "1":
          //   item.standar = 0
          //   break;
          // case "2":
          //   item.standar = ''
          //   break;
          // case "3":
          //   item.standar = false
          //   break;
          // case "4":
          //   item.fileList = [
          //         // {
          //         //     "id": "20229a8c-db46-4447-be3e-6731665f7bd0",
          //         //     "type": "image",
          //         //     "url": "https://img-blog.csdnimg.cn/20210823085628540.jpeg",
          //         //     "thumb": "blob:http://localhost:8080/4343e24a-edc5-4693-8fbd-f99647ea3bd5",
          //         //     "size": 11600,
          //         //     "name": "静态人流量统计.png",
          //         //     "status": "success",
          //         //     "message": "",
          //         //     "result": {
          //         //         "code": 200,
          //         //         "message": "操作成功",
          //         //         "result": "https://img-blog.csdnimg.cn/20210823085628540.jpeg"
          //         //     }
          //         // }
          //     ]
          //   break;
        ) {
        }
        return item;
      });
    } else {
      this.getData();
    }
    if (this.json.checkedSelect) {
      this.formData = {
        hdPic: this.json.checkedSelect.hdPic || "",
        hdDesc: this.json.checkedSelect.hdDesc || "",
        hdInfo: this.json.checkedSelect.hdInfo || "",
      };
    }
  },
  // 页面显示
  onShow() {},
  // 计算属性
  computed: {},
  // 方法
  methods: {
    // 删除图片
    deletePic(event, item) {
      item.fileList.splice(event.index, 1);
    },
    //获取随机id
    uuid(len, binary) {
      len = !len ? 36 : len;
      binary = !binary ? 16 : binary;
      return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"
        .replace(/[xy]/g, function (c) {
          var r = (Math.random() * binary) | 0,
            v = c == "x" ? r : (r & 0x3) | 0x8;
          return v.toString(binary);
        })
        .substring(0, len);
    },
    // 新增图片
    async afterRead(event, item) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      const id = this.uuid();
      item.fileList.push({
        id,
        ...event.file,
        status: "uploading",
        message: "上传中",
      });
      const result = await this.uploadFilePromise(item.fileList[0].url);
      const resultInfo = JSON.parse(result);
      const index = item.fileList.findIndex((v) => v.id === id);
      if (resultInfo.code == 200) {
        item.fileList.splice(
          index,
          1,
          Object.assign(item.fileList[index], {
            status: "success",
            message: "",
            result: resultInfo,
            url: resultInfo.result,
          })
        );
      } else {
        this.$.toast("上传失败");
        item.fileList.splice(
          index,
          1,
          Object.assign(item.fileList[index], {
            status: "error",
            message: "失败",
          })
        );
      }
    },
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: this.$.baseUrl + "/hiddenDanger/ftp/uploadFileToFtp", // 仅为示例，非真实的接口地址
          filePath: url,
          name: "file",
          success: (res) => {
            resolve(res.data);
          },
        });
      });
    },
    // 删除图片
    deletePic2(event, key) {
      this[key].splice(event.index, 1);
      this.formData.hdPic = this[key]
        .filter((item) => item.status === "success")
        .map((item) => item.url)
        .toString();
      this.changeEmit();
    },
    // 新增图片
    async afterRead2(event, key) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      const id = this.uuid();
      this[key].push({
        id,
        ...event.file,
        status: "uploading",
        message: "上传中",
      });
      const result = await this.uploadFilePromise(this[key][0].url);
      const resultInfo = JSON.parse(result);
      const index = this[key].findIndex((v) => v.id === id);
      if (resultInfo.code == 200) {
        this[key].splice(
          index,
          1,
          Object.assign(this[key][index], {
            status: "success",
            message: "",
            result: resultInfo,
            url: resultInfo.result,
          })
        );
      } else {
        this.$.toast("上传失败");
        this[key].splice(
          index,
          1,
          Object.assign(this[key][index], {
            status: "error",
            message: "失败",
          })
        );
      }
      this.formData.hdPic = this[key]
        .filter((item) => item.status === "success")
        .map((item) => item.url)
        .toString();
      this.changeEmit();
    },
    changeEmit() {
      this.$emit("change", this.formData);
    },
    getData2() {
      this.$request
        .globalRequest(
          "/hiddenDanger/highDanger/getImportDangerInfo",
          {
            sid: this.$props.json.nid,
          },
          "GET"
        )
        .then((res) => {
          if (res.code == 200) {
            this.investigationDetailList = res.result.map((item) => {
              switch (item.type) {
                case "1":
                  item.standar = 0;
                  break;
                case "2":
                  item.standar = "";
                  break;
                case "3":
                  item.standar = false;
                  break;
                case "4":
                  item.fileList = [];
                  break;
              }
              return item;
            });
          }
        });
      // this.$request.globalRequest('/hiddenDanger/highDanger/getImportDangers', {}, 'GET').then(res => {
      // 	if (res.code == 200) {
      // 		this.investigationList = res.result
      // 	}
      // })
    },
    getData() {
      this.$request
        .globalRequest(
          "/hiddenDanger/highDanger/getImportDangerDisplayDetail",
          {
            dangerId: this.$props.json.id,
            businessId: this.$props.businessId,
          },
          "GET"
        )
        .then((res) => {
          if (res.code == 200) {
            if (res.result.length > 0) {
              this.investigationDetailList = res.result.map((item) => {
                switch (item.type) {
                  case "1":
                    item.standar = 0;
                    break;
                  case "2":
                    item.standar = "";
                    break;
                  case "3":
                    item.standar = false;
                    break;
                  case "4":
                    item.fileList = [];
                    break;
                }
                return item;
              });
            } else {
              this.getData2();
            }
          }
        });
    },
    // 跳转页面
    skipPage(even) {
      this.$.open(even);
    },
    handleSelect(item, index) {
      this.investigationSelect = index;
      this.investigationDetailTitle = item.name;
      this.showInvestigationDetail = true;
      // this.$emit('select', this.investigationSelect, this.investigationList[index])
    },
    investigationDetailHandle() {
      this.$emit("select", {
        ...this.json,
        checkedSelect: this.formData,
        extraConfigs: this.investigationDetailList,
      });
    },
  },
  onReady() {},
  // 页面卸载
  onUnload() {},
  // 触发下拉刷新
  onPullDownRefresh() {
    // 延迟关闭刷新动画
    setTimeout(() => {
      uni.stopPullDownRefresh();
    }, 1500);
  },
  // 页面上拉触底事件的处理函数
  onReachBottom() {},
};
</script>

<style>
page {
  background: #ffffff;
}
</style>
<style lang="scss" scoped>
.investigation-item {
  margin: 0 auto 20rpx;
  width: 90%;
  border-radius: 8rpx;
  padding: 20rpx;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
  overflow: hidden;

  &.active {
    background: #dfebf8;
  }
}

.detail-item {
  width: 100%;
  background: #f0f3f7;
  padding: 20rpx 30rpx;
  border-radius: 8rpx;
  box-sizing: border-box;

  /deep/ .uni-forms-item__content {
    justify-content: flex-end;
    text-align: right;
    display: flex;
  }

  /deep/ .uni-forms-item {
    margin-bottom: 0;
  }

  /deep/ .uni-forms-item__label {
  	font-size: 32rpx;
	height: auto;
	margin-bottom: 20rpx;
  }
}

.custom-pop-head {
  width: 100%;
  padding: 20rpx;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #e6e6e6;
  margin-bottom: 20rpx;

  .left {
    color: #666666;
  }

  .title {
    font-size: 16px;
  }

  .right {
    color: #2663bf;
  }
}
</style>