<template>
  <div class="h-full flex">
    <div class="p-5 w-80 pr-0">
      <div class="bg-white w-full h-full shadow-md rounded-md flex flex-col">
        <div class="flex-1 p-3 overflow-y-auto">
          <el-form :model="businessOpportunityForm" label-width="70px" style="max-width: 600px">
            <el-form-item label="商机名称">
              <el-input v-model="businessOpportunityForm.name" clearable placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="商机阶段">
              <el-select v-model="businessOpportunityForm.stageId" placeholder="请选择" clearable>
                <el-option v-for="item in fixedData.BusinessStage" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="客户名称">
              <el-input v-model="businessOpportunityForm.customerName" clearable placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="联系人">
              <el-input v-model="businessOpportunityForm.contactsName" clearable placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="产品">
              <el-select v-model="businessOpportunityForm.product" placeholder="请选择" clearable>
                <el-option v-for="item in fixedData.ProductArr" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="负责人">
              <!-- <el-select v-model="businessOpportunityForm.inchargerId" placeholder="请选择" clearable>
                <el-option v-for="item in fixedData.Personnel" :key="item.id" :label="item.name" :value="item.id" />
              </el-select> -->
              <personnel-search v-model="businessOpportunityForm.inchargerId" :size="''" placeholder="请选择"></personnel-search>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker v-model="businessOpportunityForm.startTime" type="date" placeholder="请选择"
                :clearable="false" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="">
              <el-date-picker v-model="businessOpportunityForm.endTime" type="date" placeholder="请选择" :clearable="false"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-form>
        </div>
        <div class="w-full flex p-3 shadow-[0_-3px_5px_0px_rgba(0,0,0,0.2)]">
          <El-button class="w-full" @click="resetForm()">重置</El-Button>
          <El-button type="primary" class="w-full" @click="getBusinessTableList()">搜索</El-Button>
        </div>
      </div>
    </div>
    <div class="flex-1 p-5 overflow-auto">
      <div class="bg-white w-full h-full p-3 shadow-md rounded-md flex flex-col">
        <div class="flex justify-end pb-3">
          <el-button v-permission="['businessAddAnEdit']" type="primary"
            @click="editNewBusiness(false)">新建商机</el-button>
          <el-button type="primary" @click="showVisible('batchTransferVisible')"
            :disabled="batchTableData.length <= 0">批量转移</el-button>
          <el-button type="primary" v-permission="['businessDelete']" @click="batchDeteleItem()"
            :disabled="batchTableData.length <= 0">批量删除</el-button>
          <el-button type="primary" @click="showVisible('stageSetVisible')">阶段设置</el-button>
          <el-button type="primary" v-permission="['businessRecycle']"
            @click="showVisible('deteleBusinessVisible')">回收站</el-button>
          <el-button v-permission="['businessImport']" type="primary"
            @click="showVisible('importVisible')">导入</el-button>
          <el-button v-permission="['businessExport']" type="primary" @click="exportBusinessTableList()"
            :loading="allLoading.exoprtLoading">导出</el-button>
        </div>
        <div class="flex-1 w-full overflow-hidden">
          <el-table ref="businessTableRef" :data="businessTable" border v-loading="allLoading.businessTableLading"
            :show-overflow-tooltip="tableShowOverflowTooltip" @selection-change="changeBatch"
            style="width: 100%;height: 100%;">
            <el-table-column type="selection" width="55" />
            <el-table-column v-for="(item, index) in tableColumn" :prop="item.prop" :label="item.label" :key="index"
              :width="item.width">
              <template #default="scope">
                <div class="table-text-textnowrap" v-if="item.eventName"
                  @click="dealWithTableColumn(scope.row, item.eventName)">{{ scope.row[item.prop] }}</div>
                <template v-else-if="['inchargerName', 'creatorName'].includes(item.prop)">
                  <TextTranslation translationTypes="userName" :translationValue="scope.row[item.prop]"></TextTranslation>
                </template>
                <template v-else>{{ scope.row[item.prop] }}</template>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="200"
              v-permission="['businessAddAnEdit', 'tasksAdd', 'businessDelete']">
              <template #default="scope">
                <el-button link type="primary" size="large" @click="editNewBusiness(scope.row)"
                  v-permission="['businessAddAnEdit']">编辑</el-button>
                <el-button link type="primary" size="large" @click="newTask(scope.row)"
                  v-permission="['tasksAdd']">新建任务</el-button>
                <el-button link type="danger" size="large" @click="businessDeteleItem(scope.row.id, scope.row.name)"
                  v-permission="['businessDelete']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="flex justify-end pt-3">
          <el-pagination layout="total, prev, pager, next, sizes" :page-size="businessOpportunityForm.pageFrom"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" :total="businessTotalTable"
            :hide-on-single-page="true" />
        </div>
      </div>
    </div>
    <!-- 弹窗 -->
    <el-dialog v-model="allVisible.newBusinessisible" width="1000" :show-close="false" top="10vh"
      :before-close="handleClose">
      <template #header="{ close, titleId, titleClass }">
        <div class="flex justify-between items-center border-b pb-3 dialog-header">
          <h4 :id="titleId">{{ allText.newBusinessisibleText }}</h4>
          <div>
            <el-button type="primary" :loading="allLoading.newBusinessSaveLading"
              :disabled="allLoading.businessSaveLading" @click="editBusiness(true)"
              v-if="!businessTemplateValue.id">保存并新建</el-button>
            <el-button type="primary" @click="editBusiness(false)" :loading="allLoading.businessSaveLading"
              :disabled="allLoading.newBusinessSaveLading">保存</el-button>
            <el-button @click="closeVisible('newBusinessisible')">取消</el-button>
          </div>
        </div>
      </template>
      <div class="h-[60vh] overflow-y-auto scroll-bar pt-3" v-loading="allLoading.generateFormLading">
        <GenerateForm ref="businessTemplateRef" :data="businessTemplate" :value="businessTemplateValue"
          :key="businessTemplateKey" />
        <div>相关产品</div>
        <RelatedProducts ref="relatedProductsRef" :productTableList="productTableList"
          :productTableListValue="productTableListValue" />
      </div>
    </el-dialog>

    <!-- 批量转移 -->
    <el-dialog v-model="allVisible.batchTransferVisible" width="600" :show-close="false" top="10vh">
      <template #header="{ close, titleId, titleClass }">
        <div class="flex justify-between items-center border-b pb-3 dialog-header">
          <h4 :id="titleId">{{ allText.transferText }}</h4>
          <div>
            <el-button type="primary" v-loading="allLoading.transferLoading" @click="transferBusiness()">转移</el-button>
            <el-button @click="allVisible.batchTransferVisible = false">取消</el-button>
          </div>
        </div>
      </template>
      <div class="scroll-bar m-6">
        <div class="flex mb-4">
          <div class="w-20 flex items-center justify-end pr-4">转移至:</div>
          <!-- <el-select v-model="transferPersonnel" placeholder="请选择" class="flex1">
            <el-option v-for="item in fixedData.Personnel" :key="item.id" :label="item.name" :value="item.id" />
          </el-select> -->
          <personnel-search v-model="transferPersonnel" :size="''" placeholder="请选择"></personnel-search>
        </div>
        <div class="pl-3 text-[#e94a4a]">转移后，将看不到此商机</div>
      </div>
    </el-dialog>

    <!-- 导入 -->
    <el-dialog v-model="allVisible.importVisible" width="680" :show-close="false" top="10vh">
      <template #header="{ close, titleId, titleClass }">
        <div class="flex justify-between items-center border-b pb-3 dialog-header">
          <h4 :id="titleId">导入产品</h4>
          <div class="flex">
            <el-upload class="upload-demo mr-3" :limit="1" :show-file-list="false" accept=".xlsx"
              :http-request="importBusiness">
              <el-button type="primary" :loading="allLoading.importLoading">导入</el-button>
            </el-upload>
            <el-button @click="allVisible.importVisible = false">取消</el-button>
          </div>
        </div>
      </template>
      <div class="p-8">
        <div class="ml-4 mr-4">
          <div class="flex items-center">1、点击下载 <el-link type="primary"
              @click="downloadTemplate(MODURL, '商机导入模板.xlsx')">商机导入模板.xlsx</el-link></div>
          <div class="mt-4">2、填写excel文件、商机名称、商机金额、商机阶段必填</div>
        </div>
      </div>
    </el-dialog>

    <!-- 新建任务 -->
    <TaskModal :visible="allVisible.taskModalVisible" :edit-form="taskModalForm" :save-loading="taskLoading"
      @close="closeVisible('taskModalVisible')" @submit="submitForm" :title="'新建任务'"
      :disabled-list="['taskType', 'businessOpportunityId']" />

    <!-- 回收站 -->
    <DeteleBusiness :visibles="allVisible.deteleBusinessVisible" @closeVisible="closeVisible" />

    <!-- 阶段设置 -->
    <StageSetting :visibles="allVisible.stageSetVisible" @closeVisible="closeVisible" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, inject } from "vue";
