<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: () => newContract(),
          },
        ]"
        @get-list="getList">
        <template #amount="{ item }">
          <div>
            <span style="padding-right: 4px">{{ item.currency }}</span>
            <span>{{ moneyFormat(item.amount, 2) }}</span>
          </div>
        </template>
        <template #claimAmount="{ item }">
          <div>
            <span style="padding-right: 4px">{{ item.currency }}</span>
            <span>{{ moneyFormat(item.claimAmount, 2) }}</span>
          </div>
        </template>
        <template #advanceRatio="{ item }">
          <div>
            <span>{{ item.advanceRatio }}%</span>
          </div>
        </template>
      </byTable>
    </div>

    <el-dialog title="服务记录" v-if="dialogVisible" v-model="dialogVisible" width="800" v-loading="loadingDialog">
      <div style="margin-bottom: 20px">
        <el-button type="primary" @click="clickAddRecord" plain>添加服务记录</el-button>
      </div>
      <el-timeline>
        <el-timeline-item v-for="(item, index) in recordList" :key="index" :timestamp="item.serviceTime" :hide-timestamp="true">
          <div>
            <div style="display: flex; justify-content: space-between; padding-bottom;: 20px">
              <span>{{ item.userName }}</span>
              <span>{{ item.serviceTime }}</span>
            </div>
            <div style="padding-bottom;: 20px">
              <div v-html="item.remark"></div>
            </div>
            <div style="padding-bottom;: 20px" v-if="item.fileList && item.fileList.length > 0">
              <div v-for="(file, index) in item.fileList" :key="index">
                <a style="color: #409eff; cursor: pointer" @click="openFile(file.fileUrl)">{{ file.fileName }}</a>
              </div>
            </div>
          </div>
        </el-timeline-item>
      </el-timeline>
      <div style="padding: 16px; text-align: center">
        <el-button @click="dialogVisible = false" size="large">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="服务记录" v-if="openAddRecord" v-model="openAddRecord" width="700" v-loading="loadingRecord">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
        <template #serviceTime>
          <div>
            <el-date-picker v-model="formData.data.serviceTime" type="datetime" placeholder="请选择服务时间" value-format="YYYY-MM-DD HH:mm:ss" />
          </div>
        </template>
        <template #remark>
          <div style="width: 100%">
            <Editor :value="formData.data.remark" @updateValue="updateContent" />
          </div>
        </template>
        <template #file>
          <div style="width: 100%">
            <el-upload
              v-model:fileList="fileList"
              action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
              :data="uploadData"
              multiple
              :before-upload="uploadFile"
              :on-preview="onPreviewFile">
              <el-button>选择</el-button>
            </el-upload>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="openAddRecord = 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 { ElMessage, ElMessageBox } from "element-plus";
import byForm from "@/components/byForm/index";
import useUserStore from "@/store/modules/user";
import Editor from "@/components/Editor/index.vue";
import path from "path";

