<template>
  <div class="app-container">
    <customForm ref="formRef" :model="queryParams" :config="FormConfig">
      <template #region>
        <el-tree-select
          v-model="queryParams.decideType"
          :data="deptList"
          :props="{
            value: 'id',
            label: 'label',
            children: 'children',
          }"
          value-key="id"
          default-expanded-keys
          check-strictly
          style="width: 200px"
        />
      </template>
      <template #monTime>
        <el-date-picker
          v-model="queryParams.time"
          type="daterange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        />
      </template>
      <template #tbmj>
        <!-- clearable -->
        <el-select
          v-model="queryParams.dkmjbs"
          style="width: 100px; margin-right: 10px"
        >
          <el-option
            v-for="item in num_compare"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-input
          v-model="queryParams.dkmj"
          style="width: calc(100% - 120px)"
          placeholder="数据"
        />
      </template>
      <template #action>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </template>
    </customForm>
    <div class="pointlist" @click="handleBrowse({})"></div>
    <numCard
      :sddata="countData"
      :sdlist="sdlist[route.query.type]"
      @numclick="cardclick"
    ></numCard>

    <tablePage
      class="tablePage"
      v-loading="loading"
      :cloumn="TableHeader"
      :table="{ total, data: dkjbxxList }"
      :indexed="false"
      :check="true"
      ref="tableDialogRef"
      v-model:pageNum="queryParams.pageNum"
      v-model:pageSize="queryParams.pageSize"
      @selectChange="handleSelectionChange"
      @currentChange="getList"
    >
      <template #action="{ row, $index }">
        <el-button link type="primary" @click="handleBrowse(row, $index)"
          >查看
        </el-button>
        <el-button
          v-if="row.status == '0'"
          link
          type="primary"
          @click="Issued(row)"
          >下发
        </el-button>
      </template>
    </tablePage>
    <div class="bottom">
      <div class="selected">已选{{ ids.length }}条</div>
      <el-button
        v-if="route.path == '/checkLand'"
        type="primary"
        @click="fieldwork(true)"
      >
        分发至外业
      </el-button>
      <el-button
        v-if="route.path == '/checkLand'"
        type="primary"
        @click="fieldwork(false)"
      >
        取消外业任务
      </el-button>
      <el-button @click="handleDownload">下载</el-button>
    </div>

    <!-- 添加或修改地块基本信息（DKJBXX）对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="dkjbxxRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="监测编号：" prop="dkjdxxIds">
          {{ form.dkjdxxIds.join(";") }}
        </el-form-item>
        <el-form-item label="截止时间：" prop="endTime" v-if="isfield">
          <el-date-picker
            v-model="form.endTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择截止时间"
          />
        </el-form-item>
        <el-form-item label="核查人员：" prop="fieldworkId" v-if="isfield">
          <el-select
            v-model="form.fieldworkId"
            placeholder="请选择"
          >
            <el-option
              v-for="dict in roles"
              :key="dict.userId"
              :label="dict.nickName"
              :value="dict.userId"
            ></el-option>
          </el-select>
         
        </el-form-item>
        <el-form-item label="举证说明：" prop="notes">
          <el-input
            v-model="form.notes"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        {{ isfield ? "说明：对于已分发的图斑系统将自动跳过，不再分发。" : "" }}
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script setup name="Dkjbxx">
import { userDept } from "@/api/system/dept";
import {
  getDkcount,
  listDkjbxx,
  field,
  removeField,
  getRoles
} from "@/api/rsmonitoring/dkjbxx";
import numCard from "@/components/numCard";
import { FormConfig, TableHeader } from "./config";
const { proxy } = getCurrentInstance();
const { num_compare } = proxy.useDict("num_compare");
const route = useRoute();
const router = useRouter();

const dkjbxxList = ref([]);
const open = ref(false);
const loading = ref(true);
const ids = ref([]);
const total = ref(0);
const isfield = ref(true);
const title = ref("");

const data = reactive({
  deptList: [],
  form: {},
  roles: [],
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    time: ["", ""],
    startTime: "",
    endTime: "",
    auditflowList: [],
    dkmjbs: "",
    dkmj: "",
    descValue: "dkmj",
    dkbh: "",
    xzqdm: null,
  },
  countData: {},
  sdlist: {
    normal: [
      { name: "核查图斑", pro: "all", ctype: "blue" },
      {
        name: "未分发图斑",
        pro: "WYFF",
        // children: [{ name: "未分发图斑", pro: "155" }],
      },
      { name: "举证中图斑", pro: "WYDC" },
      { name: "已举证图斑", pro: "WYTJ" },
      { name: "外业退回图斑", pro: "WYQR", ctype: "red" },
      { name: "县级审核退回图斑", pro: "XJTJ", ctype: "red" },
    ],
    XJ: [
      { name: "待审核", pro: "XJDSH" },
      { name: "已审核", pro: "XJYSH" },
      { name: "已提交", pro: "XJYTJ" },
      { name: "市级退回图斑", pro: "SJTH", ctype: "red" },
      { name: "省级退回图斑", pro: "SJJTH", ctype: "red" },
    ],
    SJ: [
      { name: "待审核", pro: "SJDSH" },
      { name: "已审核", pro: "SJYSH" },
      { name: "已提交", pro: "SJYTJ" },
      { name: "省级退回图斑", pro: "SJJTH", ctype: "red" },
    ],
    SJJ: [
      { name: "待审核", pro: "SJJDSH" },
      { name: "已审核", pro: "SJJYSH" },
    ],
  },
});