import type { ElTable, FormInstance, FormRules, UploadRequestOptions } from 'element-plus'
import { useRouter, useRoute } from "vue-router";
import { GETSYSFILED, MOD, GETPERSONNEL, GETGENERATEFOEM, GETBUSINESSLIST, UPDATEINSET, BUSINESSDETELE, BATCHTRANSFER, MODURL, tableColumn, BUSIESS_GETSATE, URL_IMPOERBUSINESS, BUSIESS_INFO, URL_EXPORTBUSINESS } from './api'
import { GETTABLELIST } from '@/pages/product/api'
import { post, get, uploadFile } from "@/utils/request";
import { getAllListByCode, getFromValue, resetFromValue, getFirstDayOfMonth, createTaskFromType, formatDate, confirmAction, downloadTemplate, downloadFile, judgmentaAmounteEqual } from '@/utils/tools'
import { createTask } from '@/components/TaskModal/taskFunction'
import { formatDateTime } from '@/utils/times'
import { GenerateForm } from '@zmjs/form-design';
import { tableShowOverflowTooltip } from '@/utils/globalVariables'
import RelatedProducts from '@/components/relatedProducts/relatedProducts.vue'
import TaskModal from '@/components/TaskModal/index.vue'
import DeteleBusiness from './component/deteleTables.vue'
import StageSetting from './component/stageSetting.vue'
import { GETTABLELISTPRODUCT } from "../order/api";
import personnelSearch from '@/components/translationComponent/personnelSearch/personnelSearch.vue';

