<template>
  <view class="container"
        style="margin-top: 20rpx;">
    <tui-form ref="form"
              :show-message="false"
              :model="form">
      <view class="header">
        <tui-card style="flex: 1;">
          <template>
            <tui-section title="姓名:">
              <view>{{form.find_problem_person_name}}</view>
            </tui-section>
            <tui-section title="单位:">{{form.find_problem_person_id}}</tui-section>
            <tui-section title="岗位:">{{form.find_problem_person_job}}</tui-section>
          </template>
        </tui-card>
        <tui-card style="width: 120px;height: 120px;;margin-left: 0;">
          <template>
            <image :src="form.find_problem_person_avatar?form.find_problem_person_avatar:'/static/images/person.jpg'"
                   style=" width:120px; height:120px;"></image>
          </template>
        </tui-card>
      </view>
      <tui-card style="margin-top: 20rpx;">
        <template>
          <view class="tui-default">
            <tui-form-item labelFontWeight="600">
              <tui-input padding="0"
                         label="项目部:"
                         :borderBottom="false"
                         placeholder="请选择项目部"
                         disabled
                         backgroundColor="transparent"
                         v-model="form.find_problem_org_name">
                <template v-slot:right>
                  <tui-button width="100rpx"
                              height="60rpx"
                              background="#f2f2f2"
                              color="#5677fc"
                              :size="24"
                              bold
                              radius="12rpx"
                              @click="clickProjectDepartment">选择</tui-button>
                </template>
              </tui-input>
            </tui-form-item>
            <tui-form-item asterisk
                           prop="end_time"
                           disabled
                           label="截止时间">
              <view @click="showShow('end_time')"
                    style="z-index:9999999">
                <tui-input placeholder="截止时间"
                           v-model="form.find_problem_deal_deadline"></tui-input>
              </view>
            </tui-form-item>
          </view>
        </template>

      </tui-card>
      <tui-card style="margin-top: 20rpx;">
        <template>
          <view class="tui-default">
            <tui-form-item label="隐患级别:"
                           labelFontWeight="600">
              <tui-radio-group v-model="form.find_problem_level">
                <view style="display: flex;">
                  <tui-label v-for="(item,index) in radioItems"
                             :key="index"
                             margin="0 0 0 10rpx">
                    <tui-radio :checked="item.checked"
                               :value="item.value"
                               color="#5179ef"
                               borderColor="#5179ef">
                    </tui-radio>
                    <text class="tui-text">{{item.name}}</text>
                  </tui-label>
                </view>
              </tui-radio-group>
            </tui-form-item>
          </view>
        </template>
      </tui-card>

      <tui-card :title="{text:'隐患描述'}"
                style="margin-top:20rpx;margin-bottom: 20rpx;overflow:visible;">
        <template v-slot:body>
          <tui-dropdown-list :show="false"
                             :top="200"
                             :height="500">
            <template v-slot:selectionbox>
              <tui-textarea placeholder="请输入隐患描述"
                            v-model="form.find_problem_description">
              </tui-textarea>
            </template>
            <template v-slot:dropdownbox>
              <scroll-view style="height: 500rpx; border: 1px solid #eee;"
                           :scroll-y="true">
                <tui-list-cell :hover="false"
                               :arrow="false"
                               @click="clickCategroy(key,'redline')">
                  {{' 1. 我是选择项阿松大临时搭建拉克斯基狄拉克解释代'}}
                </tui-list-cell>
              </scroll-view>
            </template>
          </tui-dropdown-list>
        </template>
      </tui-card>
      <tui-card :title="{text:'隐患视频'}">
        <template v-slot:body>
          <view style="padding:20rpx;display:flex;flex-wrap:wrap;">
            <view class="unloadlist"
                  v-for="(m,n) in videoList"
                  :key="n">
              <video :src="m"
                     controls></video>
            </view>
            <view class="unloadbut"
                  @click="uploadVideo">
              <tui-icon name="plus"
                        :size="38"></tui-icon>
            </view>
          </view>
        </template>
      </tui-card>
      <tui-card style="margin-top: 20rpx; overflow:visible;">
        <tui-form-item prop="end_time"
                       label="红线工程"
                       @click="showDropdown('redline','showCategroy')">
          <tui-dropdown-list :show="selecteDataType['redline'].showCategroy"
                             :top="94"
                             :height="500">
            <template v-slot:selectionbox>
              <tui-input placeholder='请选择红线工程类型'
                         clearable
                         v-model="selecteDataType['redline'].categroy"></tui-input>
            </template>
            <template v-slot:dropdownbox>
              <scroll-view style="height: 500rpx;"
                           :scroll-y="true">
                <tui-list-cell v-for="[key] in selecteDataType['redline'].map"
                               :hover="false"
                               :arrow="false"
                               :key="key"
                               @click="clickCategroy(key,'redline')">
                  {{ key }}
                </tui-list-cell>
              </scroll-view>

            </template>
          </tui-dropdown-list>
        </tui-form-item>
        <tui-form-item prop="end_time"
                       label="红线问题"
                       @click="showDropdown('redline','showQuestion')">
          <tui-dropdown-list :show="selecteDataType['redline'].showQuestion"
                             :top="94"
                             :height="500">
            <template v-slot:selectionbox>
              <tui-input placeholder='请选择红线问题'
                         clearable
                         v-model="selecteDataType['redline'].question"></tui-input>
            </template>
            <template v-slot:dropdownbox>
              <scroll-view style="height: 400rpx;"
                           scroll-y="true">
                <tui-list-cell v-for="item in selecteDataType['redline'].map.get(selecteDataType['redline'].categroy)"
                               :hover="false"
                               :arrow="false"
                               :key="item.id"
                               @click="clickQuestion(item,'redline')">
                  {{ item.question}}
                </tui-list-cell>
              </scroll-view>

            </template>
          </tui-dropdown-list>
        </tui-form-item>
      </tui-card>
      <tui-card style="margin-top: 20rpx;  overflow:visible;">
        <tui-form-item prop="end_time"
                       label="禁令工程"
                       @click="showDropdown('prohibit','showCategroy')">
          <tui-dropdown-list :show="selecteDataType['prohibit'].showCategroy"
                             :top="94"
                             :height="500">
            <template v-slot:selectionbox>
              <tui-input placeholder='请选择禁令工程类型'
                         clearable
                         v-model="selecteDataType['prohibit'].categroy"></tui-input>
            </template>
            <template v-slot:dropdownbox>
              <scroll-view style="height: 500rpx;"
                           scroll-y="true">
                <tui-list-cell v-for="[key] in selecteDataType['prohibit'].map"
                               :hover="false"
                               :arrow="false"
                               :key="key"
                               @click="clickCategroy(key,'prohibit')">
                  {{ key }}
                </tui-list-cell>
              </scroll-view>

            </template>
          </tui-dropdown-list>

        </tui-form-item>
        <tui-form-item prop="end_time"
                       label="禁令内容"
                       @click="showDropdown('prohibit','showQuestion')">
          <tui-dropdown-list :show="selecteDataType['prohibit'].showQuestion"
                             :top="94"
                             :height="500">
            <template v-slot:selectionbox>
              <tui-input placeholder='请选择禁令内容'
                         clearable
                         v-model="selecteDataType['prohibit'].question"></tui-input>
            </template>
            <template v-slot:dropdownbox>
              <scroll-view style="height: 500rpx;"
                           scroll-y="true">
                <tui-list-cell v-for="item in selecteDataType['prohibit'].map.get(selecteDataType['prohibit'].categroy)"
                               :hover="false"
                               :arrow="false"
                               :key="item.id"
                               @click="clickQuestion(item,'prohibit')">
                  {{ item.content}}
                </tui-list-cell>
              </scroll-view>

            </template>
          </tui-dropdown-list>

        </tui-form-item>
      </tui-card>
      <view class="tui-btn__box">
        <tui-button width="400rpx"
                    height="84rpx"
                    bold
                    @click="submit">上报</tui-button>
      </view>
    </tui-form>
    <tui-bottom-popup :zIndex="1002"
                      :maskZIndex="1001"
                      :show="isShowProjectDepartment"
                      @close="hideProjectDepartment">
      <tui-cascade-selection height="300px"
                             :itemList="tuiCascadeSelection"
                             @complete="changeProjectDepartment">
      </tui-cascade-selection>
    </tui-bottom-popup>
    <view v-show="end_time">
      <tui-datetime ref="end_time"
                    :type="7"
                    @confirm="endDateTimeChange">
      </tui-datetime>
    </view>
  </view>
