<template>
  <div class="tenant">
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        :selectConfig="selectConfig"
        highlight-current-row
        :action-list="[
          {
            text: '添加任务',
            action: () => openModal('add'),
          },
        ]"
        @get-list="getList"
      >
        <template #title="{ item }">
          <div>
            <span style="color: #409eff">{{ item.title }}</span>
          </div>
        </template>
        <template #file="{ item }">
          <div>
            <span
              style="color: #409eff; cursor: pointer"
              @click="clickFile(item.id)"
              >{{ item.fileName }}</span
            >
          </div>
        </template>
      </byTable>
    </div>

    <el-dialog
      :title="modalType == 'add' ? '添加任务' : '编辑任务'"
      v-if="dialogVisible"
      v-model="dialogVisible"
      width="600"
      v-loading="loadingDialog"
    >
      <byForm
        :formConfig="formConfig"
        :formOption="formOption"
        v-model="formData.data"
        :rules="rules"
        ref="submit"
      >
        <template #importanceLv>
          <div>
            <el-radio-group v-model="formData.data.importanceLv">
              <el-radio
                v-for="item in importanceLv"
                :key="item.value"
                :label="item.value"
                border
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </div>
        </template>
        <template #urgencyLv>
          <div>
            <el-radio-group v-model="formData.data.urgencyLv">
              <el-radio
                v-for="item in urgencyLv"
                :key="item.value"
                :label="item.value"
                border
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </div>
        </template>
        <template #dueDate>
          <div>
            <el-date-picker
              v-model="formData.data.dueDate"
              type="date"
              placeholder="请选择完成期限"
              value-format="YYYY-MM-DD"
            />
          </div>
        </template>
        <template #fileList>
          <div style="width: 100%">
            <el-upload
              v-model:fileList="fileList"
              action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
              :data="uploadData"
              :limit="1"
              :before-upload="uploadFile"
              :on-preview="onPreviewFile"
            >
              <el-button>选择</el-button>
            </el-upload>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitForm()" size="large"
          >确 定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref } from "vue";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import useUserStore from "@/store/modules/user";
import { ElMessage, ElMessageBox } from "element-plus";

