<template>
  <div>
    <van-nav-bar
      :title="route.query.bh == '1' ? '驳回反馈' : '处置反馈'"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <div class="listcontent" :style="`height:${bodyheight}px`">
      <div v-if="route.query.bh == '1'">
        <van-form @submit="onSubmitbh">
          <van-cell-group>
            <van-field
              v-model="bhobj.resonRemark"
              name="驳回原因"
              label="驳回原因"
              placeholder="请输入驳回原因"
            />
            <van-field name="现场图片" label="现场图片">
              <template #input>
                <ImageUpload v-model="bhobj.images"></ImageUpload>
              </template>
            </van-field>

            <van-field name="说明报告" label="说明报告">
              <template #input>
                <FileUpload v-model="bhobj.files" :fileSize="100"></FileUpload>
              </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 v-if="route.query.bh != '1'">
        <van-form @submit="onSubmit">
          <van-cell-group>
            <van-field
              v-model="czobj.qsdes"
              name="权属确认"
              label="权属确认"
              placeholder="请输入权属确认(现场勘查)"
            />
            <van-field
              v-model="xyobj.zyrs"
              name="作业人数"
              label="作业人数"
              type="number"
              placeholder="请输入"
            />
            <van-field
              v-model="xyobj.carxh"
              name="车辆型号"
              label="车辆型号"
              placeholder="请输入车辆型号"
            />
            <van-field
              v-model="xyobj.carnumber"
              name="车辆号牌"
              label="车辆号牌"
              placeholder="请输入车辆号牌"
            />
            <van-field
              v-model="xyobj.gls"
              name="公里数"
              label="公里数"
              placeholder="请输入公里数"
            />


            <van-tabs v-model:active="activeName">
              <van-tab title="工作量" name="1">
                <van-row>
                  <van-col :span="24" v-for="item in czobj.gzldata">
                    <div style="margin-bottom:10px">
                       <van-row>
                      <!-- <van-col :span="8"><div style="text-align: right;padding-right:6px">{{ item.name }}:</div></van-col> -->
                      <van-col :span="item.hasOwnProperty('value2') ? 16 : 24">
                        <van-field
                          v-model="item.value1"
                          placeholder="请输入"
                          :label="item.name"
                        >
                          <template #button v-if="item.unit1!==''">{{
                            item.unit1
                          }}</template></van-field
                        >
                      </van-col>
                      <van-col :span="8" v-if="item.hasOwnProperty('value2')">
                        <div style="padding-left:5px">
                           <van-field
                          v-if="item.hasOwnProperty('value2')"
                          v-model="item.value2"
                          placeholder="请输入"
                        >
                          <template #button v-if="item.unit2!==''">{{
                            item.unit2
                          }}</template></van-field>
                        </div>
                      </van-col>
                    </van-row>

                    </div>
                  </van-col>

                </van-row>
              </van-tab>
              <van-tab title="车辆设备" name="2">
                 <van-row>
                  <van-col :span="24" v-for="item in czobj.clsbdata">
                    <div style="margin-bottom:10px">
                       <van-row>
                      <!-- <van-col :span="8"><div style="text-align: right;padding-right:6px">{{ item.name }}:</div></van-col> -->
                      <van-col :span="item.hasOwnProperty('value2') ? 16 : 24">
                        <van-field
                          v-model="item.value1"
                          placeholder="请输入"
                          :label="item.name"
                        >
                          <template #button v-if="item.unit1!==''">{{
                            item.unit1
                          }}</template></van-field
                        >
                      </van-col>
                      <van-col :span="8" v-if="item.hasOwnProperty('value2')">
                        <div style="padding-left:5px">
                           <van-field
                          v-if="item.hasOwnProperty('value2')"
                          v-model="item.value2"
                          placeholder="请输入"
                        >
                          <template #button v-if="item.unit2!==''">{{
                            item.unit2
                          }}</template></van-field>
                        </div>
                      </van-col>
                    </van-row>

                    </div>
                  </van-col>

                </van-row>
              </van-tab>
              <van-tab title="耗材" name="3">
                 <van-row>
                  <van-col :span="24" v-for="item in czobj.hcdata">
                    <div style="margin-bottom:10px">
                       <van-row>
                      <!-- <van-col :span="8"><div style="text-align: right;padding-right:6px">{{ item.name }}:</div></van-col> -->
                      <van-col :span="item.hasOwnProperty('value2') ? 16 : 24">
                        <van-field
                          v-model="item.value1"
                          placeholder="请输入"
                          :label="item.name"
                        >
                          <template #button v-if="item.unit1!==''">{{
                            item.unit1
                          }}</template></van-field
                        >
                      </van-col>
                      <van-col :span="8" v-if="item.hasOwnProperty('value2')">
                        <div style="padding-left:5px">
                           <van-field
                          v-if="item.hasOwnProperty('value2')"
                          v-model="item.value2"
                          placeholder="请输入"
                        >
                          <template #button v-if="item.unit2!==''">{{
                            item.unit2
                          }}</template></van-field>
                        </div>
                      </van-col>
                    </van-row>

                    </div>
                  </van-col>

                </van-row>
              </van-tab>
            </van-tabs>


            <van-field
              v-model="czobj.images[0]"
              name="处置前照片"
              label="处置前照片"
            >
               <template #input>
                <ImageUpload v-model="czobj.images[0]"></ImageUpload>
               </template>

            </van-field>
             <van-field
              v-model="czobj.images[1]"
              name="处置中照片"
              label="处置中照片"
            >
               <template #input>
                <ImageUpload v-model="czobj.images[1]"></ImageUpload>
               </template>

            </van-field>
             <van-field
              v-model="czobj.images[2]"
              name="处置后照片"
              label="处置后照片"
            >
               <template #input>
                <ImageUpload v-model="czobj.images[2]"></ImageUpload>
               </template>

            </van-field>
            <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-cell-group>

          <div style="margin: 16px">
            <van-button round block type="primary" native-type="submit">
              提交
            </van-button>
          </div>
        </van-form>
      </div>
    </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 { useDict } from "@/utils/dict";