const { queryParams, deptList, form, roles,rules, sdlist, countData } = toRefs(data);
let countparm = {
  normal: {
    all: null,
    WYFF: [{ auditflowStep: "WYFF" }],
    WYDC: [{ auditflowStep: "WYDC" }],
    WYTJ: [{ auditflowStep: "WYTJ" }],
    XJSH: [{ auditflowStep: "WYQR", successType: "1" }],
    XJTJ: [{ auditflowStep: "XJTJ", successType: "1" }],
  },
  XJ: {
    XJDSH: [
      { auditflowStep: "XJHGX" },
      { auditflowStep: "XJSH" },
      { auditflowStep: "WYTJ", successType: "0" },
    ],
    XJYSH: [{ auditflowStep: "XJSH" }],
    XJYTJ: [{ auditflowStep: "XJTJ" }],
    SJTH: [{ auditflowStep: "SJTJ", successType: "1" }],
    SJJTH: [{ auditflowStep: "SJJTJ", successType: "1" }],
  },
  SJ: {
    SJDSH: [
      { auditflowStep: "SJSH" },
      { auditflowStep: "XJTJ", successType: "0" },
    ],
    SJYSH: [{ auditflowStep: "SJSH" }],
    SJYTJ: [{ auditflowStep: "SJTJ" }],
    SJJTH: [{ auditflowStep: "SJJTJ", successType: "1" }],
  },
  SJJ: {
    SJJDSH: [
      { auditflowStep: "SJJSH" },
      { auditflowStep: "SJTJ", successType: "0" },
    ],
    SJJYSH: [{ auditflowStep: "SJJSH" }],
  },
};
/** 查询地块基本信息（DKJBXX）列表 */
function getList() {
  loading.value = true;
  queryParams.value.startTime = queryParams.value.time[0];
  queryParams.value.endTime = queryParams.value.time[1];
  listDkjbxx(queryParams.value).then((response) => {
    dkjbxxList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
function getcount() {
  countData.value = {};
  let prams = countparm[route.query.type || "normal"];
  Object.keys(prams).forEach((key) => {
    getDkcount({
      startTime: "",
      endTime: "",
      auditflowList: prams[key],
    }).then((res) => {
      countData.value[`${key}num`] = res.data.countNumber;
      countData.value[`${key}mj`] = res.data.countSum;
    });
  });
}
function cardclick(key) {
  let prams = countparm[route.query.type || "normal"];
  queryParams.value.auditflowList = prams[key];
  getList();
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    dkjdxxIds: [],
    stepState: "",
    endTime: "",
    fieldworkId: "",
    fieldworkBy: "",
    notes: "",
    createBy: "测试",
    auditflowStep: "WYQR",
  };
  proxy.resetForm("dkjbxxRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    time: ["", ""],
    startTime: "",
    endTime: "",
    auditflowList: [],
    dkmjbs: "",
    dkmj: "",
    descValue: "dkmj",
    dkbh: "",
    xzqdm: null,
  };
  // proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
}
/** 新增按钮操作 */
function fieldwork(field) {
  if (!ids.value.length) {
    proxy.$modal.msgError("请选择地块图斑");
    return;
  }
  isfield.value = field;
  reset();
  form.value.dkjdxxIds = ids.value;
  open.value = true;
  title.value = field ? "分发至外业" : "取消分发外业任务";
  if (field) {
    form.value.fieldworkId = "";
    form.value.fieldworkBy = "zhang";
  }
  form.value.auditflowStep = field ? "WYFF" : "WYQR";
  getRoles().then((response) => {
    roles.value = response.data;
    console.log( response,'---- response.')
  });
}
function rolesChaneg(params) {
  form.value.fieldworkBy = "";
}

/** 提交按钮 */
function submitForm() {

  proxy.$refs["dkjbxxRef"].validate((valid) => {
    if (valid) {
      if (isfield.value) {
        field(form.value).then((response) => {
          proxy.$modal.msgSuccess("分发成功");
          open.value = false;
          getList();
        });
      } else {
        removeField(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "rsmonitoring/dkjbxx/export",
    {
      ...queryParams.value,
    },
    `dkjbxx_${new Date().getTime()}.xlsx`
  );
}
function handleBrowse(row, index) {
  router.push({
    path: "/remote/gdjc",
    query: { id: row.id, form: "checkLand", dataType: route.query.type, index },
    params: { queryParams: queryParams.value },
  });
}

function handleDownload(row) {
  const zipfile = row.proxypath + ".zip";
  window.open(`${zipfile}`);
}
function getDrpt() {
  userDept({}).then((response) => {
    deptList.value = response.data;
  });
}
getDrpt();
getcount();
getList();
</script>
  <style lang="css" scoped>
.pointlist {
  width: 32px;
  height: 32px;
  margin-left: auto;
  background: url("@/assets/images/pointlist.png") no-repeat center;
  background-size: 100% 100%;
  cursor: pointer;
}
.bottom {
  margin-top: 20px;
  display: flex;
}
.selected {
  width: calc(100% - 250px);
}
</style>