<template>
  <div>
    <van-nav-bar
      title="工单新增"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <div class="listcontent" :style="`height:${bodyheight}px`">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="taskinfo.taskCode"
            name="系统工单"
            label="系统工单"
            placeholder="工单号"
          />
          <van-field
            v-model="taskinfo.taskOtherId"
            name="来件工单号"
            label="来件工单号"
            placeholder="来件工单号"
          />

          <van-field
            v-model="taskdfrom"
            name="事件来源"
            label="事件来源"
            placeholder="点击选择事件来源"
            is-link
            readonly
            @click="showPicker3 = true"
          />
          <van-popup v-model:show="showPicker3" position="bottom">
            <van-picker
              v-model="taskdfrom"
              title="选择事件来源"
              :columns="allfrom"
              @confirm="onConfirm3"
              @cancel="showPicker3 = false"
            />
          </van-popup>

          <van-field
            v-model="taskdarea"
            name="行政区"
            label="行政区"
            placeholder="点击选择行政区"
            is-link
            readonly
            @click="showPicker2 = true"
          />
          <van-popup v-model:show="showPicker2" position="bottom">
            <van-picker
              v-model="taskdarea"
              title="选择行政区"
              :columns="allarea"
              @confirm="onConfirm2"
              @cancel="showPicker2 = false"
            />
          </van-popup>

          <van-field
            v-model="taskinfo.taskAddrRoad"
            name="道路名"
            label="道路名"
            placeholder="道路名"
          />
          <van-field
            v-model="taskinfo.taskComplainConnect"
            name="投诉人电话"
            label="投诉人电话"
            placeholder="投诉人电话"
          />

          <van-field label="班组区域" name="班组区域">
            <template #input>
              <el-tree-select
                v-model="taskinfo.taskDeptRange"
                multiple
                :data="treedept"
                check-strictly="true"
              />
            </template>
          </van-field>

<!--          <van-field-->
<!--            v-model="taskinfo.taskTime"-->
<!--            is-link-->
<!--            readonly-->
<!--            name="picker"-->
<!--            label="来件时间"-->
<!--            placeholder="点击选择时间"-->
<!--            @click="showPicker = true"-->
<!--          />-->

<!--          <van-popup v-model:show="showPicker" position="bottom">-->
<!--            <van-datetime-picker-->
<!--              v-model="taskdate"-->
<!--              type="datetime"-->
<!--              title="选择完整时间"-->
<!--              @confirm="onConfirm"-->
<!--              @cancel="showPicker = false"-->
<!--            />-->
<!--          </van-popup>-->






          <van-field
            v-model="taskinfo.taskReqCompleteTime"
            is-link
            readonly
            name="picker1"
            label="要求完成时间"
            placeholder="点击选择时间"
            @click="showPicker4 = true"
          />

          <van-popup v-model:show="showPicker4" position="bottom">
            <van-datetime-picker
              v-model="taskdate1"
              type="datetime"
              title="选择完整时间"
              @confirm="onConfirm4"
              @cancel="showPicker4 = false"
            />
          </van-popup>

          <van-field
            v-model="taskinfo.taskTime"
            name="处理时限"
            label="处理时限"
            placeholder="处理时限"
            readonly
          />

          <van-field
            v-model="taskdtype"
            name="事件类型"
            label="事件类型"
            is-link
            readonly
            placeholder="点击选择事件类型"
            @click="showPicker1 = true"
          />

          <van-popup v-model:show="showPicker1" position="bottom">
            <van-picker
              v-model="taskdtype"
              title="选择事件类型"
              :columns="alltype"
              @confirm="onConfirm1"
              @cancel="showPicker1 = false"
            />
          </van-popup>

          <van-field
            v-model="taskdcategory"
            name="事件分类"
            label="事件分类"
            is-link
            readonly
            placeholder="点击选择事件分类"
            @click="showPicker5 = true"
          />

          <van-popup v-model:show="showPicker5" position="bottom">
            <van-picker
              v-model="taskdcategory"
              title="选择事件类型"
              :columns="allcategory"
              @confirm="onConfirm5"
              @cancel="showPicker5 = false"
            />
          </van-popup>
          <van-field
            name="任务内容"
            label="任务内容"
            v-model="taskinfo.taskContent"
            rows="2"
            autosize
            type="textarea"
            placeholder="请输入任务内容"
          />

