<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"
              @click="onSubmitbh"
            >
              提交
            </van-button>
          </div>
        </van-form>
      </div>
      <div v-if="route.query.bh != '1'">
        <van-form>
          <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" style="background:#8080800d">
                <van-row >
                  <van-col :span="24" v-for="item in czobj.zcdata">
                    <van-cell-group inset style="margin-top: 10px;">
                      <van-field
                        v-model="item.type"
                        is-link
                        readonly
                        name="picker"
                        label="类型"
                        placeholder="点击选择类型"
                        @click="showpicker = true"
                      />
                      <van-popup v-model:show="showpicker" position="bottom">
                        <van-picker
                          :columns="
                            zctype.map((i) => {
                              return { text: i.label, value: i.label };
                            })
                          "
                          @confirm="
                            ( selectedOptions ) => {
                              item.type = selectedOptions.text;
                              showpicker = false;
                            }
                          "
                          @cancel="showpicker = false"
                        />
                      </van-popup>
                       <van-field
                        v-model="item.cz"
                        is-link
                        readonly
                        name="picker"
                        label="材质"
                        placeholder="点击选择材质"
                        @click="showpicker1 = true"
                      />
                      <van-popup v-model:show="showpicker1" position="bottom">
                        <van-picker
                          :columns="
                            zccz.map((i) => {
                              return { text: i.label, value: i.label };
                            })
                          "
                          @confirm="
                            ( selectedOptions ) => {
                              item.cz = selectedOptions.text;
                               showpicker1 = false;
                            }
                          "
                          @cancel="showpicker1 = false"
                        />
                      </van-popup>
                       <van-field
                        v-model="item.gg"
                        is-link
                        readonly
                        name="picker"
                        label="规格"
                        placeholder="点击选择规格"
                        @click="showpicker2 = true"
                      />
                      <van-popup v-model:show="showpicker2" position="bottom">
                        <van-picker
                          :columns="
                            zcgg.map((i) => {
                              return { text: i.label, value: i.label };
                            })
                          "
                          @confirm="
                            ( selectedOptions ) => {
                              item.gg = selectedOptions.text;
                                showpicker2 = false;
                            }
                          "
                          @cancel="showpicker2 = false"
                        />
                      </van-popup>
                       <van-field v-model="item.num" type="number" label="数量" />
                       <van-field
                        v-model="item.dw"
                        is-link
                        readonly
                        name="picker"
                        label="单位"
                        placeholder="点击选择单位"
                        @click="showpicker3 = true"
                      />
                      <van-popup v-model:show="showpicker3" position="bottom">
                        <van-picker
                          :columns="
                            zcdw.map((i) => {
                              return { text: i.label, value: i.label };
                            })
                          "
                          @confirm="
                            ( selectedOptions ) => {
                              item.dw= selectedOptions.text;
                               showpicker3 = false;
                            }
                          "
                          @cancel="showpicker3 = false"
                        />
                      </van-popup>
                    </van-cell-group>

                  </van-col>

                  <van-col :span="24" style="text-align: center;">
                    <van-button
                      round
                      block
                      type="primary"
                      style="margin-top: 10px;"
                      size="small"
                      @click="
                        czobj.zcdata.push({
                          index: czobj.zcdata.length,
                          label: '',
                          value: '',
                        })
                      "
                    >
                      新增
                    </van-button>
                  </van-col>
                </van-row>
              </van-tab>
              <van-tab title="辅材" name="4">
                <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="czobj.images[3]" name="处置后远景照片" label="处置后远景照片">
              <template #input>
                <ImageUpload v-model="czobj.images[3]"></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-row>
              <van-col :span="12">
                <div style="padding-right: 5px">
                  <van-button round block type="primary" @click="onSubmit">
                    暂存
                  </van-button>
                </div>
              </van-col>
              <van-col :span="12">
                <div style="padding-left: 5px">
                  <van-button round block type="primary" @click="onSubmit1">
                    处置完成
                  </van-button>
                </div>
              </van-col>
            </van-row>
          </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,
  zctype,
  zccz,
  zcdw,
  zcgg,
} = useDict(
  "sys_area",
  "task_work",
  "task_car",
  "task_consumables",
  "zctype",
  "zccz",
  "zcdw",
  "zcgg"
);

const activeName = "1";
const route = useRoute();
const showpicker = ref(false);
const showpicker1 = ref(false);
const showpicker2 = ref(false);
const showpicker3 = ref(false);

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

const czobj = ref({
  qsdes: "",
  images: ["", "", "",""],
  gzldata: [],
  clsbdata: [],
  hcdata: [],
  zcdata: [],
});
const xyobj = ref({
  bzxytime: "",
  ddxctime: "",
  czwctime: "",
  zysc: "",
  clsc: "",
  zyfzr: "",
  zyrs: 0,
  carxh: "",
  carnumber: "",
  gls: "",
});

var task = localStorage.getItem("currenttask");

try {
  if (task) {
    task = JSON.parse(task);

    if (task.taskId != Number(route.query.id)) {
      Toast.fail("未查到任务");
      router.back();
    }
    var templist = {};
    var list = task.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]);
    }
    task.tblTaskLogList = lists;

    var logs1 = (task.tblTaskLogList ?? []).filter((i) => i.taskStatus == -1);

    if (Array.isArray(logs1) && logs1.length > 0) {
      var log = JSON.parse(logs1[0].logDes);
      if (log.bzxytime) log.bzxytime = moment(log.bzxytime)._d;
      if (log.ddxctime) log.ddxctime = moment(log.ddxctime)._d;
      if (log.czwctime) log.czwctime = moment(log.czwctime)._d;
      xyobj.value = log;
    }

    var logs = (task.tblTaskLogList ?? []).filter((i) => i.taskStatus == 3);

    if (Array.isArray(logs) && logs.length > 0) {
      var log = JSON.parse(logs[0].logDes);
      czobj.value = log;
      console.log(log);
      if (Array.isArray(log.images)) {
        if (log.images.length < 3) {
          czobj.value.images = log.images.concat(["", "", "",""]);
        } else {
          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 = [];
      }
      if (!czobj.value.hasOwnProperty("zcdata")) {
        czobj.value.zcdata = [];
      }
    }
  } 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 onSubmitbh = async () => {
  Toast.loading({
    message: "加载中...",
    forbidClick: true,
  });
  closeTask({
    taskId: Number(route.query.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: Number(route.query.id),
      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 () => {
  Toast.loading({
    message: "加载中...",
    forbidClick: true,
  });
  ddTask({
    taskId: Number(route.query.id),
    taskStatus: 3,
    logDes: JSON.stringify(czobj.value),
  }).then(async (res) => {
    await updateTask(taskinfo.value);
    await ddTask({
      taskId: Number(route.query.id),
      taskStatus: -1,
      logDes: JSON.stringify(xyobj.value),
    });
    Toast.clear();
    Toast.success("成功");
    router.back();
  });
};

const onSubmit1 = async () => {
  Toast.loading({
    message: "加载中...",
    forbidClick: true,
  });
  await updateTask(taskinfo.value);
  await ddTask({
    taskId: Number(route.query.id),
    taskStatus: -1,
    logDes: JSON.stringify(xyobj.value),
  });
  czTask({
    taskId: Number(route.query.id),
    logDes: JSON.stringify(czobj.value),
  }).then((res) => {
    Toast.clear();
    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>