const route = useRoute()
const router = useRouter()
const globalPopup = inject<GlobalPopup>('globalPopup')
const businessTableRef = ref<InstanceType<typeof ElTable>>() // 商机table dom
const businessTotalTable = ref(0)
const businessTemplateRef = ref<typeof GenerateForm>() // 自定义表单dom
const relatedProductsRef = ref<typeof RelatedProducts>()
const businessTemplateValue = ref<any>({})
const businessTemplateKey = ref(1)
const businessTemplate = ref({
  config: {},
  list: []
}) // 自定义表单数据
const businessTable = ref([])
const allLoading = reactive({
  businessTableLading: false,
  businessSaveLading: false,
  newBusinessSaveLading: false,
  transferLoading: false,
  importLoading: false,
  exoprtLoading: false,
  generateFormLading: false
})
const allVisible = reactive({
  newBusinessisible: false,
  recycleVisible: false,
  taskModalVisible: false,
  batchTransferVisible: false,
  deteleBusinessVisible: false,
  stageSetVisible: false,
  importVisible: false
})
const allText = reactive({
  newBusinessisibleText: '新建商机',
  transferText: '转移商机'
}) // 所有文本

const taskModalForm = ref({}) // 任务弹窗表单
const taskLoading = ref<saveLoadingType>("1");
const batchTableData = ref([]) // 批量数据
const transferPersonnel = ref('') // 转移人

const businessOpportunityForm = reactive<businessOpportunityFormType>({
  name: '',
  stageId: '',
  customerName: '',
  contactsName: '',
  product: '',
  inchargerId: '',
  startTime: getFirstDayOfMonth(new Date()),
  endTime: formatDate(new Date()),
  pageIndex: 1,
  pageFrom: 10
})
const fixedData = reactive({
  BusinessStage: [] as fixedDataInterface[],
  Personnel: [] as personnelInterface[],
  ProductArr: [] as productInterface[]
})
const productTableList = ref([])
const productTableListValue = ref([])


function editBusiness(visibles: boolean) {
  businessTemplateRef.value?.getData().then((res: any) => {
    let productTableListData = relatedProductsRef?.value?.returnData()
    console.log(!productTableListData, judgmentaAmounteEqual({ ...businessTemplateValue.value, ...res }, productTableListData))
    if (!productTableListData || judgmentaAmounteEqual({ ...businessTemplateValue.value, ...res }, productTableListData)) {
      return
    }

    productTableListData.forEach((item: any) => {
      delete item.id
    })
    let newForm = {
      ...res,
      expectedTransactionDate: res.expectedTransactionDate ? formatDateTime(new Date(res.expectedTransactionDate)) : '',
      businessItemProductList: productTableListData ? JSON.stringify(productTableListData) : []
    }
    allLoading.businessSaveLading = true
    setTimeout(() => {
      post(UPDATEINSET, { ...businessTemplateValue.value, ...newForm }).then((_res) => {
        allVisible.newBusinessisible = visibles
        globalPopup?.showSuccess('保存成功')
        getBusinessTableList()
      }).finally(() => {
        allLoading.businessSaveLading = false
      })
    }, 1500)
  }).catch((_err: any) => {
    console.log(_err)
    globalPopup?.showError('请填写完整')
  })
}

