<template>
  <my-drawer
    class="sop-dialog"
    :visible="visible"
    :header="title"
    size="85%"
    attach="body"
    :destroyOnClose="true"
    :closeOnOverlayClick="false"
    :close-btn="true"
    :cancel-btn="null"
    @close="drawerOnClose"
    confirmBtn="关闭"
    @confirm="drawerOnClose"
  >
    <t-collapse class="sop-step-mid" defaultExpandAll>
      <t-collapse-panel disabled>
        <template #expandIcon></template>
        <template #header>
          项目派单信息（派单号：{{ dispatchInfo.crmNo }}）
        </template>
        <t-form colon label-width="72px">
          <t-row :gutter="[0, 4]">
            <t-col :span="4">
              <t-form-item label="客户经理">{{
                dispatchInfo.crmUserName
              }}</t-form-item>
            </t-col>
            <t-col :span="4">
              <t-form-item label="项目名称">{{
                dispatchInfo.name
              }}</t-form-item>
            </t-col>
            <t-col :span="4">
              <t-form-item label="客户类型">教务处</t-form-item>
            </t-col>
            <t-col :span="4">
              <t-form-item label="客户名称">{{
                dispatchInfo.custom
              }}</t-form-item>
            </t-col>
            <t-col :span="4">
              <t-form-item label="实施产品">{{
                dispatchInfo.product
              }}</t-form-item>
            </t-col>
            <t-col :span="4">
              <t-form-item label="服务单元">{{
                dispatchInfo.service
              }}</t-form-item>
            </t-col>
          </t-row>
        </t-form>
      </t-collapse-panel>
    </t-collapse>
    <div class="pt-20px" style="border-top: 1px solid #f0f0f0">
      <t-button @click="editProcessVar" v-if="!radioEditStatus">编辑</t-button>
      <t-button @click="editProcessVar" v-else>取消</t-button>
      <t-button
        class="ml-10px animate__animated"
        variant="outline"
        @click="saveProcessVar"
        :disabled="!radioEditStatus"
        :class="{ animate__shakeX: rejectClose }"
        >保存</t-button
      >
    </div>
    <div class="mt-10px">
      <t-row :gutter="[0, 0]">
        <t-col
          :span="
            fullWidthCodes.includes(config.code)
              ? 12
              : config.span < 6
              ? 6
              : config.span || 6
          "
          v-for="config in processVar"
          :key="config.id"
        >
          <dynamic-form-item
            v-if="config.visable"
            :config="config"
            @change="itemValueChange"
          ></dynamic-form-item>
        </t-col>
      </t-row>
    </div>
    <div class="btn-box pt-20px" style="border-top: 1px solid #f0f0f0">
      <t-space>
        <t-button @click="toCreateSop">
          <template #icon><svg-icon name="add-circle" color="#fff" /></template
          >新增sop</t-button
        >
        <upload-button
          upload-url="/api/admin/tb/crm/detail/sop/import"
          :format="['xls', 'xlsx']"
          :uploadData="{ crmNo: props.dispatchInfo.crmNo }"
          @onSuccess="fetchData"
          :failRule="uploadFailRule"
        >
          <t-button variant="outline">
            <template #icon><svg-icon name="import" color="#262626" /></template
            >批量导入
          </t-button>
        </upload-button>
        <t-button
          variant="outline"
          @click="downloadImportTemplate('TEMPLATE_CRM_SOP_DETAIL')"
        >
          <template #icon><svg-icon name="export" color="#262626" /></template
          >下载模板
        </t-button>
      </t-space>
    </div>
    <div class="mt-10px">
      <t-table
        size="small"
        row-key="index"
        :columns="columns"
        :data="tableData"
        bordered
      >
        <template #serviceScope="{ row }">{{
          SERVICE_RANGE[row.serviceScope]
        }}</template>
        <template #scanStartTime="{ row }">{{
          dateFormat(row.scanStartTime, 'yyyy/MM/dd HH:mm')
        }}</template>
        <template #scanEndTime="{ row }">{{
          dateFormat(row.scanEndTime, 'yyyy/MM/dd HH:mm')
        }}</template>
        <template #markPaperStartTime="{ row }">{{
          dateFormat(row.markPaperStartTime, 'yyyy/MM/dd HH:mm')
        }}</template>
        <template #markPaperEndTime="{ row }">{{
          dateFormat(row.markPaperEndTime, 'yyyy/MM/dd HH:mm')
        }}</template>
        <template #operate="{ row }">
          <div class="table-operations" @click.stop>
            <t-link
              theme="primary"
              hover="color"
              @click="allocation(row)"
              :disabled="row.sopStatus === 'START'"
            >
              人员配置
            </t-link>
            <t-link
              theme="primary"
              hover="color"
              @click="editSopItem(row)"
              :disabled="row.sopStatus === 'START'"
            >
              编辑
            </t-link>
            <t-link
              theme="primary"
              hover="color"
              :disabled="row.status === 'PUBLISH'"
              @click="publishSopItem(row)"
            >
              发布
            </t-link>
            <t-link
              theme="primary"
              hover="color"
              @click="deleteSopItem(row)"
              :disabled="row.sopStatus === 'START'"
            >
              删除
            </t-link>
          </div>
        </template>
      </t-table>
    </div>
    <CreateSopItem
      v-model:visible="showCreateDialog"
      :curRow="curRow"
      @confirm="addSopItem"
    ></CreateSopItem>

    <AllocationDialog
      v-model:visible="showAllocationDialog"
      :curRow="curRow"
      @success="fetchData"
    ></AllocationDialog>
  </my-drawer>
