<template>
  <!-- 申请任务弹窗 -->
  <el-dialog
    :visible.sync="dialogVisible"
    :show-close="false"
    width="800px"
    :before-close="handleClose"
    v-loading="initLoading"
  >
    <template slot="title">
      <div class="dialogTitle">
        <div class="dialogTitleIcon"></div>
        发到手机-新建任务
      </div>
    </template>
    <el-form ref="createTaskForm" :model="createTaskForm" :rules="createTaskRrules" label-width="80px">
      <el-form-item label="任务名称" prop="c_task_name">
        <el-input v-model="createTaskForm.c_task_name" placeholder="请输入任务名称"></el-input>
      </el-form-item>
      <el-form-item label="关联任务" prop="c_associated_item_ids">
        <el-select
          v-model="createTaskForm.c_associated_item_ids"
          filterable
          :loading="selectLoading"
          @change="changePorject"
          placeholder="请选择"
          width="100%"
          clearable
        >
          <el-option
            v-for="item in selectSelectDataMap.associatedItemsOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属街道" prop="c_area_code">
        <el-input v-model="c_area_code_str" disabled placeholder="请选择关联任务，自动填入"></el-input>
      </el-form-item>
      <el-form-item label="任务类型" prop="c_task_type">
        <el-input v-model="c_task_type_str" disabled placeholder="请选择关联任务，自动填入"></el-input>
      </el-form-item>
      <el-form-item label="选择疑点">
        <el-cascader
          v-model="c_doubtful_pointsList"
          :disabled="legendTreeOptionsLoading"
          :options="legendTreeOptions"
          placeholder="请选择关联任务，动态生成"
          :props="cascaderProps"
          clearable
        ></el-cascader>
      </el-form-item>
      <!-- <el-form-item label="截止时间" prop="c_end_time">
        <el-date-picker v-model="createTaskForm.c_end_time" type="date" placeholder="请选择截止日期"> </el-date-picker>
      </el-form-item> -->
      <el-form-item label="任务描述" prop="c_task_description">
        <el-input
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 6 }"
          placeholder="请描述任务"
          v-model="createTaskForm.c_task_description"
          width="100%"
        ></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="clearDialogVisible('createTaskForm')">取 消</el-button>
      <el-button type="primary" @click="subMitDialogVisible('createTaskForm')">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
/**
 * 底部菜单（发到手机）组件
 * @author: LiuMengxiang
 * @Date: 2022年11月21-25日
 */
