<template>
  <div class="">
    <el-form ref="ref_form"
             :inline="false"
             :model="formData"
             :rules="dataRule"
             label-width="100px">
      <el-form-item label="项目标题"
                    prop="title"
                    label-width="150px"
                    style="display: block">
        <el-input class="cell-width-1"
                  maxlength="50"
                  placeholder="请输入项目标题"
                  v-model="formData.title">
        </el-input>
      </el-form-item>

      <el-form-item label="所属网格	"
                    prop="gridId"
                    label-width="150px"
                    style="display: block">
        <el-select v-model.trim="formData.gridId"
                   placeholder="请选择"
                   clearable
                   class="cell-width-1">
          <el-option v-for="item in gridList"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="处理部门"
                    label-width="150px"
                    prop="projectStaffId">
        <el-popover placement="bottom"
                    width="400"
                    height="400"
                    v-model="visibleStaffPanel">
          <div class="f">
            <select-staff @confirm="(ret) => (formData.staffList = ret)"
                          @close="visibleStaffPanel = false" />
          </div>

          <div slot="reference">
            <a v-if="formData.staffList.length == 0"
               style="cursor: pointer">点击选择</a>
            <a v-else
               style="cursor: pointer">已选 {{ formData.staffList.length }} 人</a>
          </div>
        </el-popover>
      </el-form-item>

      <el-form-item label="协办单位"
                    label-width="150px"
                    prop="assistanceUnitIndex">
        <el-select v-model.trim="formData.assistanceUnitIndex"
                   placeholder="请选择"
                   class="cell-width-1">
          <el-option v-for="(item, index) in assistanceUnitList"
                     :key="item.assistanceUnitId"
                     :label="item.assistanceUnitName"
                     :value="index">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="项目方案"
                    label-width="150px"
                    prop="publicReply">
        <el-input type="textarea"
                  class="cell-width-area"
                  :rows="2"
                  placeholder="请输入项目方案"
                  v-model="formData.publicReply">
        </el-input>
      </el-form-item>

      <el-form-item label="内部备注"
                    label-width="150px"
                    prop="internalRemark">
        <el-input type="textarea"
                  class="cell-width-area"
                  :rows="2"
                  placeholder="请输入内部备注"
                  v-model="formData.internalRemark">
        </el-input>
      </el-form-item>

      <el-form-item label="图片/附件："
                    label-width="150px"
                    prop="internalFile">
        <el-upload class="avatar-uploader"
                   :action="uploadUlr"
                   :data="{ customerId: customerId }"
                   :show-file-list="true"
                   :on-success="handleImgSuccess"
                   :on-remove="handleImgRemove"
                   :before-upload="beforeImgUpload">
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="标签"
                    label-width="150px"
                    prop="tagList">

        <fold-text v-if="tagList.length>0"
                   style="width: 300px"
                   :row="3">
          <div :key="item.name"
               v-for="item in tagList">
            {{ item.name }}
          </div>
        </fold-text>

        <el-popover placement="bottom"
                    width="400"
                    height="400"
                    v-model="visibleTagPanel">
          <div class="f"
               style="min-height: 120px">
            <h2>选择标签</h2>
            <el-select v-model="selectedTagData"
                       multiple
                       allow-create
                       filterable
                       placeholder="请选择"
                       @change="handleTagChange">
              <el-option-group label="自定义标签">
                <el-option v-for="item in tagOptions.customized"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-option-group>

              <el-option-group label="常用标签">
                <el-option v-for="item in tagOptions.defaulted"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-option-group>
            </el-select>

            <el-button style="margin-left: 10px"
                       size="small"
                       type="danger"
                       @click="updateProjectTag">关闭</el-button>
          </div>
          <div slot="reference">
            <el-button size="small"
                       type="">选择</el-button>
          </div>
        </el-popover>
      </el-form-item>

    </el-form>

  </div>
</template>

