<template>
  <div class="app-container">
    <card-table :modalData="followList"  labelWidth="120px" :searchParams="queryParams" @pagination="getList" @selection-change="handleSelectionChange" :loading="loading"
                :tableSearch="true" @columnSearch="handleQuery" @resetList="resetQuery" @sortChange="sortChange" show-no show-selection
    >
      <template #operations="{ selections }">
        <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['business:follow:add']"
            >{{ $t('common.add') }}</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['business:follow:export']"
            >{{ $t('common.export') }}</el-button>
          </el-col>
        </el-row>
      </template>

      <template #default="{ list }">
        <!--<el-table-column align="center" type="selection" width="55"/>-->
        <!--<el-table-column label="No" align="center" :min-width="50"  fixed="left" >-->
        <!--  <template slot-scope="scope">{{ scope.$index + 1 }}</template>-->
        <!--</el-table-column>-->
        <!-- <Column :label="$t('follow.followNo')" align="center" prop="followNo" :min-width="150"  fixed="left"
                :searchParams="queryParams" :showSearch="true" searchType="input" sortable="custom">
          <template #default="{ row }">
            <span @click="handleView(row)" class="link-type">{{ row.followNo }}</span>
          </template>
        </Column> -->
        <Column :label="$t('follow.followTime')" align="center" prop="followTimeFormat" :min-width="300"  :searchParams="queryParams" :showSearch="true" searchType="dateRange" sortable="custom">
          <template #default="{ row }">
            <span>{{ row.followTimeFormat}}</span>
          </template>
          </Column>
        <Column  :label="$t('follow.followType')" align="center" prop="followType" :min-width="200" :searchDict="dict.type.crm_follow_type"
                 :selectMore="true" :searchParams="queryParams" :showSearch="true" searchType="select" sortable="custom">
          <template #default="{ row }">
            <span>{{ formatDict(row.followType,'crm_follow_type') }}</span>
          </template>
        </Column>
        <Column :label="$t('follow.followRelated')" align="center" prop="businessNo" :min-width="200" :searchParams="queryParams" :showSearch="true" searchType="input" sortable="custom">
          <template #default="{ row }">
            <span class="link-type" @click="handleDetailView(row)">{{ row.businessNo }}</span>
          </template>
        </Column>
        <Column :label="$t('follow.follower')" prop="follower" :min-width="150" show-overflow-tooltip :showSearch="true" :searchParams="queryParams"/>
        <!--<Column :label="$t('follow.country')" prop="countryName" :min-width="150" show-overflow-tooltip :searchParams="queryParams"/>-->
        <!--国家-->
        <Column :label="$t('account.country')" :search-dict="curCountryOps" :showSearch="true" label-prop="second"
                prop="countryId"
                search-type="select" select-more value-prop="first" select-prop="countries"
        >
          <template #default="{ row }">
            <span>{{ row.countryName }}</span>
          </template>
        </Column>
        <Column :label="$t('follow.followPerson')" align="center" prop="followPerson" :min-width="150" show-overflow-tooltip  :searchParams="queryParams" :showSearch="true" searchType="input"/>
        <Column :label="$t('follow.followWay')" align="center" prop="followWay" :min-width="200"
                :selectMore="true" :searchDict="dict.type.crm_follow_way" :searchParams="queryParams" :showSearch="true" searchType="select">
          <template #default="{ row }">
            <span>{{ formatDict(row.followWay,'crm_follow_way') }}</span>
          </template>
        </Column>
        <Column :label="$t('follow.contactPerson')" align="center" prop="contactPerson" :min-width="150" :searchParams="queryParams" :showSearch="true" searchType="input"/>
        <Column :label="$t('follow.contact')" align="center" prop="contact" :min-width="150" :searchParams="queryParams" :showSearch="true" searchType="input"/>
        <Column :label="$t('follow.followDesc')" align="center" prop="followDesc" :min-width="200" show-overflow-tooltip :searchParams="queryParams" :showSearch="true" searchType="input"/>
        <Column :label="$t('common.operate')" align="center" :min-width="250" fixed="right" :showSearch="true" searchType="operate">
          <template #default="{ row }">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(row)"
              v-hasPermi="['business:follow:view']"
            >{{ $t('common.view') }}</el-button>

            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleCommand('handleEdit',row)"
              v-if="$store.state.user.id == row.createBy || $store.getters.roles.includes('sales_director')"
              v-hasPermi="['business:follow:edit']"
            >{{ $t('common.edit') }}</el-button>

            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleCommand('handleDelete',row)"
              v-if="$store.state.user.id == row.createBy || $store.getters.roles.includes('sales_director')"
              v-hasPermi="['business:follow:remove']"
            >{{ $t('common.delete') }}</el-button>

            <!-- <el-dropdown size="mini" v-if="$store.state.user.id == row.createBy" @command="(command) => handleCommand(command, row)">
              <el-button icon="el-icon-d-arrow-right" size="mini" type="text">{{ $t('common.more') }}</el-button>
              <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-hasPermi="['business:follow:edit']" command="handleEdit"
                                    size="mini" icon="el-icon-edit">{{ $t('common.edit') }}
                  </el-dropdown-item>
                  <el-dropdown-item v-hasPermi="['business:follow:remove']" command="handleDelete" size="mini" icon="el-icon-delete">{{ $t('common.delete') }}
                  </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown> -->
          </template>
        </Column>
      </template>
    </card-table>

    <FollowDialog ref="followDialog" @returnRow="dialogReturn" @close="open = false"></FollowDialog>
  </div>