function editNewBusiness(item: any) {
  console.log(item, '选择数据')
  showVisible('newBusinessisible')
  allLoading.generateFormLading = true
  if (item) {
    editProduct(item)
    businessTemplateValue.value = editBusinessData(item)
    allText.newBusinessisibleText = '编辑商机'
  }
  if (!item) {
    businessTemplateValue.value = {}
    productTableListValue.value = []
    allText.newBusinessisibleText = '新建商机'
  }
  setTimeout(() => {
    businessTemplateRef.value && businessTemplateRef.value.reset()
    businessTemplateKey.value++
    allLoading.generateFormLading = false
  }, 500)
}

function newTask(item: any) {
  const { id } = item
  taskModalForm.value = { ...createTaskFromType(1), businessOpportunityId: id, }
  showVisible('taskModalVisible')
}

function submitForm(submitData: any, isClose: boolean) { // 任务提交
  taskLoading.value = '2'
  createTask(submitData, isClose).then((res) => {
    const { saveLoading, isClose } = res
    taskLoading.value = saveLoading
    allVisible.taskModalVisible = isClose
    globalPopup?.showSuccess('新增成功')
  }).catch((err) => {
    const { saveLoading, isClose, message } = err
    taskLoading.value = saveLoading
    allVisible.taskModalVisible = isClose
    globalPopup?.showError(message)
  })
}

function transferBusiness() {
  const ids = batchTableData.value.map((item: any) => item.id).join(',')
  allLoading.transferLoading = true
  post(BATCHTRANSFER, { ids, inchargerId: transferPersonnel.value }).then(() => {
    transferPersonnel.value = ''
    globalPopup?.showSuccess('转移成功')
    closeVisible('batchTransferVisible')
    getBusinessTableList()
  }).finally(() => {
    allLoading.transferLoading = false
  })
}

function batchDeteleItem() {
  const value = batchTableData.value.map((item: any) => item.id).join(',')
  const label = batchTableData.value.map((item: any) => item.name).join(',')
  businessDeteleItem(value, label, true)
}

function businessDeteleItem(value: string | number, label: string, batch: boolean = false) {
  confirmAction(`确定${batch ? '批量' : ''}删除【${label}】商机吗？`).then(() => {
    post(BUSINESSDETELE, { ids: value }).then(res => {
      if (res.code != 'ok') {
        globalPopup?.showError(res.msg)
        return
      }
      globalPopup?.showSuccess('删除成功')
      changeBatch(false)
      getBusinessTableList()
    }).catch((err) => {
      globalPopup?.showError(err.msg)
    })
  })
}

async function importBusiness(param: UploadRequestOptions) {
  allLoading.importLoading = true
  const formData = new FormData();
  formData.append('multipartFile', param.file)
  const res = await uploadFile(URL_IMPOERBUSINESS, formData).finally(() => {
    allLoading.importLoading = false
  })
  if (res.code == 'ok') {
    globalPopup?.showSuccess('导入成功' || '')
    getBusinessTableList()
    return
  }
  globalPopup?.showError(res.msg || '')
}

function exportBusinessTableList() {
  allLoading.exoprtLoading = true
  let valueForm = getFromValue(businessOpportunityForm)
  post(URL_EXPORTBUSINESS, { ...valueForm }).then((res) => {
    downloadFile(res.data, '商机表导出.xlsx')
  }).finally(() => {
    allLoading.exoprtLoading = false
  })
}

function changeBatch(flag: boolean = true) {
  if (flag) {
    batchTableData.value = businessTableRef.value && businessTableRef.value.getSelectionRows()
  } else {
    batchTableData.value = []
    businessTableRef.value && businessTableRef.value.clearSelection()
  }
}