</template>

<script>
import { mapState } from "vuex";
export default {
  props: {
    //当前问题上传类别
    current_type: {
      type: Number,
      default: 1,
    },
    //所属任务
    type_source_id: {
      type: String,
      default: null,
    },
    //所属隐患描述详情
    type_source_id_detail: {
      type: Object,
      default: null,
    },
    //负责人
    contacts: {
      type: String,
      default: null,
    },
    //负责人id
    contacts_id: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      videoList: [],
      value: [],
      serverUrl:
        "https://anquansys.sxlq.com:37100/uploadoss/upload?token=1add2b5e9c36ce7d75a1ff3d11b9ffb8",
      initializeImg: [], //初始化图片
      radioItems: [
        {
          name: "轻度",
          value: "1",
          checked: true,
        },
        {
          name: "中等",
          value: "2",
          checked: false,
        },
        {
          name: "重度",
          value: "3",
          checked: false,
        },
      ],
      selecteDataType: {
        redline: {
          categroy: "",
          question: "",
          // pageUrl: "/pages/template/everyday/common/selecteDataItem",
          requestUrl: "common/basicData/getRedLine",
          showCategroy: false,
          showQuestion: false,
          id: null,
          map: new Map(),
        },
        prohibit: {
          categroy: "",
          question: "",
          // pageUrl: "/pages/template/everyday/common/selecteDataItem",
          requestUrl: "common/basicData/getProhibit",
          showCategroy: false,
          showQuestion: false,
          id: null,
          map: new Map(),
        },
      },

      form: {
        //-----问题识别到特定的发布者-------
        find_problem_description: "", //【问题描述
        find_problem_video: {}, //【问题视频
        find_problem_redline_type_id: null, //问题 红线类型
        find_problem_prohibit_type_id: null, //问题 禁令类型
        find_problem_type: this.current_type, //【问题类型（（1全员  2专项巡查 3 日常巡查））
        find_problem_type_source_id: this.type_source_id, //【(日常巡查那个任务【日常巡查时间所属id，或者哪个专项巡查)
        find_problem_type_source_id_detail: JSON.stringify(
          this.type_source_id_detail
        ), //【对应巡查任务下面的某一个具体检查内容【日常巡查下针对的所属隐患详情
        //若详情id 是-1  则为其他隐患
        //------------
        find_problem_org_deptcode: "", //【问题所属组织编码
        find_problem_org_id: "", //【问题所属组织id
        find_problem_org_name: "", //【问题所属组织名称
        find_problem_company_org_deptcode: "", //【问题所属公司编码
        find_problem_company_org_id: "", //【问题所属公司id
        find_problem_company_org_name: "", //【问题所属公司名称
        find_problem_level: "", //【问题等级  （123分别表示 轻中重）
        find_problem_time: "", //【问题发现时间
        find_problem_deal_deadline: "", //【问题发现要解决完成的截至时间

        find_problem_person_id: "", //【问题发现人id
        find_problem_person_name: "", //【问题发现人名称
        find_problem_person_job: "", //【问题发现人的工作岗位
        find_problem_person_avatar: "", //【问题发现人的头像
        find_problem_address: "", //【发现问题的位置
        find_problem_location: "", //【发现问题位置经纬度
        find_problem_person_org_id: "", //【发现人组织id
        find_problem_person_org_name: "", //【发现人组织名称
        find_problem_person_org_deptcode: "", //【发现人组织deptcode

        the_problem_is_distribution: 1, //【问题是否被分配（1 未分配  2 已分配）
        distribution_person_id: "", //【分配人id
        distribution_person_name: "", //【分配人名称
        distribution_problem_time: "", //【问题分配时间
        the_problem_is_deal: 1, //【问题是否被处理 （1 未处理  2已处理）
        deal_problem_person_name: "", //【处理人姓名
        deal_problem_person_id: "", //【处理人id
        deal_problem_person_org_id: "", //【处理人组织id
        deal_problem_person_org_name: "", //【处理人组织名称
        deal_problem_person_org_deptcode: "", //【处理人组织身份证
        deal_problem_description: "", //【处理问题描述
        deal_problem_video: "", //【处理问题视频
        deal_problem_time: "", //【问题处理时间
        the_problem_is_comment: 1, //【问题是否被评论
        comment_problem_person_id: "", //【评论人id
        comment_problem_person_name: "", //【评论人名称
        comment_problem_score: "", //【评论人评论分
        comment_problem_is_solve: 1, //【评论问题是否解决 ( 1解决 2 未解决)
        comment_problem_time: "", //【评论时间
      },
      rules: [
        {
          name: "find_problem_org_name",
          rule: ["required"],
          msg: ["项目部不能为空,请选择"],
        },
      ],
      isShowProjectDepartment: false,
      end_time: false,
    };
  },
  computed: {
    ...mapState(["userinfo", "roleName", "tuiCascadeSelection"]),
  },
  mounted() {
    this.onLoading();
  },
  methods: {
    showShow: function (ref = "end_time") {
      this.$refs[ref] && this.$refs[ref].show();
      this[ref] = true;
    },
    endDateTimeChange(e) {
      this.form.find_problem_deal_deadline = e.result;
      this[ref] = false;
    },
    onLoading() {
      this.form.find_problem_person_id = this.userinfo.userId;
      this.form.find_problem_person_name = this.userinfo.nickname;
      this.form.find_problem_person_job = this.roleName;
      this.form.find_problem_person_avatar = this.userinfo.avatar;
      // this.form.find_problem_person_org_id = this.userinfo.org[0].id;
      // this.form.find_problem_person_org_name = this.userinfo.org[0].name;
      this.form.find_problem_person_org_deptcode =
        this.userinfo.org[0].deptcode;
      //获取红线和禁令数据
      this.getRedLine();
      this.getProhibit();
    },
    submit() {
      uni.showLoading({
        title: "提交中...",
      });
      this.$refs.form
        .validate(this.form, this.rules)
        .then(async (res) => {
          if (res.isPass) {
            if (!this.form?.find_problem_org_name) {
              uni.showToast({
                icon: "none",
                title: "项目部不能为空,请选择",
                duration: 2000,
              });
              return;
            }
            let model = JSON.parse(JSON.stringify(this.form));
            if (!!this.selecteDataType.redline.question)
              model.find_problem_redline_type_id =
                this.selecteDataType.redline.id;
            if (!!this.selecteDataType.prohibit.question)
              model.find_problem_prohibit_type_id =
                this.selecteDataType.prohibit.id;
            model.contacts = this.contacts; //责任人
            model.contacts_id = this.contacts_id ?? null;
            const res = await this.$request.post("patrol/problem/store", {
              body: model,
            });
            uni.hideLoading();
            if (res.code == 0) {
              uni.showToast({
                icon: "success",
                title: "上报成功",
                duration: 2000,
              });
              //重置参数
              this.form.find_problem_description = "";
              this.form.find_problem_video = {};
              this.videoList = [];
            } else {
              uni.showToast({
                icon: "error",
                title: res.msg,
                duration: 2000,
              });
            }
          } else {
            uni.hideLoading();
            uni.showToast({
              icon: "error",
              title: "请填写完整信息",
              duration: 2000,
            });
          }
        })
        .catch((errors) => {
          console.log(errors);
        });
    },
    //单选框发生变化
    chnageHandle(e) {
      console.log(e);
    },
    // 获取上传状态
    async uploadVideo(e) {
      if (!!this.form?.deal_problem_video?.url) {
        uni.showToast({
          title: "只支持上传一个视频,再次上传会替换原视频!",
          icon: "none",
          duration: 2000,
        });
      }
      uni.chooseVideo({
        sourceType: ["camera", "album"],
        success: (res) => {
          const tempFilePath = res.tempFilePath;
          const voideName = res.name;
          uni.showLoading({
            title: "上传中...",
          });
          uni.uploadFile({
            url: this.serverUrl,
            filePath: tempFilePath,
            name: "file",
            fileType: "video",
            success: (resFile) => {
              this.videoList = [JSON.parse(resFile.data).data.url];
              this.form.find_problem_video = {
                url: this.videoList[0],
                name: voideName,
              };
              uni.hideLoading();
              uni.showToast({
                title: "上传成功",
                icon: "success",
                duration: 2000,
              });
            },
            fail: (res) => {
              uni.hideLoading();
              uni.showToast({
                title: "上传失败",
                icon: "error",
              });
            },
          });
        },
      });
    },
    clickProjectDepartment() {
      this.isShowProjectDepartment = true;
    },
    hideProjectDepartment() {
      this.isShowProjectDepartment = false;
    },
    changeProjectDepartment(data) {
      let leng = data.result.length - 1;
      //组织
      this.form.find_problem_org_deptcode = data.result[leng].value.deptcode;
      this.form.find_problem_org_id = data.result[leng].value.id;
      this.form.find_problem_org_name = data.result[leng].text;
      if (leng >= 1) {
        //公司
        leng = leng - 1;
        this.form.find_problem_company_org_deptcode =
          data.result[leng].value.deptcode;
        this.form.find_problem_company_org_id = data.result[leng].value.id;
        this.form.find_problem_company_org_name = data.result[leng].text;
      }
    },
    showDropdown(typeText, showText) {
      this.selecteDataType[typeText][showText] =
        !this.selecteDataType[typeText][showText];
    },
    clickCategroy(key, typeText) {
      this.selecteDataType[typeText].categroy = key;
    },
    clickQuestion(value, typeText) {
      if (typeText == "prohibit")
        this.selecteDataType[typeText].question = value.content;
      else this.selecteDataType[typeText].question = value.question;
      this.selecteDataType[typeText].id = value.id;
    },
    //获取红线和禁令的 数据
    async getRedLine() {
      const res = await this.$request.get(
        this.selecteDataType["redline"].requestUrl
      );
      this.mapFor(res.data, this.selecteDataType["redline"].map);
    },
    async getProhibit() {
      const res = await this.$request.get(
        this.selecteDataType["prohibit"].requestUrl
      );
      this.mapFor(res.data, this.selecteDataType["prohibit"].map);
    },
    mapFor(data, map) {
      data.forEach((element) => {
        if (!map.has(element.categroy)) map.set(element.categroy, [element]);
        else map.set(element.categroy, [...map.get(element.categroy), element]);
      });
    },
    navTo(typeText) {
      const url = this.selecteDataType[typeText];
      uni.navigateTo({
        url: url.pageUrl,
        success: (res) => {
          res.eventChannel.emit("acceptDataFromOpenerPage", {
            url: url.requestUrl,
          });
        },
        event: {
          backReturn: (item) => {
            console.log("结果返回", item);
          },
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  padding-bottom: 320rpx;
}
.header {
  display: flex;
}

.tui-title {
  width: 100%;
  font-size: 28rpx;
  color: #888;
  padding: 30rpx;
  box-sizing: border-box;
}

.tui-btn__box {
  width: 100%;
  padding: 60rpx 0;
  display: flex;
  justify-content: center;
}

.tui-text {
  font-size: 30rpx;
  padding-left: 12rpx;
}
.unloadbut {
  width: 180rpx;
  height: 180rpx;
  background: #f7f7f7;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>