<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible.sync="addOrEditDialogFlag"
    :title="title"
    :append-to-body="false"
    :close-on-click-modal="false"
    width="80%"
    :before-close="cancel"
    :fullscreen="fullscreen"
  >
    <template slot="title">
      <modalTitle
        :title="title"
        @setFullscreen="fullscreen = !fullscreen"
      ></modalTitle>
    </template>
    <el-form
      ref="form"
      :rules="rules"
      class="el-form-box borNone"
      :model="form"
      label-width="0"
      style="padding: 0 15px"
    >
      <el-row :gutter="15">
        <el-descriptions title="基本信息" :column="4" border>
          <el-descriptions-item label="编码">
            <el-input v-model="form.code" disabled></el-input
          ></el-descriptions-item>
          <el-descriptions-item label="类型">
            <el-form-item prop="type">
              <!-- <el-input
                v-model="form.type"
                placeholder="请选择"
              ></el-input> -->
              <DictSelection
                dictName="市场活动类型"
                clearable
                v-model="form.type"
              >
              </DictSelection> </el-form-item
          ></el-descriptions-item>
          <el-descriptions-item label="主题"
            ><el-form-item prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入"
              ></el-input> </el-form-item
          ></el-descriptions-item>

          <el-descriptions-item label="发起人">
            <el-form-item prop="promoterName">
              <el-input
                v-model="form.promoterName"
                @click.native="userListOpen('promoterName')"
                placeholder="请选择"
              ></el-input>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
        <el-descriptions title="来访信息" :column="4" border>
          <el-descriptions-item label="来访单位">
            <el-form-item prop="visitingUnitsName">
              <el-input
                v-model="form.visitingUnitsName"
                :disabled="!!form.visitingUnits"
              >
                <template slot="append">
                  <el-link
                    type="primary"
                    :underline="false"
                    @click.native="contactOpen"
                  >
                    选择</el-link
                  >
                </template>
              </el-input>
            </el-form-item>
          </el-descriptions-item>

          <el-descriptions-item label="人数">
            <el-form-item prop="numberOfVisitors">
              <el-input
                v-model="form.numberOfVisitors"
                type="number"
                placeholder="请输入"
              ></el-input></el-form-item
          ></el-descriptions-item>
          <el-descriptions-item label="负责人">
            <el-form-item prop="commanderName">
              <el-autocomplete
                class="inline-input"
                v-model="form.commanderName"
                :fetch-suggestions="getLinkList"
                placeholder="请输入"
                @select="linkListClick"
              ></el-autocomplete>
              <!-- <el-select
                v-model="form.commanderName"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in linkList"
                  :key="item.linkName"
                  :label="item.linkName"
                  :value="item.linkName"
                  @click="linkListClick(item)"
                >
                </el-option>
              </el-select> -->
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="职位">
            <el-form-item prop="positionName">
              <el-input
                v-model="form.positionName"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="联系方式">
            <el-form-item prop="phone">
              <el-input v-model="form.phone" placeholder="请输入"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="时间">
            <el-form-item prop="TimeArr">
              <el-date-picker
                v-model="TimeArr"
                type="datetimerange"
                align="right"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['9:00:00', '12:00:00']"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
              <span v-if="TimeArr.length > 1"> {{ getTimeArr }} 天 </span>
            </el-form-item></el-descriptions-item
          >
        </el-descriptions>
        <el-descriptions title="接待项目" :column="4" border>
          <el-descriptions-item label="项目类别">
            <el-form-item prop="checkList">
              <el-checkbox-group
                v-model="checkList"
                @change="changeCheckList"
                style="margin-left: 10px"
              >
                <el-checkbox
                  :label="item.refKey"
                  v-for="item in checkboxGroup"
                  :key="item.name"
                  >{{ item.name }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
        <el-descriptions title="接待人信息" :column="4" border>
          <el-descriptions-item label="接待部门">
            <el-form-item prop="receptionDepartmentId">
              <el-cascader
                class="ele-block"
                :options="organizationList"
                placeholder="请选择接待部门"
                :props="defaultProps"
                ref="deptRef"
                :show-all-levels="false"
                v-model="form.receptionDepartmentId"
                @change="receptionDepartmentIdChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="接待人">
            <el-form-item prop="receptionUserName">
              <el-input
                v-model="form.receptionUserName"
                @click.native="receptionUserOpen"
                placeholder="请选择"
              ></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="费用归属人">
            <el-form-item prop="costOwnerName">
              <el-input
                v-model="form.costOwnerName"
                @click.native="userListOpen('costOwnerId')"
                placeholder="请选择"
              ></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="欢迎标语">
            <el-form-item prop="welcomeSign">
              <el-input
                v-model="form.welcomeSign"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="接待流程">
            <el-form-item prop="remark">
              <el-input
                type="textarea"
                v-model="form.remark"
                style="height: 150px"
              ></el-input>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-row>
      <el-row
        :gutter="15"
        style="margin-top: 20px"
        v-if="form.receptionProjectList.length > 0"
      >
        <el-col :span="24">
          <el-tabs
            v-model="activeName"
            type="border-card"
            style="height: calc(100% - 124px); width: 100%"
          >
            <el-tab-pane
              v-for="item in form.receptionProjectList"
              :label="item.name"
              :name="item.refKey"
              :key="item.refKey"
            >
              <taskInfoTable
                ref="taskInfoTableRef"
                v-if="item.name == '用车'"
                :key="'用车'"
              ></taskInfoTable>
              <mealList
                ref="mealListRef"
                v-if="item.name == '用餐'"
                :organizationList="organizationList"
              ></mealList>
              <putUpList ref="putUpRef" v-if="item.name == '住宿'"></putUpList>
              <souvenirList
                ref="souvenirListRef"
                v-if="item.name == '纪念品'"
                :organizationList="organizationList"
              ></souvenirList>
              <conferenceList
                ref="conferenceListRef"
                v-if="item.name == '会议'"
                :organizationList="organizationList"
              ></conferenceList>
              <companyList
                ref="companyListRef"
                v-if="item.name == '公司参观'"
                :organizationList="organizationList"
              ></companyList>
              <visitList
                ref="visitListRef"
                v-if="item.name == '景点游览'"
                :organizationList="organizationList"
              ></visitList>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer">
      <el-button type="primary" @click="save()" v-click-once>保存</el-button>
      <el-button type="primary" @click="save('sub')" v-click-once
        >提交</el-button
      >

      <el-button @click="cancel">返回</el-button>
    </div>
    <UserList ref="userListRef" @success="userListSuccess"></UserList>
    <contact ref="contactRef" @changeParent="contactChange"></contact>
    <staffSelection
      ref="staffSelectionRef"
      @confirm="staffSelectionbk"
    ></staffSelection>
    <process-submit-dialog
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      v-if="processSubmitDialogFlag"
      ref="processSubmitDialogRef"
      @reload="done"
      :isNotNeedProcess="false"
    ></process-submit-dialog>
  </ele-modal>
</template>
<script>
  const defForm = {
    name: '', //名称
    type: '', //类型
    state: '', //状态
    promoterId: '', //发起人id
    promoterName: '', //发起人名称
    visitingUnits: '', //来访单位id
    visitingUnitsName: '', //来访单位名称
    numberOfVisitors: '', //来访人数
    commanderId: '', //负责人id
    commanderName: '', //负责人名称
    positionId: '', //职位id
    positionName: '', //职位名称
    phone: '', //电话
    start: '', //开始时间
    end: '', //结束
    receptionDepartmentId: [], //接待部门id
    receptionDepartmentName: '', //接待部门名称
    receptionUserId: [], //接待人id
    receptionUserName: '', //接待人名称
    costOwnerId: '', //费用归属人id
    costOwnerName: '', //归属人名称
    welcomeSign: '', //欢迎标语
    receptionProjectList: [] //接待项目
  };
  import { listOrganizations } from '@/api/system/organization';
  import { save, getById } from '@/api/marketManagem/index';
  import { mapGetters } from 'vuex';

  import modalTitle from '@/BIZComponents/modalTitle.vue';
  import { contactDetail } from '@/api/saleManage/contact';

  import deptSelect from '@/components/CommomSelect/dept-select.vue';
  import staffSelection from './staffSelection.vue';

  import dictMixins from '@/mixins/dictMixins';
  import UserList from './userList.vue';
  //客户
  import contact from '@/views/saleManage/contact/components/parentList.vue';
  //车
  import taskInfoTable from './taskInfoTable.vue';
  //用餐
  import mealList from './mealList.vue';
  //纪念品
  import souvenirList from './souvenirList.vue';
  //会议
  import conferenceList from './conferenceList.vue';
  //参观
  import companyList from './companyList.vue';
  //游览
  import visitList from './visitList.vue';
  //住宿
  import putUpList from './putUpList.vue';
  import processSubmitDialog from '@/BIZComponents/processSubmitDialog/processSubmitDialog.vue';

  export default {
    components: {
      deptSelect,
      UserList,
      contact,
      taskInfoTable,
      mealList,
      souvenirList,
      conferenceList,
      companyList,
      modalTitle,
      putUpList,
      visitList,
      staffSelection,
      processSubmitDialog
    },
    mixins: [dictMixins],
    computed: {
      ...mapGetters(['user']),
      getTimeArr() {
        let [start, end] = this.TimeArr;
        return (
          Math.ceil(
            (new Date(end).getTime() - new Date(start).getTime()) /
              1000 /
              60 /
              60 /
              24
          ) || ''
        );
      }
    },
    data() {
      return {
        dialogType: '',
        fullscreen: false,
        title: '',
        checkList: [],
        TimeArr: [],
        addOrEditDialogFlag: false,
        activeName: '',
        organizationList: [],
        form: { ...defForm },
        linkList: [],
        processSubmitDialogFlag: false,
        checkboxGroup: [
          {
            refKey: 'taskInfoTableRef',
            name: '用车'
          },
          {
            refKey: 'mealListRef',
            name: '用餐'
          },
          {
            refKey: 'putUpRef',
            name: '住宿'
          },
          {
            refKey: 'souvenirListRef',
            name: '纪念品'
          },
          {
            refKey: 'conferenceListRef',
            name: '会议'
          },
          {
            refKey: 'companyListRef',
            name: '公司参观'
          },
          {
            refKey: 'visitListRef',
            name: '景点游览'
          }
        ],
        defaultProps: {
          multiple: true,
          checkStrictly: true,
          emitPath: false,
          children: 'children',
          value: 'id',
          label: 'name'
        }
      };
    },
    mounted() {},
    created() {
      this.getListOrganizations();
    },
    methods: {
      //初始化
      async open(row = {}, type) {
        this.addOrEditDialogFlag = true;
        this.title = type == 'add' ? '新增' : '修改';
        this.dialogType = type;
        if (type !== 'add') {
          this.form = await getById(row.id);
          this.$nextTick(() => {
            this.form.receptionProjectList.forEach((item) => {
              if (
                this.$refs[item.refKey] &&
                this.$refs[item.refKey][0].putTableValue
              ) {
                this.$refs[item.refKey][0].putTableValue(item.tableList);
              }
              this.checkList.push(item.refKey);
            });
            this.activeName = this.checkList[0];
            if (this.form.start && this.form.end) {
              this.TimeArr = [this.form.start, this.form.end];
            }
          });
        } else {
          this.form.promoterName = this.user.info.name;
          this.form.promoterId = this.user.info.id;
        }
      },
      submit(data) {
        this.processSubmitDialogFlag = true;
        this.$nextTick(() => {
          let params = {
            businessId: data.id,
            businessKey: 'market_management_approve',
            formCreateUserId: data.createUserId,
            pcHandle: '/bpm/handleTask/components/marketManagem/submit.vue',
            pcView: '/bpm/handleTask/components/marketManagem/view.vue',
            variables: {
              businessCode: data.code
            }
          };
          this.$refs.processSubmitDialogRef.init(params);
        });
      },
      done() {
        this.$emit('done');
      },
      async save(type) {
        try {
          if (!this.form.name) {
            this.$message.error('主题不能为空');
            return;
          }
          if (!this.form.type) {
            this.$message.error('请选择类型');
            return;
          }
          // 表单验证通过，执行保存操作
          this.loading = true;
          await this.$nextTick(() => {
            this.form.receptionProjectList = this.form.receptionProjectList.map(
              (item) => {
                if (
                  this.$refs[item.refKey] &&
                  this.$refs[item.refKey][0].getTableValue
                ) {
                  item.tableList = this.$refs[item.refKey][0].getTableValue();
                }
                return item;
              }
            );
          });
          this.form.start = this.TimeArr[0];
          this.form.end = this.TimeArr[1];

          // return;
          save(this.form)
            .then(async (res) => {
              this.loading = false;
              this.$message.success('操作成功');
              if (type == 'sub') {
                if (this.form.id) {
                  this.submit(this.form);
                } else {
                  this.submit(await getById(res));
                }
              }
              this.cancel();
              this.$emit('done');
            })
            .catch((e) => {
              this.loading = false;
            });
        } catch (error) {
          console.log(error);
          // 表单验证未通过，不执行保存操作
        }
      },
      getValidate() {
        return Promise.all([
          new Promise((resolve, reject) => {
            this.$refs.form.validate((valid) => {
              if (!valid) {
                reject(false);
              } else {
                resolve(true);
              }
            });
          })
        ]);
      },
      getListOrganizations() {
        listOrganizations().then((list) => {
          let _list = list.filter((i) => i.name != '超级管理员');

          this.organizationList = this.$util.toTreeData({
            data: _list,
            idField: 'id',
            parentIdField: 'parentId'
          });
        });
      },
      receptionUserOpen() {
        this.$refs.staffSelectionRef.open(this.form.receptionUserId);
      },
      staffSelectionbk(data) {
        this.form.receptionUserId = data;
        this.form.receptionUserName = data.map((item) => item.name).toString();
        // console.log(data,'data')
      },
      changeCheckList() {
        this.activeName = this.checkList[0];
        this.form.receptionProjectList = this.checkboxGroup.filter((item) =>
          this.checkList.includes(item.refKey)
        );
      },
      userListOpen(key) {
        this.$refs.userListRef.open(key);
      },
      userListSuccess({ data, key }) {
        if (key == 'promoterName') {
          this.form.promoterName = data?.name;
          this.form.promoterId = data?.id;
        }

        if (key == 'costOwnerId') {
          this.form.costOwnerName = data?.name;
          this.form.costOwnerId = data?.id;
        }
      },
      contactOpen() {
        this.$refs.contactRef.open();
      },
      //客户回调
      async contactChange(data) {
        this.form.visitingUnits = data?.id;
        this.form.visitingUnitsName = data?.name;
      },

      async getLinkList(linkName, cb) {
        if (!this.form.visitingUnits) {
          cb([]);
          return;
        }
        const res = await contactDetail(this.form.visitingUnits);
        cb(
          res.linkList.map((item) => {
            return {
              value: item.linkName,
              commanderId: item.id,
              phone: item.mobilePhone,
              positionName: item.post
            };
          })
        );
      },
      linkListClick({ commanderId, phone, positionName }) {
        this.form.commanderId = commanderId;
        this.form.phone = phone;
        this.form.positionName = positionName;
      },
      receptionDepartmentIdChange() {
        this.$nextTick(() => {
          const data = this.$refs.deptRef.getCheckedNodes();
          console.log(data, 'data');
          this.form.receptionDepartmentName = data
            .map((item) => item.label)
            .toString();
        });
      },

      //关闭弹窗
      cancel() {
        this.addOrEditDialogFlag = false;
        this.checkList = [];
        this.TimeArr = [];
        this.form = {
          ...defForm
        };
      }
    }
  };
</script>
<style scoped lang="scss">
  .borNone {
    :deep(.el-input__inner) {
      border-color: #fff;
    }
  }

  :deep(.el-input-group__append) {
    border-left: 1px solid var(--border-color-base);
  }
  :deep(.el-descriptions--medium.is-bordered .el-descriptions-item__cell) {
    padding: 2px;
  }
  :deep(.el-descriptions-item__label) {
    width: 130px;
    color: #333;
    text-align: center !important;
  }
  :deep(.el-form-box .el-form-item) {
    margin-bottom: 0 !important;
  }
  :deep(.el-descriptions__header) {
    margin-top: 10px;
    margin-bottom: 10px;
  }
  :deep(.el-textarea__inner) {
    border: none;
  }
  :deep(.el-descriptions__title) {
    color: #1890ff;
  }
  :deep(.el-descriptions-item__content) {
    width: 285px;
  }
  :deep(.el-descriptions) {
    td:nth-of-type(1) {
      width: 400px;
    }
  }
  :deep(.el-tabs__item) {
    font-size: 16px;
    font-weight: 800;
  }
</style>