</template>
<script>
import { listFollow, deleteFollow, exportFollow, getCountryList } from '@/api/business/crm/follow.js'
  import Form from "../../../components/element/form/Form";
  import CardForm from "../../../components/element/form/CardForm";
  import CardTable from "../../../components/element/table/CardTable";
  import ImageUpload from "../../../components/ImageUpload";
  import ImagePreview from "../../../components/ImagePreview";
  import DictColumn from "../../../components/element/table/DictColumn";
  import Column from "../../../components/element/table/Column";

  import {getLocalTime} from "@/utils/data/dataUtils"
  import FollowDialog from "./FollowDialog";
  import {parseTime} from "@/utils/ruoyi";
  export default {
    name: "Follow",
    components: {
      FollowDialog,
      Column,
      DictColumn,
      CardTable,
      CardForm,
      Form,
      ImageUpload,
      ImagePreview
    },
    dicts: ['crm_follow_type','crm_follow_way'],
    data() {
      return {
        // 遮罩层
        loading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 项目表格数据
        followList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 编辑可能区分
        contentEditable:true,
        // 新增编辑FLAG
        addEditFlag: 1,
        // 跟进类别下拉框
        followTypeDropdownList:[],
        // 跟进方法下拉框
        followWayDropdownList:[],
        // dialog传参
        dialogParams: {
          followId: "",
          addEditFlag: '1'
        },
        // 查询参数
        queryParams: {
          total:0,
          pageNum: 1,
          pageSize: 10,
          followNo: undefined,
          businessNo:undefined,
          followType: [],
          followPerson:undefined,
          followWay: [],
          contactPerson:undefined,
          contact:undefined,
          followDesc:undefined,
          beginTime: undefined,
          endTime: undefined,
          language:undefined,
          createByName:undefined,
          follower: undefined,
        },

        curCountryOps: [],
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询跟进记录列表 */
      getList() {
        let params;
        this.loading = true;
        params = {
          pageNum:this.queryParams.pageNum,
          pageSize:this.queryParams.pageSize,
          language:this.queryParams.language,
          beginTime: this.queryParams.beginTime,
          endTime: this.queryParams.endTime,

          contact: this.queryParams.contact,
          contactPerson: this.queryParams.contactPerson,
          followTypeArray: this.queryParams.followType,
          followWayArray: this.queryParams.followWay,
          followNo: this.queryParams.followNo,
          followDesc: this.queryParams.followDesc,
          followPerson: this.queryParams.followPerson,
          businessNo: this.queryParams.businessNo,
          orderByColumn: this.queryParams.orderByColumn,
          isAsc: this.queryParams.isAsc,
          follower: this.queryParams.follower,
          countries: this.queryParams.countries,
        }

        listFollow(params).then(response => {
          this.followList = response.rows;
          this.queryParams.total = response.total;
          this.loading = false;
        });

        this.curCountry()
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams.followType = [];
        this.queryParams.followPerson = "";
        this.queryParams.followWay = [];
        this.queryParams.followTimeFormat = [];
        this.queryParams.beginTime = '';
        this.queryParams.endTime = '';
        this.queryParams.followNo = '';
        this.queryParams.businessNo = '';
        this.queryParams.contactPerson = "";
        this.queryParams.contact = "";
        this.queryParams.followDesc = "";
        this.queryParams.follower = "";
        this.queryParams.countryId = '';
        this.queryParams.countries = '';
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.open = true
        this.dialogParams.followId = "";
        this.dialogParams.addEditFlag = '1';
        let para = {
          flag: '1',
          followId: "",
          leadId: null,
          accountId: null,
          projectId: null
        }
        this.$refs.followDialog.dialogItemInit(para);
      },
      /**  查看按钮操作 */
      handleView(row){
        this.open = true
        this.dialogParams.followId = row.followId;
        this.dialogParams.addEditFlag = '3';
        let para = {
          flag: '3',
          followId: row.followId,
          leadId: null,
          accountId: null,
          projectId: null
        }
        this.$refs.followDialog.dialogItemInit(para);
      },
      /**  查看具体操作 */
      handleDetailView(row){
        const {followType, businessId} = row;
        // console.log(followType, businessId)

        //
        if (!followType || !businessId) {
          console.error('followType or businessId is null')
          return
        }

        // 跟进类型 0:线索 1:客户 2:项目
        switch (followType) {
          case '0':
             this.$tab.openPage(this.$t('lead.detail'), '/crmManagement/lead-view/index/' + businessId);
             break;
          case '1':
            this.$tab.openPage(this.$t('account.view'), '/account-edit/index/' + businessId, { type: 'view' });

            break;
          case '2':
            this.$tab.openPage(this.$t('project.view'), '/project-view/' + businessId);
            break;
          default:
            break;
        }

      },
      /** 编辑按钮操作 */
      handleEdit(row){
        this.open = true
        this.dialogParams.followId = row.followId;
        this.dialogParams.addEditFlag = '2';
        let para = {
          flag: '2',
          followId: row.followId,
          leadId: null,
          accountId: null,
          projectId: null
        }
        this.$refs.followDialog.dialogItemInit(para);
      },

      /** 删除按钮操作 */
      handleDelete(row) {

        this.$modal.confirm(this.$t('common.isDelete')).then(function() {
          return deleteFollow(row);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t('common.deleteSuccess'));
          if (row.followType == '2') {
            // 触发刷新
            this.$store.commit('refreshProject');
          }
        }).catch(() => {});

      },
      /** 导出按钮操作 */
      handleExport() {
        this.queryParams.language = this.$i18n.locale;
        const fileName = this.$t('follow.follow') + parseTime(new Date(), '{y}{m}{d}') + '.xlsx'
        this.download('business/follow/export', {
          ...this.queryParams,
          followIds: this.ids
        }, fileName)
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.followId)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },

      sortChange({column, prop, order}) {
        if (order === 'ascending') {
          this.queryParams.orderByColumn = prop;
          this.queryParams.isAsc = 'asc';
        } else if (order === 'descending') {
          this.queryParams.orderByColumn = prop;
          this.queryParams.isAsc = 'desc';
        } else {
          this.queryParams.orderByColumn = null;
          this.queryParams.isAsc = null;
        }
        this.getList();
      },

      // 字典值format
      formatDict(value,dictType){
        let labelStr = '';
        for(let i =0;i< this.dict.type[dictType].length;i++){
          let item = this.dict.type[dictType][i]
          if(item.value == value){
            labelStr = item.label;
            break;
          }
        }
        return  labelStr;
      },
      // 日期format（時區）
      formatterTime(data){
        return getLocalTime(data,"YYYY-MM-DD");
      },
      // 弹出窗的关闭处理
      dialogReturn(returnRow){
        if(returnRow.returnCode == "OK"){this.getList();}
      },
      handleCommand(command, row) {
        switch (command) {
          case "handleEdit":
            this.handleEdit(row);
            break;
          case "handleDelete":
            this.handleDelete(row);
            break;
          default:
            break;
        }
      },

      async curCountry() {
        const response = await getCountryList()
        this.curCountryOps = response.data
      },
    },
    mounted() {

    },

  };
</script>
<style scoped lang="scss">
@import "@/assets/styles/element-variables.scss";
.el-dropdown-menu {
  padding: 8px 0;

.el-dropdown-menu__item {
  padding: 0 20px;
  color: $--color-primary;

// 不知道为什么 对 i 标签使用margin或者padding 无效，暂时使用 flex + gap
display: flex;
  align-items: center;
  justify-content: space-around;
  gap: 8px;

//&> i {
   //  margin-right: 20px;
   //}
}


.el-dropdown-menu__item + .el-dropdown-menu__item {
  margin-top: 5px;
}
}
</style>