import { useRoute } from "vue-router";
import MapSelect from "@/components/MapSelect";
import moment from "moment";
import ImageUpload from "@/components/ImageUpload";
import FileUpload from "@/components/FileUpload";
import {
  listTask,
  getTask,
  delTask,
  addTask,
  updateTask,
  distributedTask,
  closeTask,
  czTask,
  gzTask,
  hcTask,
  ddTask,
} from "@/api/system/task";

import { Toast } from "vant";
import router from "../../../../router";
import {
  changeUserStatus,
  listUser,
  resetUserPwd,
  delUser,
  getUser,
  updateUser,
  addUser,
} from "@/api/system/user";

const {
  sys_area,
  task_work,
  task_car,
  task_consumables,
} = useDict(
  "sys_area",
  "task_work",
  "task_car",
  "task_consumables"
);


const activeName = "1";
const route = useRoute();

const bhobj = ref({ resonRemark: [], files: "", images: [] });

const czobj = ref({
  qsdes: "",
  images: ["","",""],
  gzldata: [],
  clsbdata: [],
  hcdata: [],
});

var task = localStorage.getItem("currenttask");
try {
  if (task) {
    task = JSON.parse(task);
    if (task.taskId != Number(route.query.id)) {
      Toast.fail("未查到任务");
      router.back();
    }
    var logs = (task.tblTaskLogList ?? []).filter((i) => i.taskStatus == 2);
    if (Array.isArray(logs) && logs.length > 0) {
      var log = JSON.parse(logs[0].logDes);
      czobj.value = log;
      if (Array.isArray(log.images)) {
        if (log.images.length < 3) {
          czobj.value.images = log.images.concat(["", "", ""]);
        } else {
          czobj.value.images = log.images;
        }
      } else {
         czobj.value.images = ["", "", ""]
      }
      if (!czobj.value.hasOwnProperty('gzldata')) {
        czobj.value.gzldata = [];
      }
      if (!czobj.value.hasOwnProperty('clsbdata')) {
        czobj.value.clsbdata = [];
      }
      if (!czobj.value.hasOwnProperty('hcdata')) {
        czobj.value.hcdata = [];
      }

    }
  } else {
    Toast.fail("未查到任务");
    router.back();
  }
} catch (E) {}

const bodyheight = ref(0);
const gettaskitemlogdes = (item, status) => {
   var templist = {};
    var list = item.tblTaskLogList;
    for (var i in list) {
      var log = list[i];
      if (templist.hasOwnProperty(log.taskStatus + "")) {
        if (
          moment(templist[log.taskStatus + ""].createTime).unix() -
            moment(log.createTime).unix() <
          0
        ) {
          templist[log.taskStatus + ""] = log;
        }
      } else {
        templist[log.taskStatus + ""] = log;
      }
    }
    var lists = [];
    for (var i in templist) {
      lists.push(templist[i]);
    }
  if (templist[status + ""] == null || templist[status + ""] == undefined || templist[status + ""] == "") return null;
  return JSON.parse(templist[status + ""].logDes);
}

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

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