function editProduct(row: any) {
  post(BUSIESS_INFO, { id: row.id }).then(({ data }) => {
    const list = (data.businessItemProducts || []).map((item: any) => {
      const { id, productName, productId, productCode, unit, unitName, typeName, productType, type, price, inventory, orderProductDetail, num, discount, sellingPrice, sealPrice, totalPrice, quantity } = item
      return {
        id, productId: productId, productName, productCode, unitName: unit, typeName: productType, type, price, inventory,
        num, discount, sealPrice, totalPrice, quantity, sellingPrice
      }
    })
    productTableListValue.value = list
  })
}

function editBusinessData(item: any) {
  const { name, expectedTransactionDate, amountOfMoney = 0, customerId, contactsId, creatorId, stageId, id, inchargerId, remark } = item
  return { name, expectedTransactionDate, amountOfMoney, customerId, contactsId, creatorId, stageId, id, inchargerId, remark }
}

function handleSizeChange(val: number) {
  businessOpportunityForm.pageIndex = 1
  businessOpportunityForm.pageFrom = val
  getBusinessTableList()
}

function handleCurrentChange(val: number) {
  businessOpportunityForm.pageIndex = val
  getBusinessTableList()
}

function showVisible(type: keyof typeof allVisible) { // 显示弹窗
  allVisible[type] = true
}

function closeVisible(type: keyof typeof allVisible) {
  allVisible[type] = false
}

function handleClose(done: () => void) {
  done()
}

function getBusinessTableList() {
  const formValue = getFromValue(businessOpportunityForm)
  allLoading.businessTableLading = true
  post(GETBUSINESSLIST, { ...formValue }).then((res) => {
    const { data, total } = res.data
    businessTable.value = data.map((item: any) => {
      return {
        ...item,
        expectedTransactionDate: formatDate(new Date(item.expectedTransactionDate))
      }
    })
    businessTotalTable.value = total
  }).finally(() => {
    allLoading.businessTableLading = false
  })
}

function resetForm() {
  let reset = {
    startTime: getFirstDayOfMonth(new Date()),
    endTime: formatDate(new Date()),
    pageIndex: 1,
    pageFrom: 10
  }
  let newBusinessOpportunityForm = resetFromValue(businessOpportunityForm, { ...reset })
  Object.assign(businessOpportunityForm, newBusinessOpportunityForm)
  getBusinessTableList()
}

async function getSystemField() {
  // const systemField = getAllListByCode(['商机阶段'])
  // for (let i in systemField) {
  //   const { data } = await get(`${GETSYSFILED}?code=${systemField[i]}`)
  //   for (let key of Object.keys(fixedData)) {
  //     if (systemField[i] == key) {
  //       Object.assign(fixedData, { [key]: data })
  //     }
  //   }
  // }

  const row = await post(BUSIESS_GETSATE, {})
  fixedData.BusinessStage = (row.data || []).map((item: any) => {
    const { name, id, seq } = item
    return { name, id, seq }
  }).sort(function (a: any, b: any) { return a.seq - b.seq; });

  const { data } = await post(GETPERSONNEL, {})
  fixedData.Personnel = data.map((item: any) => {
    const { id, name, phone, jobNumber } = item
    return {
      id, name, phone, jobNumber
    }
  })

  post(GETTABLELISTPRODUCT, { pageIndex: -1, pageSize: -1 }).then(({ data }) => {
    fixedData.ProductArr = (data.record || []).map((item: any) => {
      const { id, productName } = item
      return {
        value: id, label: productName
      }
    })
  })

  const res = await get(GETGENERATEFOEM)
  businessTemplate.value = JSON.parse(res.data[0].config)
}

function toBusinessTableDetail(row: any) {
  router.push({
    path: `${MOD}/detail`,
    query: { id: row.id }
  })
}

function dealWithTableColumn(row: any, eventName: string) {
  if (eventName == 'toClueTableDetail') {
    toBusinessTableDetail(row)
  }
}

function getProductTableList() {
  post(GETTABLELIST, { pageIndex: -1, pageSize: -1 }).then((res) => {
    if (res.code == 'ok') {
      const { record, total } = res.data
      productTableList.value = record.map((item: any) => {
        const { id, productName, productCode, unit, unitName, typeName, type, price, inventory } = item
        return {
          id,
          productId: id,
          productName,
          productCode,
          unit,
          unitName,
          price,
          type,
          typeName,
          inventory,
          quantity: '',
          discount: '',
          totalPrice: ''
        }
      })
    }
  })
}

onMounted(() => {
  getSystemField()
  getProductTableList()
  getBusinessTableList()
})
</script>

<style lang="scss" scoped>
.dialog-header {
  h4 {
    font-size: 18px;
    line-height: 24px;
  }
}
</style>