const { proxy } = getCurrentInstance();
const corporationList = ref([]);
const customerList = ref([]);
const userList = ref([]);
const status = ref([
  {
    label: "审批中",
    value: 10,
  },
  {
    label: "驳回",
    value: 20,
  },
  {
    label: "审批通过",
    value: 30,
  },
  {
    label: "作废",
    value: 999,
  },
]);
const serviceStatus = ref([
  {
    label: "服务中",
    value: 10,
  },
  {
    label: "已完结",
    value: 20,
  },
]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
    status: "",
    serviceStatus: "",
  },
});
const loading = ref(false);
const selectConfig = computed(() => {
  return [
    {
      label: "审批状态",
      prop: "status",
      data: status.value,
    },
    {
      label: "服务状态",
      prop: "serviceStatus",
      data: serviceStatus.value,
    },
  ];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "归属公司",
        prop: "sellCorporationId",
        "min-width": 220,
      },
      render(type) {
        let text = "";
        if (corporationList.value && corporationList.value.length > 0) {
          let data = corporationList.value.filter((item) => item.value == type);
          if (data && data.length > 0) {
            text = data[0].label;
          }
        }
        return text;
      },
    },
    {
      attrs: {
        label: "合同编码",
        prop: "code",
        width: 180,
      },
    },
    {
      attrs: {
        label: "客户",
        prop: "buyCorporationId",
        "min-width": 220,
      },
      render(type) {
        let text = "";
        if (customerList.value && customerList.value.length > 0) {
          let data = customerList.value.filter((item) => item.value == type);
          if (data && data.length > 0) {
            text = data[0].label;
          }
        }
        return text;
      },
    },
    {
      attrs: {
        label: "版本号",
        prop: "version",
        width: 120,
      },
    },
    {
      attrs: {
        label: "合同金额",
        slot: "amount",
        width: 140,
      },
    },
    {
      attrs: {
        label: "已到账金额",
        slot: "claimAmount",
        width: 140,
      },
    },
    {
      attrs: {
        label: "业务员",
        prop: "userName",
        width: 140,
      },
    },
    {
      attrs: {
        label: "创建时间",
        prop: "createTime",
        width: 160,
      },
    },
    {
      attrs: {
        label: "审批状态",
        prop: "status",
        width: 140,
      },
      render(type) {
        let text = "";
        if (status.value && status.value.length > 0) {
          let data = status.value.filter((item) => item.value == type);
          if (data && data.length > 0) {
            text = data[0].label;
          }
        }
        return text;
      },
    },
    {
      attrs: {
        label: "到款状态",
        prop: "serviceStatus",
        width: 140,
      },
      render(type) {
        let text = "";
        if (serviceStatus.value && serviceStatus.value.length > 0) {
          let data = serviceStatus.value.filter((item) => item.value == type);
          if (data && data.length > 0) {
            text = data[0].label;
          }
        }
        return text;
      },
    },
    {
      attrs: {
        label: "操作",
        width: "140",
        align: "center",
        fixed: "right",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "作废",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              ElMessageBox.confirm("此操作将永久删除该数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }).then(() => {
                proxy
                  .post("/serviceContract/cancel", {
                    id: row.id,
                    status: 88,
                  })
                  .then(() => {
                    ElMessage({
                      message: "作废成功",
                      type: "success",
                    });
                    getList();
                  });
              });
            },
          },
          {
            attrs: {
              label: "服务记录",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              clickRecord(row);
            },
          },
        ];
      },
    },
  ];
});
const getDict = () => {
  proxy.post("/corporation/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    corporationList.value = res.rows.map((item) => {
      return {
        ...item,
        label: item.name,
        value: item.id,
      };
    });
  });
  proxy.post("/customer/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    customerList.value = res.rows.map((item) => {
      return {
        ...item,
        label: item.name,
        value: item.id,
      };
    });
  });
  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("/serviceContract/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 newContract = () => {
  proxy.$router.replace({
    path: "/platform_manage/process/processApproval",
    query: {
      flowKey: "service_contract_flow",
      flowName: "服务合同审批流程",
    },
  });
};
const submit = ref(null);
const dialogVisible = ref(false);
const loadingDialog = ref(false);
const openAddRecord = ref(false);
const recordList = ref([]);
const getRecordList = () => {
  proxy.post("/serviceContractRecord/page", { serviceContractId: formData.data.serviceContractId }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      recordList.value = res.rows;
      let fileIds = res.rows.map((item) => {
        return item.id;
      });
      proxy.post("/fileInfo/getList", { businessIdList: fileIds }).then((resFile) => {
        recordList.value = recordList.value.map((item) => {
          let fileData = [];
          if (resFile[item.id] && resFile[item.id].length > 0) {
            fileData = resFile[item.id];
            // .map((item) => {
            //   return {
            //     raw: item,
            //     name: item.fileName,
            //     url: item.fileUrl,
            //   };
            // });
          }
          return {
            ...item,
            fileList: fileData,
          };
        });
        console.log(recordList.value);
      });
    } else {
      recordList.value = [];
    }
    loadingDialog.value = false;
  });
};
const clickRecord = (item) => {
  formData.data.serviceContractId = item.id;
  loadingDialog.value = true;
  dialogVisible.value = true;
  getRecordList();
};
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const formData = reactive({
  data: {
    serviceContractId: "",
    remark: "",
    fileList: [],
  },
});
const formConfig = computed(() => {
  return [
    {
      label: "账户信息",
    },
    {
      type: "select",
      prop: "userId",
      label: "服务人员",
      data: userList.value,
    },
    {
      type: "slot",
      prop: "serviceTime",
      slotName: "serviceTime",
      label: "服务时间",
    },
    {
      type: "select",
      prop: "status",
      label: "服务状态",
      data: serviceStatus.value,
    },
    {
      type: "slot",
      prop: "remark",
      slotName: "remark",
      label: "服务记录",
    },
    {
      type: "slot",
      prop: "file",
      slotName: "file",
      label: "上传附件",
    },
  ];
});
const rules = ref({
  userId: [{ required: true, message: "请选择服务人员", trigger: "change" }],
  serviceTime: [{ required: true, message: "请选择服务时间", trigger: "change" }],
  status: [{ required: true, message: "请选择服务状态", trigger: "change" }],
  remark: [{ required: true, message: "请输入服务记录", trigger: "blur" }],
});
const fileList = ref([]);
const uploadData = ref({});
const loadingRecord = ref(false);
const clickAddRecord = () => {
  formData.data = {
    serviceContractId: formData.data.serviceContractId,
    remark: "",
    fileList: [],
  };
  loadingRecord.value = false;
  openAddRecord.value = true;
};
const updateContent = (val) => {
  formData.data.remark = val;
};
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(() => {
    if (fileList.value && fileList.value.length > 0) {
      formData.data.fileList = fileList.value.map((item) => {
        return {
          id: item.raw.id,
          fileName: item.raw.fileName,
          fileUrl: item.raw.fileUrl,
        };
      });
    }
    loadingRecord.value = true;
    proxy.post("/serviceContractRecord/add", formData.data).then(
      () => {
        ElMessage({
          message: "添加成功",
          type: "success",
        });
        openAddRecord.value = false;
        getRecordList();
      },
      (err) => {
        console.log(err);
        loadingRecord.value = false;
      }
    );
  });
};
const openFile = (path) => {
  window.open(path, "_blank");
};
</script>

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