const taskinfo = ref({
  taskId: Number(route.query.id),
  taskAddr: task.taskAddr,
  taskLocation: task.taskLocation,
  taskArea: task.taskArea,
});

const mapSelect = ref(null);
const formlocation = ref({ addr: "", locations: "" });
if (route.query.bh != "1") {
  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;
                }
              }
            }
          }
        );
      }
    }
  );
}


const xyobj = ref({
  bzxytime: "",
  ddxctime: "",
  czwctime: "",
  zysc: "",
  clsc: "",
  zyfzr: "",
  zyrs: 0,
  carxh: "",
  carnumber: "",
  gls: "",
});
const onSubmitbh = async () => {

  const TaskClose = () => {
    closeTask({
      taskId: route.params.id,
      logDes: JSON.stringify(bhobj.value),
    }).then(async (res) => {
      var logc = gettaskitemlogdes(taskinfo.value, -1);
      if (logc !=null) {
       xyobj.value = logc;
      }
     xyobj.value.czwctime = moment().format("YYYY-MM-DD HH:mm:ss");
     await ddTask({
      taskId: item.taskId,
      taskStatus: -1,
      logDes: JSON.stringify(xyobj.value)
     })
      Toast.success("成功");
      router.back();
    });
  };
};

watch(
  [() => xyobj.value.bzxytime, xyobj.value.ddxctime, xyobj.value.czwctime],
  () => {
    if (xyobj.value.bzxytime != "" && xyobj.value.czwctime != "") {
      xyobj.value.clsc =
        (
          (moment(xyobj.value.czwctime).unix() -
            moment(xyobj.value.bzxytime).unix()) /
          3600.0
        ).toFixed(2) + "";
    }
    if (xyobj.value.ddxctime != "" && xyobj.value.czwctime != "") {
      xyobj.value.zysc =
        (
          (moment(xyobj.value.czwctime).unix() -
            moment(xyobj.value.ddxctime).unix()) /
          3600.0
        ).toFixed(2) + "";
    }
  }
);

const onSubmit = async () => {
  ddTask({
    taskId: Number(route.query.id),
    taskStatus: 2,
    logDes: JSON.stringify(czobj.value),
  }).then(async (res) => {
    await updateTask(taskinfo.value);
    await ddTask({
      taskId: item.taskId,
      taskStatus: -1,
      logDes: JSON.stringify(xyobj.value)
     })
      Toast.success("成功");
      router.back();

  });
};

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

watch(() => task_work.value, () => {
  task_work.value.map((i) => {
      i.remark = i.remark == undefined || i.remark == null ? '' : i.remark;
      var data = { name: i.label, unit1: i.remark };
      if ((i.remark ?? "").split(",").length > 1) {
        data["value1"] = '';
        data["value2"] = '';
        data["unit1"] = (i.remark ?? "").split(",")[0];
        data["unit2"] = (i.remark ?? "").split(",")[1];
      } else {
        data["value1"] = '';
      }
      var temp = czobj.value.gzldata.find((p) => {
        return p.name == data.name;
      });
      if (temp == undefined) {
        czobj.value.gzldata.push(data);
      }
      });
})

watch(() => task_car.value, () => {
  task_car.value.map((i) => {
      i.remark = i.remark == undefined || i.remark == null ? '' : i.remark;
      var data = { name: i.label, unit1: i.remark };
      if ((i.remark ?? "").split(",").length > 1) {
        data["value1"] = '';
        data["value2"] = '';
        data["unit1"] = (i.remark ?? "").split(",")[0];
        data["unit2"] = (i.remark ?? "").split(",")[1];
      } else {
        data["value1"] = '';
      }
      var temp = czobj.value.clsbdata.find((p) => {
        return p.name == data.name;
      });
      if (temp == undefined) {
        czobj.value.clsbdata.push(data);
      }
      });
})

watch(() => task_consumables.value, () => {
  task_consumables.value.map((i) => {
      i.remark = i.remark == undefined || i.remark == null ? '' : i.remark;
      var data = { name: i.label, unit1: i.remark };
      if ((i.remark ?? "").split(",").length > 1) {
        data["value1"] = '';
        data["value2"] = '';
        data["unit1"] = (i.remark ?? "").split(",")[0];
        data["unit2"] = (i.remark ?? "").split(",")[1];
      } else {
        data["value1"] = '';
      }
      var temp = czobj.value.hcdata.find((p) => {
        return p.name == data.name;
      });
      if (temp == undefined) {
        czobj.value.hcdata.push(data);
      }
      });
})

onMounted(() => {
  formlocation.value.addr = taskinfo.value.taskAddr;
  formlocation.value.locations = taskinfo.value.taskLocation;
});
</script>

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