<template>
  <div class="container">
    <!-- 单据弹窗 -->
    <ele-modal
      :title="title"
      :before-close="handleClose"
      custom-class="ele-dialog-form long-dialog-form"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :append-to-body="true"
      :maxable="true"
      :resizable="true"
      width="50%"
    >
      <el-form
        label-width="100px"
        ref="form"
        :model="form"
        :rules="rules"
        style="margin-top: 30px; padding-right: 20px"
      >
        <el-form-item label="客户联系人" prop="linkId">
          <el-select
            v-model="form.linkId"
            multiple
            placeholder="请选择"
            style="width: 100%"
            @change="onchangeLink"
          >
            <el-option
              v-for="item in linkNameOptions"
              :key="item.id"
              :label="item.linkName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="跟进时间" prop="followupTime">
          <el-date-picker
            v-model="form.followupTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="结束时间"
            type="datetime"
            style="width: 100%"
            class="filter-item"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="跟进阶段" prop="stageCode">
          <DictSelection dictName="商机阶段" clearable v-model="form.stageCode">
          </DictSelection>
        </el-form-item>
        <el-form-item label="跟进内容" prop="content">
          <el-input
            placeholder="请输入"
            type="textarea"
            v-model="form.content"
            maxlength="500"
          ></el-input>
        </el-form-item>
        <el-form-item label="达成共识" prop="agreement">
          <el-input
            placeholder="请输入"
            type="textarea"
            v-model="form.agreement"
            maxlength="500"
          ></el-input>
        </el-form-item>

        <el-form-item label="下一步计划" prop="nextPlan">
          <el-input
            placeholder="请输入"
            v-model="form.nextPlan"
            type="textarea"
            maxlength="300"
          ></el-input>
        </el-form-item>
        <el-form-item prop="files" label="附件">
          <!-- <fileUpload
            v-model="form.files"
            module="main"
            :showLib="false"
            :limit="5"
          />  -->
          <fileMain v-model="form.files"></fileMain>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleClose">关 闭</el-button>
        <el-button size="small" @click="sumbit" type="primary" v-click-once
          >确 认</el-button
        >
      </div>
    </ele-modal>
  </div>
</template>
<script>
  import dictMixins from '@/mixins/dictMixins';
  import { copyObj } from '@/utils/util';
  import { deepClone } from '@/utils/index';
  // import fileMain from '@/components/upload/fileUpload';

  import {
    UpdateInformation,
    addInformation,
    getcontactlink
  } from '@/api/saleManage/businessFollow';
  export default {
    mixins: [dictMixins],
    components: {
      // fileUpload
    },
    data() {
      let formDef = {
        agreement: '',
        contactId: '',
        content: '',
        followupTime: '',
        linkId: '',
        linkName: '',
        nextPlan: '',
        opportunityId: '',
        stageCode: '',
        files: []
      };

      return {
        dialogVisible: false,
        currentDetail: {}, //选择的客户信息
        linkNameOptions: [],
        title: '',
        row: {},
        activeName: 'base',
        formDef,
        form: copyObj(formDef),
        rules: {
          content: [
            { required: true, message: '请输入跟进内容', trigger: 'blur' }
          ],
          followupTime: [
            { required: true, message: '请选择跟进时间', trigger: 'change' }
          ],
          stageCode: [
            { required: true, message: '请选择跟进阶段', trigger: 'change' }
          ],

          linkName: [
            {
              required: true,
              message: '请选择客户联系人名称',
              trigger: 'change'
            }
          ]
        },

        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false
      };
    },
    created() {},
    methods: {
      //更改弹框状态
      async open(type, row, currentDetail) {
        this.title = type === 'add' ? '新增' : '修改';
        this.currentDetail = currentDetail;
        this.row = copyObj(row);
        this.dialogVisible = true;
        this.getInfo();
        if (type == 'add') {
          this.isUpdate = false;
        } else {
          this.isUpdate = true;
          this.row.linkId =
            (this.row.linkId && this.row.linkId.split(',')) || [];
          this.form = this.row;
        }
      },

      //表单验证
      getValidate() {
        return new Promise((resolve, reject) => {
          this.$refs.form.validate((valid) => {
            if (!valid) {
              reject(false);
            } else {
              resolve(true);
            }
          });
        });
      },

      //初始数据
      async getInfo() {
        const data = await getcontactlink({
          contactId: this.currentDetail?.contactId
        });
        if (data && data?.length) {
          this.linkNameOptions = data;
        }
      },

      //选择下拉框
      onchangeLink(selectedOptions) {
        const selectedLabels = selectedOptions
          .map((optionId) => {
            const option = this.linkNameOptions.find(
              (opt) => opt.id === optionId
            );
            return option ? option.linkName : '';
          })
          .join(',');
        this.form.linkName = selectedLabels;
      },

      //保存
      async sumbit() {
        try {
          await this.getValidate();
          // 表单验证通过，执行保存操作
          this.loading = true;

          if (!this.isUpdate) {
            delete this.form.id;
          }
          let _stageName = this.getDictValue('商机阶段', this.form.stageCode);
          let params = deepClone(this.form);
          let { contactId, id } = this.currentDetail;
          params = Object.assign({}, params, {
            contactId: contactId,
            opportunityId: id,
            linkId: params?.linkId?.join(',') || '',
            stageName: _stageName,
            files: this.form.files || []
          });
          if (this.isUpdate) {
            UpdateInformation(params)
              .then((res) => {
                this.loading = false;
                this.$message.success('修改成功');
                this.cancel();
                this.$emit('done');
              })
              .catch((e) => {
                //this.loading = false;
              });
          } else {
            addInformation(params)
              .then((res) => {
                this.loading = false;
                this.$message.success('新增成功');
                this.cancel();
                this.$emit('done');
              })
              .catch((e) => {
                //this.loading = false;
              });
          }
        } catch (error) {
          console.log(error);
          // 表单验证未通过，不执行保存操作
        }
      },
      cancel() {
        this.$nextTick(() => {
          // 关闭后，销毁所有的表单数据
          this.$refs['form'] && this.$refs['form'].resetFields();
          (this.form = copyObj(this.formDef)), (this.dialogVisible = false);
        });
      },
      handleClose() {
        this.cancel();
      }
    }
  };
</script>

<style lang="scss" scoped>
  .container {
    padding: 10px 0;
  }
</style>