</template>

<script lang="ts" name="CreateSop" setup>
import { computed, ref, watch } from 'vue';
import { useVModel } from '@vueuse/core';
import CreateSopItem from './create-sop-item.vue';
import AllocationDialog from './allocation-dialog.vue';
import useFetchTable from '@/hooks/useFetchTable';
import { downloadImportTemplate } from '@/api/common';
import {
  getDispatchInfoApi,
  getSubSopListApi,
  saveProcessVarApi,
  saveSubSopListApi,
  subSopPublishApi,
  subSopDeleteApi,
} from '@/api/service-unit';
import { SERVICE_RANGE } from '@/config/constants';
import { dateFormat } from '@/utils/tool';
import DynamicFormItem from '../../../sop/components/dynamic-form-item/index.vue';
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import { cloneDeep } from 'lodash-es';

const uploadFailRule = (res) => {
  return res.error !== '无';
};

const fullWidthCodes = ref([
  'TABLE',
  'FORM_GROUP_TITLE',
  'TEXTAREA',
  'ONLY_TITLE',
  'DEVICE_OUT_TABLE',
  'DEVICE_IN_TABLE',
]);
const showAllocationDialog = ref(false);
const props = defineProps({
  modelValue: Boolean,
  type: String,
  dispatchInfo: {
    type: Object,
    default() {
      return {};
    },
  },
});
const emit = defineEmits(['update:modelValue', 'confirm']);