const { proxy } = getCurrentInstance();
const userList = ref([]);
const status = ref([
  {
    label: "未完成",
    value: "0",
  },
  {
    label: "已完成",
    value: "1",
  },
]);
const source = ref([]);
const importanceLv = ref([
  {
    label: "重要",
    value: 1,
  },
  {
    label: "不重要",
    value: 0,
  },
]);
const urgencyLv = ref([
  {
    label: "紧急",
    value: 1,
  },
  {
    label: "不紧急",
    value: 0,
  },
]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
    source: "",
    status: "",
  },
});
const loading = ref(false);
const selectConfig = computed(() => {
  return [
    {
      label: "任务来源",
      prop: "source",
      data: source.value,
    },
    {
      label: "状态",
      prop: "status",
      data: status.value,
    },
  ];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "任务来源",
        prop: "source",
        width: 140,
      },
      render(type) {
        let text = "";
        if (source.value && source.value.length > 0) {
          let data = source.value.filter((item) => item.value == type);
          if (data && data.length > 0) {
            text = data[0].label;
          }
        }
        return text;
      },
    },
    {
      attrs: {
        label: "任务标题",
        slot: "title",
        width: 260,
      },
    },
    {
      attrs: {
        label: "紧急程度",
        prop: "urgencyLv",
        width: 140,
      },
      render(type) {
        let text = "";
        if (urgencyLv.value && urgencyLv.value.length > 0) {
          let data = urgencyLv.value.filter((item) => item.value == type);
          if (data && data.length > 0) {
            text = data[0].label;
          }
        }
        return text;
      },
    },
    {
      attrs: {
        label: "重要程度",
        prop: "importanceLv",
        width: 140,
      },
      render(type) {
        let text = "";
        if (importanceLv.value && importanceLv.value.length > 0) {
          let data = importanceLv.value.filter((item) => item.value == type);
          if (data && data.length > 0) {
            text = data[0].label;
          }
        }
        return text;
      },
    },
    {
      attrs: {
        label: "完成期限",
        prop: "dueDate",
        width: 120,
      },
    },
    {
      attrs: {
        label: "发布人",
        prop: "createUser",
        width: 120,
      },
      render(type) {
        let text = "";
        if (userList.value && userList.value.length > 0) {
          let data = userList.value.filter((item) => item.value == type);
          if (data && data.length > 0) {
            text = data[0].label;
          }
        }
        return text;
      },
    },
    {
      attrs: {
        label: "发布时间",
        prop: "createTime",
        width: 160,
      },
    },
    {
      attrs: {
        label: "负责人",
        prop: "personLiableName",
        width: 120,
      },
    },
    {
      attrs: {
        label: "附件",
        slot: "file",
      },
    },
    {
      attrs: {
        label: "状态",
        prop: "status",
        width: 120,
      },
      render(type) {
        return type == 1 ? "已完成" : type == 0 ? "未完成" : "";
      },
    },
    {
      attrs: {
        label: "操作",
        width: "120",
        align: "center",
      },
      renderHTML(row) {
        return [
          row.source === 1
            ? {
                attrs: {
                  label: "完成",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  accomplish(row);
                },
              }
            : {},
          row.source === 1
            ? {
                attrs: {
                  label: "取消",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  ElMessageBox.confirm(
                    "此操作将永久取消该数据, 是否继续?",
                    "提示",
                    {
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                      type: "warning",
                    }
                  ).then(() => {
                    proxy
                      .post("/workTasks/delete", {
                        id: row.id,
                      })
                      .then(() => {
                        ElMessage({
                          message: "取消成功",
                          type: "success",
                        });
                        getList();
                      });
                  });
                },
              }
            : {},
        ];
      },
    },
  ];
});
const getDict = () => {
  proxy
    .post("/dictTenantData/page", {
      pageNum: 1,
      pageSize: 999,
      dictCode: "work_order_source",
      tenantId: useUserStore().user.tenantId,
    })
    .then((res) => {
      if (res.rows && res.rows.length > 0) {
        source.value = res.rows.map((item) => {
          return {
            label: item.dictValue,
            value: item.dictKey,
          };
        });
      }
    });
  proxy
    .get("/tenantUser/list", {
      pageNum: 1,
      pageSize: 10000,
      tenantId: useUserStore().user.tenantId,
    })
    .then((res) => {
      userList.value = res.rows.map((item) => {
        return {
          label: item.nickName,
          value: item.userId,
        };
      });
    });
};
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/workTasks/page", sourceList.value.pagination).then((res) => {
    sourceList.value.data = res.rows;
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
getDict();
getList();
const modalType = ref("add");
const dialogVisible = ref(false);
const loadingDialog = ref(false);
const submit = ref(null);
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const formConfig = computed(() => {
  return [
    {
      type: "input",
      prop: "title",
      label: "任务标题",
      itemType: "text",
    },
    {
      type: "slot",
      prop: "importanceLv",
      slotName: "importanceLv",
      label: "重要程度",
    },
    {
      type: "slot",
      prop: "urgencyLv",
      slotName: "urgencyLv",
      label: "紧急程度",
    },
    {
      type: "slot",
      prop: "dueDate",
      slotName: "dueDate",
      label: "完成期限",
    },
    {
      type: "select",
      prop: "personLiableId",
      label: "负责人",
      data: userList.value,
    },
    {
      type: "input",
      prop: "remarks",
      label: "任务说明",
      itemType: "textarea",
    },
    {
      type: "slot",
      prop: "fileList",
      slotName: "fileList",
      label: "上传附件",
    },
  ];
});
const rules = ref({
  title: [{ required: true, message: "请输入任务标题", trigger: "blur" }],
  importanceLv: [
    { required: true, message: "请选择重要程度", trigger: "change" },
  ],
  urgencyLv: [{ required: true, message: "请选择紧急程度", trigger: "change" }],
  dueDate: [
    { required: true, message: "请选择完成期限", trigger: ["change", "blur"] },
  ],
  personLiableId: [
    { required: true, message: "请选择负责人", trigger: "change" },
  ],
});
const fileList = ref([]);
const uploadData = ref({});
const formData = reactive({
  data: {},
});
const openModal = (val) => {
  modalType.value = val;
  formData.data = {};
  loadingDialog.value = false;
  dialogVisible.value = true;
};
const uploadFile = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadData.value = res.uploadBody;
  file.id = res.id;
  file.fileName = res.fileName;
  file.fileUrl = res.fileUrl;
  return true;
};
const onPreviewFile = (file) => {
  window.open(file.raw.fileUrl, "_blank");
};
const submitForm = () => {
  submit.value.handleSubmit(() => {
    loadingDialog.value = true;
    if (fileList.value && fileList.value.length > 0) {
      formData.data.fileList = fileList.value.map((item) => {
        return {
          id: item.raw.id,
          fileName: item.raw.fileName,
        };
      });
    }
    proxy.post("/workTasks/" + modalType.value, formData.data).then(
      () => {
        ElMessage({
          message: modalType.value == "add" ? "添加成功" : "编辑成功",
          type: "success",
        });
        dialogVisible.value = false;
        getList();
      },
      (err) => {
        console.log(err);
        loadingDialog.value = false;
      }
    );
  });
};
const accomplish = (row) => {
  proxy.post("/workTasks/edit", { id: row.id, status: 1 }).then((res) => {
    ElMessage({
      message: "任务完成",
      type: "success",
    });
    getList();
  });
};
const clickFile = (ID) => {
  proxy.post("/fileInfo/getList", { businessIdList: [ID] }).then((res) => {
    window.open(res[ID][0].fileUrl, "_blank");
  });
};
// const update = (row) => {
//   modalType.value = "edit";
//   loadingDialog.value = true;
//   proxy.post("/workTasks/detail", { id: row.id }).then((res) => {
//     formData.data = res;
//     loadingDialog.value = false;
//   });
//   dialogVisible.value = true;
// };
</script>

<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