<!--          <van-field-->
<!--            v-model="taskdisconfirm"-->
<!--            name="是否需要确认"-->
<!--            label="是否需要确认"-->
<!--            is-link-->
<!--            readonly-->
<!--            placeholder="点击选择"-->
<!--            @click="showPicker6 = true"-->
<!--          />-->
<!--          <van-popup v-model:show="showPicker6" position="bottom">-->
<!--            <van-picker-->
<!--              v-model="taskdisconfirm"-->
<!--              title="是否需要确认"-->
<!--              :columns="allconfirm"-->
<!--              @confirm="onConfirm6"-->
<!--              @cancel="showPicker6 = false"-->
<!--            />-->
<!--          </van-popup>-->

          <van-field name="接单人员" label="接单人员">
            <template #input>
              <el-select
                v-model="taskinfo.taskReporter"
                filterable
                default-first-option
                :reserve-keyword="false"
                placeholder="请选择人员"
              >
                <el-option
                  v-for="item in allusers"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId+''"
                />
              </el-select>
            </template>
          </van-field>

          <van-field
            v-model="taskinfo.taskFromRemark"
            name="来件备注"
            label="来件备注"
            rows="2"
            autosize
            type="textarea"
            placeholder="来件备注"
          />
          <van-field
            v-model="taskinfo.taskAddr"
            name="详细地址"
            label="详细地址"
            placeholder="详细地址"
          >
            <template #button>
              <van-button
                size="small"
                type="primary"
                icon="search"
                @click="searchaddr"
              ></van-button>
            </template>
          </van-field>
          <div style="padding-top: 10px">
            <MapSelect ref="mapSelect" v-model:formv="formlocation"></MapSelect>
          </div>

          <van-field name="照片附件" label="照片附件">
            <template #input>
              <ImageUpload v-model="fileList"></ImageUpload>
            </template>
          </van-field>
        </van-cell-group>

        <div style="margin: 16px">
          <van-button round block type="primary" native-type="submit">
            提交
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup>
import { defineComponent, ref, onMounted, watch } from "vue";
import { cloneDeep } from "lodash";
import { listDept, getDept } from "@/api/system/dept";
import ImagePreview from "@/components/ImagePreview";
import ImageUpload from "@/components/ImageUpload";
import { useDict } from "@/utils/dict";
import { useRoute } from "vue-router";
import MapSelect from "@/components/MapSelect";
import moment from "moment";
import {
  listTask,
  getTask,
  delTask,
  addTask,
  updateTask,
  distributedTask,
  closeTask,
  czTask,
  gzTask,
  hcTask,
} from "@/api/system/task";
import {
  changeUserStatus,
  listUser,
  resetUserPwd,
  delUser,
  getUser,
  updateUser,
  addUser,
} from "@/api/system/user";
import { Toast } from "vant";
import { treeselect as deptTreeselect } from "@/api/system/dept";
import router from "../../../../router";

const {
  task_status,
  task_event_category,
  task_event_type,
  sys_area,
  task_type,
} = useDict(
  "task_status",
  "task_event_category",
  "task_event_type",
  "sys_area",
  "task_type"
);
const bodyheight = ref(0);
const showPicker = ref(false);
const showPicker1 = ref(false);
const showPicker2 = ref(false);
const showPicker3 = ref(false);
const showPicker4 = ref(false);
const showPicker5 = ref(false);
const showPicker6 = ref(false);
const taskdate = ref(new Date());
const taskdate1 = ref(new Date());
const taskdate2 = ref(new Date());
const taskdate3 = ref(new Date());
const taskdate4 = ref(new Date());

const fileList = ref([]);

const taskdtype = ref("");
const taskdarea = ref("");
const taskdfrom = ref("");
const taskdcategory = ref("");
const taskdisconfirm = ref("");

const alltype = ref([]);
const allarea = ref([]);
const allfrom = ref([]);
const allcategory = ref([]);
const allconfirm = ref(["是", "否"]);

bodyheight.value = document.body.clientHeight - 48;

const onConfirm = () => {
  showPicker.value = false;
  taskinfo.value.taskTime = moment(taskdate.value).format(
    "YYYY-MM-DD HH:mm:ss"
  );
};
const onConfirm1 = (value) => {
  showPicker1.value = false;
  taskdtype.value = value;

  taskinfo.value.taskEventType =
    task_event_type.value.filter(
      (i) => i.label.toString() === (taskdtype.value ?? "").toString()
    )[0]?.value ?? null;
};
const onConfirm2 = (value) => {
  showPicker2.value = false;
  taskdarea.value = value;

  taskinfo.value.taskArea =
    sys_area.value.filter(
      (i) => i.label.toString() === (taskdarea.value ?? "").toString()
    )[0]?.value ?? null;
};
const onConfirm3 = (value) => {
  showPicker3.value = false;
  taskdfrom.value = value;

  taskinfo.value.taskType =
    task_type.value.filter(
      (i) => i.label.toString() === (taskdfrom.value ?? "").toString()
    )[0]?.value ?? null;
};
const onConfirm4 = () => {
  showPicker4.value = false;
  taskinfo.value.taskReqCompleteTime = moment(taskdate1.value==undefined?0: taskdate1.value).format(
    "YYYY-MM-DD HH:mm:ss"
  );
};
const onConfirm5 = (value) => {
  showPicker5.value = false;
  taskdcategory.value = value;

  taskinfo.value.taskEventCategory =
    task_event_category.value.filter(
      (i) => i.label.toString() === (taskdcategory.value ?? "").toString()
    )[0]?.value ?? null;
};
const onConfirm6 = (value) => {
  showPicker6.value = false;
  taskdisconfirm.value = value;

  taskinfo.value.remark = value === "是" ? "1" : "0";
};