export default {
  name: "PutPhone",
  components: {},
  data() {
    return {
      initLoading: true,
      submitLoading: false,
      selectLoading: false,
      // 申请任务弹窗显示状态
      dialogVisible: false,
      legendTree: [],
      legendTreeOptionsLoading: true,
      legendTreeOptions: [],
      cascaderProps: {
        multiple: true
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      c_doubtful_pointsList: [],
      // 新建任务form表单
      createTaskForm: {
        title: "",
        content: "申请任务",
        c_task_id: "", // 任务id
        c_task_name: "", // 任务名称
        c_associated_item_ids: "", // 关联项目ids
        c_create_time: "", // 当前时间时间戳
        c_task_description: "", // 任务描述
        c_user_id: "", // 用户id
        c_area_code: "", // 所属街道行政区划编码
        c_doubtful_points: "", // 疑点信息
        c_end_time: "", // 截止时间
        c_task_type: "" // 任务类型（所有图层中的某图层栏目名）
      },
      c_task_type_str: "", // 任务类型中文转义
      c_area_code_str: "", // 所属街道行政区划编码中文转义
      // 新建任务form表单校验
      createTaskRrules: {
        c_task_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur"
          }
        ],
        c_task_type: {
          required: true,
          message: "请选择任务类型",
          trigger: "change"
        },
        c_associated_item_ids: {
          required: true,
          message: "请选择关联项目",
          trigger: "change"
        },
        c_area_code: {
          required: true,
          message: "请选择所属街道",
          trigger: "change"
        },
        c_end_time: {
          required: true,
          message: "请选择结束时间",
          trigger: "change"
        },
        c_task_description: [
          { required: false, message: "请输入任务描述", trigger: "blur" },
          {
            min: 1,
            max: 255,
            message: "长度在 1 到 255 个字符",
            trigger: "blur"
          }
        ]
      },
      // 数据字典暂存对象
      selectSelectDataMap: {
        projectType: [],
        associatedItems: [],
        associatedItemsOptions: []
      },
      streetOfOwnership_str: "",
      taskType_str: ""
    };
  },
  created() {
    // 首先获取数据字典中的下拉框数据
    this.selectSelectData("0", "c_task_type", "projectType");
    this.selectSelectData("0", "浦东新区行政区划", "associatedItems");
    // 请求所有项目数据
    this.getAllPorjects();
  },
  mounted() {
    // 申请任务事件监听
    this.$bus.$off("putPhone");
    this.$bus.$on("putPhone", () => {
      this.changeShowBottomMenusStatus();
    });
  },
  destroy() {
    // 当容器销毁时，需要停止监听该事件
    this.$bus.$off("putPhone");
  },
  props: [],
  methods: {
    // 用户切换关联项目
    changePorject(value) {
      // 根据项目id得到所属街道和项目类型
      this.selectSelectDataMap.associatedItemsOptions.forEach(item => {
        if (item.value == value) {
          this.createTaskForm.c_area_code = item.c_area_code;
          this.createTaskForm.c_task_type = item.c_task_type;
        }
      });
      // 所属街道遍历渲染
      this.selectSelectDataMap.projectType.forEach(item => {
        if (item.index == this.createTaskForm.c_task_type) {
          this.c_task_type_str = item.name;
        }
      });
      // 任务类型遍历渲染
      this.selectSelectDataMap.associatedItems.forEach(item => {
        if (item.index == this.createTaskForm.c_area_code) {
          this.c_area_code_str = item.name;
        }
      });

      this.$bus.$emit("openMyTask", [this.createTaskForm.c_task_type, this.createTaskForm.c_area_code]);
    },
    // 数据字典查询
    selectSelectData(type, cName, keyName) {
      let params = new FormData();
      params.append("type", type);
      params.append("cName", cName);
      this.$Post(this.urlsCollection.selectByCNameAType, params).then(
        res => {
          if (res.code === 200 && res.content.length > 0) {
            this.selectSelectDataMap[keyName] = res.content;
          }
        },
        error => {
          this.$message.error(error);
          console.log(error);
        }
      );
    },
    // 请求获取所有关联项目数据
    getAllPorjects() {
      if (!this.initLoading) {
        this.initLoading = true;
      }
      let params = new FormData();
      params.append("columnId", "48");
      params.append("states", "2,3");
      params.append("pageSize", 999);
      params.append("page", 0);
      let sortparam = [{ field: "c_create_time", orderByType: 2 }];
      params.append("orderBy", JSON.stringify(sortparam));
      this.$Post(this.urlsCollection.selectContentList, params).then(
        res => {
          if (res.code === 200 && res.content.data.length > 0) {
            let associatedItemsOptionsData = res.content.data;
            associatedItemsOptionsData.filter(item => {
              this.selectSelectDataMap.associatedItemsOptions.push({
                label: item.c_task_name,
                value: item.id,
                c_area_code: item.c_area_code,
                c_task_type: item.c_task_type
              });
            });
            this.initLoading = false;
          } else {
            this.initLoading = false;
            this.$message.error(res.message);
          }
        },
        error => {
          this.initLoading = false;
          this.$message.error(error);
        }
      );
    },
    remoteMethod(query) {
      if (query !== "") {
        this.selectLoading = true;
        setTimeout(() => {
          // 开始动态请求服务器数据并赋值给options对象
          this.selectLoading = false;
          this.selectSelectDataMap.associatedItemsOptions = [];
        }, 200);
      } else {
        this.selectSelectDataMap.associatedItemsOptions = [];
      }
    },
    // 当用户点击svg底座时，切换底部菜单显示隐藏状态。
    changeShowBottomMenusStatus() {
      // 打开弹窗
      this.dialogVisible = true;
      this.$emit("changeShowBottomMenusStatus", false);
    },
    // 弹窗关闭询问
    handleClose() {
      if (this.dialogVisible) {
        this.$confirm("确认关闭？")
          .then(_ => {
            this.clearDialogVisible("createTaskForm");
          })
          .catch(_ => {});
      }
    },
    // 申请任务取消
    clearDialogVisible(formName) {
      // 关闭弹窗
      this.dialogVisible = false;
      // 重置表单
      this.$refs[formName].resetFields();
      // 修改父级菜单变量（弹窗显示状态和显示底部菜单）
      this.$emit("changeShowBottomMenusStatus", true);
    },
    // 申请任务提交
    subMitDialogVisible(formName) {
      // 表单校验
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.c_doubtful_pointsList) {
            this.c_doubtful_pointsList.forEach(item => {
              this.createTaskForm.c_doubtful_points = item[1];
              this.createTaskForm.c_task_id = this.$CryptoJS.buildGuid();
              this.createTaskForm.c_user_id = localStorage.getItem("USER_ID");
              this.createTaskForm.c_create_time = parseInt(new Date().getTime() / 1000) * 1000;
              this.createTaskForm.title = this.createTaskForm.c_task_name;
              // 开始提交
              let params = new FormData();
              params.append("columnId", "1537");
              params.append("modelId", "909");
              params.append("content", JSON.stringify(this.createTaskForm));
              this.$Post(this.urlsCollection.addContent, params).then(
                res => {
                  if (res.code === 200) {
                    this.$message.success(res.message);
                    this.submitLoading = false;
                  } else {
                    this.submitLoading = false;
                    this.$message.error(res.message);
                  }
                },
                error => {
                  this.submitLoading = false;
                  this.$message.error(error);
                }
              );
            });
          }
          setTimeout(() => {
            // 检验成功后关闭弹窗
            this.clearDialogVisible(formName);
          }, 0);
        } else {
          return false;
        }
      });
    },
    getAllLegendData() {
      if (this.legendTree.children.length > 0) {
        this.legendTreeOptionsLoading = true;
        this.legendTree.children.forEach(item => {
          this.getLegendData(item.columnId, item.label);
        });
        this.legendTreeOptionsLoading = false;
      }
    },
    getLegendData(columnId, label) {
      let layerParams = new FormData();
      layerParams = {
        columnId: columnId,
        states: "0,1,2,3",
        pageSize: 10,
        page: 0
      };
      this.$Post(this.urlsCollection.selectContentList, layerParams).then(
        res => {
          //   if (res.code === 202 && res.content === "数据不存在") {
          //     this.$message.info("暂无数据!");
          //   }
          if (res.code === 200 && res.content.data.length > 0) {
            // 初始化时将请求到的疑点数据中是否疑点全部改为未标记，疑点，非疑点三种状态
            let childrens = res.content.data.map(item => {
              if (item.c_content) {
                let conetentJson = JSON.parse(item.c_content);
                // console.log(conetentJson.id, conetentJson.properties["图斑编号"]);
                return {
                  label: conetentJson.id,
                  value: item.c_content
                };
              }
            });
            this.legendTreeOptions.push({
              value: columnId,
              label: label,
              children: childrens
            });
          }
        },
        error => {
          this.$message.error("请求错误!");
        }
      );
    }
  },
  watch: {
    "$store.state.legendTree": {
      handler(val) {
        if (val && val.length > 0) {
          val.forEach(item => {
            if (item.label == this.c_task_type_str) {
              this.legendTree = item;
              this.getAllLegendData();
            }
          });
        }
      }
    }
  }
};
</script>