const visible = useVModel(props, 'modelValue', emit);
const title = computed(() => {
  if (props.type === 'new') return '新增SOP';
  if (props.type === 'edit') return '编辑SOP';
});
const columns = [
  { colKey: 'courseName', title: '科目名称' },
  { colKey: 'examStudentCount', title: '考生人数', width: 80 },
  { colKey: 'contacts', title: '联系人', width: 100 },
  { colKey: 'mobileNumber', title: '电话', width: 120 },
  { colKey: 'serviceScope', title: '服务范围', width: 100 },
  { colKey: 'scanStartTime', title: '扫描开始时间', width: 150 },
  { colKey: 'scanEndTime', title: '扫描结束时间', width: 150 },
  { colKey: 'markPaperStartTime', title: '评卷开始时间', width: 150 },
  { colKey: 'markPaperEndTime', title: '评卷结束时间', width: 150 },
  {
    colKey: 'operate',
    title: '管理',
    fixed: 'right',
    width: 250,
    cell: 'operate',
  },
];
const showCreateDialog = ref(false);
const curRow = ref(null);
const toCreateSop = () => {
  curRow.value = null;
  showCreateDialog.value = true;
};
const addSopItem = (item) => {
  saveSubSopListApi({
    ...item,
    crmNo: props.dispatchInfo.crmNo,
    id: curRow.value?.id,
  }).then(() => {
    MessagePlugin.success(curRow.value?.id ? '修改成功' : '新增成功');
    fetchData();
  });
};
const editSopItem = (row) => {
  curRow.value = row;
  showCreateDialog.value = true;
};

const publishSopItem = (row) => {
  const confirmDia = DialogPlugin({
    header: '发布SOP提示',
    body: `您确定要发布当前派单的SOP吗？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await subSopPublishApi({ id: row.id }).catch(() => {});
      if (!res) return;
      MessagePlugin.success('发布成功');
      fetchData();
    },
  });
};
const deleteSopItem = (row) => {
  const confirmDia = DialogPlugin({
    header: '删除SOP提示',
    body: `您确定要删除当前派单的SOP吗？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await subSopDeleteApi({ id: row.id }).catch(() => {});
      if (!res) return;
      MessagePlugin.success('删除成功');
      fetchData();
    },
  });
};
const allocation = (row) => {
  curRow.value = row;
  showAllocationDialog.value = true;
};
const stepConfirm = () => {
  emit('confirm');
};

const params = computed(() => ({ crmNo: props.dispatchInfo?.crmNo }));
const {
  loading: tableLoading,
  pagination,
  tableData,
  search,
  fetchData,
  onChange,
} = useFetchTable(
  getSubSopListApi,
  {
    params,
  },
  false
);
const processVar = ref([]);
const radioEditStatus = ref(false);
const editProcessVar = () => {
  radioEditStatus.value = !radioEditStatus.value;
  processVar.value.forEach((item) => {
    item.writable = radioEditStatus.value;
  });
};
const saveProcessVar = () => {
  let arr = cloneDeep(processVar.value);
  arr.forEach((item) => {
    item.writable = false;
    item.value = JSON.stringify({
      value: item.value || null,
    });
  });
  saveProcessVarApi({
    crmNo: props.dispatchInfo.crmNo,
    processVar: JSON.stringify(arr),
  }).then(() => {
    MessagePlugin.success('保存成功');
    radioEditStatus.value = false;
    processVar.value.forEach((item) => {
      item.writable = false;
    });
    rejectClose.value = false;
  });
};
watch(visible, (val) => {
  val && whenOpen();
});
const getInfo = () => {
  getDispatchInfoApi({ crmNo: props.dispatchInfo.crmNo }).then((res) => {
    if (res) {
      try {
        processVar.value = JSON.parse(res.processVar).map((item) => {
          item.value = item.value ? JSON.parse(item.value).value : null;
          return item;
        });
        console.log('processVar.value', processVar.value);
      } catch (e) {
        console.error('processVar不是JSON');
      }
    }
  });
};
const whenOpen = () => {
  fetchData();
  getInfo();
};

const itemValueChange = ({ prop, value }) => {
  let obj = processVar.value.find((item) => item.formId == prop);
  obj.value = value;
};
const confirm = () => {
  emit('confirm');
  visible.value = false;
};
const rejectClose = ref(false);
const drawerOnClose = () => {
  if (radioEditStatus.value) {
    rejectClose.value = false;

    MessagePlugin.warning(
      '请先保存属性【部署方式】【阅卷方式】【扫描场地网络】'
    );
    setTimeout(() => {
      rejectClose.value = true;
    }, 0);
    return false;
  } else {
    visible.value = false;
  }
};
</script>