const searchaddr = () => {
  if (taskinfo.value.taskAddr) {
    mapSelect.value.searchaddr(taskinfo.value.taskAddr);
  } else {
    Toast("请输入地址");
  }
};

const alldept = ref([]);
listDept().then((response) => {
  alldept.value = cloneDeep(response.data);
});
const allusers = ref([]);
listUser({ pageSize: 1000 }).then((res) => {
  allusers.value = res.rows;
});

const taskinfo = ref({
  taskName: null,
  taskContent: null,
  taskAddr: null,
  taskLocation: null,
  taskCode: null,
  taskType: null,
  taskEventType: null,
  taskEventCategory: null,
  taskFromRemark: null,
  taskAddrRoad: null,
  taskOtherId: null,
  taskTime: null,
  taskArea: "1",
  taskReqCompleteTime: "",
  status: 1,
  taskId: null,
  remark: "",
  taskCreater: null,
  taskReporter: null,
  taskPics: null,
  taskVideos: null,
  taskComplainConnect: null,
  taskDeptRange: "",
  taskFacilitieCode: "",
  remark: "",
});

listTask({ taskCode: moment().year() + "" }).then((res) => {
  taskinfo.value.taskCode =
    moment().format("yyyyMMDD") + (Array(4).join(0) + (res.total + 1)).slice(-4);
});

const mapSelect = ref(null);
const formlocation = ref({ addr: "", locations: "" });
watch(
  () => formlocation.value.addr,
  () => {
    taskinfo.value.taskAddr = formlocation.value.addr;
  }
);
watch(
  () => formlocation.value.locations,
  () => {
    taskinfo.value.taskLocation = formlocation.value.locations;
    if (formlocation.value.locations != "") {
      mapSelect.value.getlocationaddr(formlocation.value.locations, (data) => {
        var qu = data.regeocode.addressComponent.district;
        if (qu) {
          for (var i in sys_area.value) {
            if (sys_area.value[i].label == qu) {
              taskinfo.value.taskArea = sys_area.value[i].value;
              taskdarea.value = sys_area.value[i].label;
            }
          }
        }
      });
    }
  }
);

watch(
  () => fileList.value,
  () => {
    taskinfo.value.taskPics = fileList.value;
  }
);

watch(
  () => task_event_type.value,
  () => {
    alltype.value = task_event_type.value.map((i) => i.label);
  }
);
watch(
  () => sys_area.value,
  () => {
    allarea.value = sys_area.value.map((i) => i.label);
  }
);
watch(
  () => task_type.value,
  () => {
    allfrom.value = task_type.value.map((i) => i.label);
  }
);
watch(
  () => task_event_category.value,
  () => {
    allcategory.value = task_event_category.value.map((i) => i.label);
  }
);
watch(()=>taskinfo.value.taskType,()=>{
  if(task_type.value && task_type.value.length>0){
    for (const index in task_type.value) {
      var typec = task_type.value[index];
      if((typec.value+"") === (taskinfo.value.taskType+"")){
        taskinfo.value.taskTime  = moment().add(typec.remark,'hours').format('YYYY-MM-DD HH:mm:ss')
      }
    }
  }
})

const store = useStore();
const getters = computed(() => store.getters);

taskinfo.value.taskReporter = getters.value.userId.toString();

function setdatakey(dept) {
  if (dept.children) {
    dept.children = dept.children.map((i) => {
      return setdatakey(i);
    });
  }
  dept["value"] = dept.id;
  return dept;
}

const treedept = ref([
  {
    value: "1",
    label: "ss",
  },
  {
    value: "2",
    label: "ss1",
  },
]);
deptTreeselect().then((res) => {
  treedept.value = [setdatakey(res.data[0])];
});

const onSubmit = async () => {
  if (
    taskinfo.taskName === null ||
    taskinfo.taskName === "" ||
    taskinfo.taskCode === null ||
    taskinfo.taskCode === ""
  ) {
    Toast.fail("请填写完整");
    return;
  }

  await addTask(taskinfo.value);
  Toast.success("添加成功");
  router.back();
};

const onClickLeft = () => {
  router.back();
};
</script>

<style lang="scss">
body {
  position: fixed;
  width: 100%;
  top: -1px;
}
.listcontent {
  overflow-y: auto;
  padding: 10px;
}
</style>