<script>
import { Loading } from "element-ui"; // 引入Loading服务
import { requestPost } from "@/js/dai/request";
import selectStaff from "@/views/components/selectStaff";
import formVltHelper from "dai-js/tools/formVltHelper";
import foldText from "@/views/components/foldText";

import { isCard } from "@/utils/validate";

let loading; // 加载动画
function iniFmData () {
  return {
    operationType: '1',//处理方式[0:已回复 1:已转项目  1:已转需求]	
    publicReply: '',//项目方案 1000	
    internalRemark: '',//	内部备注 1000	
    gridId: '',//
    assistanceUnitIndex: '',
    assistanceUnitId: '',//	协办单位Id	
    assistanceUnitType: '',//	 协办单位类型，1社区自组织，2联建单位	
    staffList: [],// 	勾选人员信息	
    categoryList: [],//	 	
    tagList: [],//	

    internalFile: [],//	
    title: '',//		

    publicFile: [],// 	
    locateAddress: '',//		
    locateLongitude: '',//	
    locateDimension: '',//	
    eventId: '',//	
  };
}
export default {
  data () {
    return {
      btnDisable: false,
      customerId: localStorage.getItem("customerId"),
      gridList: [],//所属网格list--场所区域
      myDepartmentList: [],//部门数组
      visibleStaffPanel: false,
      assistanceUnitList: [],//协办单位数组
      tagList: [],//标签数组

      tagOptions: [],
      visibleTagPanel: false,
      selectedTagData: [],


      formData: iniFmData(),
      formDataTemp: {
        assistanceUnitIndex: 0,
        assistanceUnitId: '',//	协办单位Id	
        assistanceUnitType: '',//	 协办单位类型，1社区自组织，2联建单位	

        eventId: "",
        gridId: "63d5ff92ea981b1c58e4914ac894c610",
        internalRemark: "内部备注",
        operationType: "1",
        projectStaffId: "1514068005825622017",
        publicReply: "项目方案",
        title: "3123123",

        internalFile: [],
        staffList: [],
        tagList: [{
          id: "46294b3c9f96ee4d0b00e997e06c8f97",
          isDisable: "enable",
          name: "车行道、人行道、盲道、无障碍通道、路名牌",
        },
        {
          id: "953bafc1191f784841d9b8da61ec7b9b",
          isDisable: "enable",
          name: "城市广场管理",
        }],


      },

      okflag: false,

      uploadUlr: window.SITE_CONFIG["apiURL"] + "/oss/file/uploadqrcodeV2",
      eventDetailCopy: {}

    };
  },
  components: { selectStaff, foldText },
  computed: {
    dataRule () {

      return {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" },
        ],
        gridId: [
          { required: true, message: "所属网格不能为空", trigger: "blur" },
        ],
        projectStaffId: [
          { required: true, message: "处理部门不能为空", trigger: "blur" },
        ],
        publicReply: [
          { required: true, message: "项目方案不能为空", trigger: "blur" },
        ],

      };
    },


  },
  props: {

    eventDetailData: {
      type: Object,
      default () {
        return {}
      }
    },
  },
  watch: {
    "formData.assistanceUnitIndex": function (val) {

      if (val === "" || this.assistanceUnitList.length === 0) {
        this.formData.assistanceUnitId = "";
        this.formData.assistanceUnitType = "";
      } else {
        this.formData.assistanceUnitId =
          this.assistanceUnitList[val].assistanceUnitId;
        this.formData.assistanceUnitType =
          this.assistanceUnitList[val].assistanceUnitType;
      }
    },

    async selectedTagData (val) {
      const { tagOptions } = this;
      this.tagList = await Promise.all(
        val.map(async (id) => {
          let ele = [...tagOptions.customized, ...tagOptions.defaulted].find(
            (item) => item.id == id || item.name == id
          );
          if (!ele) {
            await this.createTag(id);
            ele = [
              ...this.tagOptions.customized,
              ...this.tagOptions.defaulted,
            ].find((item) => item.name == id);
            if (!ele)
              return {
                id: "",
                name: ele.name,
              };
          }
          return {
            id: ele.id,
            name: ele.name,
          };
        })
      );

      this.tagList = this.tagList.filter((item) => item.id);
      console.log(this.tagList)
    },
  },

  async mounted () {
    const { user } = this.$store.state
    this.agencyId = user.agencyId
    this.loadGrid();
    this.getMyDepartmentList();
    this.getAssistanceUnitList();
    this.getTagList()
    // this.formData = { ...this.formDataTemp }
    if (this.eventId) {
      this.eventDetailCopy = JSON.parse(JSON.stringify(this.eventDetailData));
    } else {

    }
  },

  methods: {
    async loadGrid () {
      const url = "/gov/org/customergrid/gridoption"

      let params = {
        agencyId: this.agencyId
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.gridList = data

      } else {
        this.$message.error(msg)
      }

    },

    //加载处理部门数据
    async getMyDepartmentList () {
      const url = "/gov/project/trace/approvalagencylist";

      const { data, code, msg } = await requestPost(url, {
        issueId: '',
        projectStaffId: '',
      });

      if (code === 0) {
        this.myDepartmentList = data.subAgencyList;
      } else {
        this.$message.error(msg);
      }
    },

    //加载协同单位数据
    async getAssistanceUnitList () {
      const url = "/heart/icpartyunit/assistanceUnitList";

      const { data, code, msg } = await requestPost(url, {
        // projectId: this.projectIdCopy,
      });

      if (code === 0) {
        this.assistanceUnitList = data;

      } else {
        this.$message.error(msg);
      }
    },
    //加载标签
    async getTagList () {
      const url = "/gov/issue/issueprojecttagdict/list";

      const { data, code, msg } = await requestPost(url, {
        // categoryList: this.projectCate,
      });

      if (code === 0) {
        this.tagOptions = {
          customized: data.customized,
          defaulted: data.defaulted,
        };
      } else {
        this.$message.error(msg);
      }
    },


    handleTagChange (val) {
      console.log(val);
    },
    updateProjectTag () {
      this.visibleTagPanel = false;
    },


    async getProjectInfo () {
      this.okflag = false
      this.$refs["ref_form"].validate((valid, messageObj) => {
        if (!valid) {
          app.util.validateRule(messageObj);

        } else {

          this.formData.tagList = this.tagList
          this.okflag = true
        }
      });
    },

    beforeImgUpload (file) {
      const isLt1M = file.size / 1024 / 1024 < 10;

      if (!isLt1M) {
        this.$message.error("上传文件大小不能超过 10MB!");
      }
      return isLt1M;
    },
    resetData () {

    },
    handleImgSuccess (res, file, fileList) {
      console.log("res.data.url", file);
      if (res.code === 0 && res.msg === "success") {
        console.log("res.data.url", res.data.url);
        this.formData.internalFile.push({
          format: file.name.split(".").pop(),
          name: file.name,
          size: file.size,
          type: file.raw.type,
          url: res.data.url,
        });
        console.log(this.formData.internalFile);
      } else {
        this.$message.error(res.msg);
      }
    },

    handleImgRemove (file) {
      let index = this.formData.internalFile.findIndex(
        (item) => item.url == file.response.data.url
      );
      this.formData.internalFile.splice(index, 1);
      console.log(this.formData.internalFile);
    },


    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: "正在加载……", // 加载中需要显示的文字
        background: "rgba(0,0,0,.7)", // 背景颜色
      });
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close();
      }
    },
  },
};
</script>
<style
  lang="scss"
  src="@/assets/scss/modules/shequzhili/event-info.scss"
  scoped
></style>
<style
  lang="scss"
  src="@/assets/scss/modules/shequzhili/project-info.scss"
  scoped
></style>




<style>
.el-dialog__body {
  padding: 0 10px 20px !important;
}
</style>
