<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8" v-if="this.source == 'BoDetails' ? this.bo.winningState == 0 ? true : false : true">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-if="this.boAuthority.boAuthority.behaviorAdd"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col> -->
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-table v-loading="loading" :data="behaviorList" @selection-change="handleSelectionChange">
      <el-table-column type="index" label="序号" width="55" align="center"/>
      <el-table-column label="负责人" align="center" prop="staffName" />
      <el-table-column label="行动日期" align="center" prop="time" />
      <el-form-item label="行动日期" prop="time">
        <el-date-picker clearable
          v-model="form.time"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择行动日期">
        </el-date-picker>
      </el-form-item>
      <el-table-column label="联系人" align="center" prop="linkmanName" />
      <el-table-column label="拜访效果" align="center" prop="result" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mk_bo_behavior_res" :value="scope.row.result"/>
        </template>
      </el-table-column>
      <el-table-column label="是否上级协助" align="center" prop="assist" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.assist"/>
        </template>
      </el-table-column>
      <el-table-column label="协助内容" align="center" prop="assistContent" />
      <el-table-column label="洽谈内容" align="center" prop="content" />

      <el-table-column label="任务编码" align="center" prop="taskCode" v-if="source == 'Behavior'"/>
      <el-table-column label="行动类型" align="center" prop="type" v-if="source == 'Behavior'">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mk_bo_behavior_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="客户" align="center" prop="customerName" v-if="source == 'Behavior'"/>
      <el-table-column label="拜访目的" align="center" prop="purpose" v-if="source == 'Behavior'">
        <template slot-scope="scope">
            <dict-tag :options="dict.type.mk_bo_behavior_goal" :value="scope.row.purpose"/>
        </template>
      </el-table-column>
      <el-table-column label="销售组织" align="center" prop="salesOrgName" v-if="source == 'Behavior'"/>
      <el-table-column label="部门" align="center" prop="deptName" v-if="source == 'Behavior'"/>

      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width">
      <!-- <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width" v-if="this.source == 'BoDetails' ? this.bo.winningState == 0 ? true : false : true"> -->
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            :disabled="!boAuthority.boAuthority.behaviorEdit"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleBrowse(scope.row)"
            :disabled="!boAuthority.boAuthority.behaviorView"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            :disabled="!boAuthority.boAuthority.behaviorDel"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改行动对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :disabled="this.operatingState == 'Browse'">
        <el-divider content-position="left">
          <dev style="width: 50px; height: 40px; font-size: 18px">基本信息</dev>
        </el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="任务" prop="taskId" v-if="!(this.source == 'BoDetails')">
              <el-input v-model="form.taskCode" placeholder="请输入任务" :disabled="this.source == 'TaskList'"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="行动类型" prop="type">
              <el-select v-model="form.type" placeholder="请输入行动类型">
                <el-option
                  v-for="dict in dict.type.mk_bo_behavior_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="行动日期" prop="time">
              <el-date-picker clearable
                v-model="form.time"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择行动日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="客户" prop="customerName">
              <el-input v-model="form.customerName" placeholder="请输入客户" disabled="this.source == 'BoDetails' || this.source == 'TaskList'"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人" prop="linkmanName">
              <el-input v-model="form.linkmanName" placeholder="请输入联系人" >
                <el-button slot="append" icon="el-icon-more" @click="refereContact"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="拜访目的" prop="purpose">
              <el-select v-model="form.purpose" placeholder="请输入拜访目的">
                <el-option
                  v-for="dict in dict.type.mk_bo_behavior_goal"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col  :span="8">
            <el-form-item label="拜访效果" prop="result">
              <el-select v-model="form.result" placeholder="请输入拜访效果">
                <el-option
                  v-for="dict in dict.type.mk_bo_behavior_res"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col  :span="8">
            <el-form-item label="是否上级协助" prop="assist">
              <el-select v-model="form.assist" placeholder="请输入是否上级协助">
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col  :span="8">
            <el-form-item label="协助内容" prop="assistContent" v-show="form.assist == 'Y'" :rules="form.assist == 'Y' ? rules.assistContent : [{require: false}]">
              <el-input v-model="form.assistContent" placeholder="请输入协助内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="销售区域" prop="marketingAreaName">
              <el-input v-model="form.marketingAreaName" placeholder="请输入销售区域">
                <el-button slot="append" icon="el-icon-more" @click="refereSaleaea"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col  :span="8">
            <el-form-item label="销售组织" prop="salesOrgName">
              <el-input v-model="form.salesOrgName" placeholder="请输入销售组织" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col  :span="8">
             <el-form-item label="部门" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col  :span="8">
            <el-form-item label="负责人" prop="staffName">
              <el-input v-model="form.staffName" placeholder="请输入负责人" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">
          <dev style="width: 50px; height: 40px; font-size: 18px">跟进内容</dev>
        </el-divider>
        <el-form-item label="内容" prop="content" >
          <el-input
            type="textarea"
            :rows="2"
            maxlength=900
            placeholder="填写提示：今天拜访了谁，收集了什么述求，达成了什么结果，下一步计划。"
            autosize
            v-model="form.content">
          </el-input>
        </el-form-item>
        <el-divider content-position="left">
          <dev style="width: 50px; height: 40px; font-size: 18px">照片信息</dev>
        </el-divider>

        <el-upload
          action="actionUrl"
          list-type="picture-card"
          :on-change="uploadPic"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :auto-upload="false"
          :file-list="fileList"
          >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
        
        <div class="md-auditInfo">
          <el-divider content-position="left">
            <dev style="width: 50px; height: 40px; font-size: 18px">其它信息</dev>
          </el-divider>
          <el-form :inline="true" label-position="right" :model="form">
            <el-row>
              <el-col :span="6">
                <el-form-item label="创建人">
                  <el-input v-model="form.createByName" size="small" readonly></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="创建时间">
                  <el-input v-model="form.createTime" size="small" readonly></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="修改人">
                  <el-input v-model="form.updateByName" size="small" readonly></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="修改时间">
                  <el-input v-model="form.updateTime" size="small" readonly></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="this.operatingState != 'Browse'" :disabled="submitButtonEditStatus">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 联系人参照 -->
    <ContactRef
      ref="contactSelect"
      @doSubmit="contactSelectionsToInput"
      :single="true"
      :outerQueryParams="this.bo"
    />
    <!-- 销售区域参照 -->
    <SaleaeaRef
      ref="saleaeaSelect"
      @doSubmit="saleaeaSelectionsToInput"
      :single="true"
    />
  </div>
</template>

<script>
import { listBehavior, getBehavior, delBehavior, addBehavior, updateBehavior,addPicture } from "@/api/business/spd/bo/behavior";
import ContactRef from '@/views/business/spd/bo/refer/contact/index.vue';
import SaleaeaRef from '@/views/business/spd/bo/refer/saleaea/index.vue';

export default {
  name: "BehaviorList",
  props:["source","bo","boAuthority"],
  dicts: ['mk_bo_behavior_res','mk_bo_behavior_type','sys_yes_no','mk_bo_behavior_goal'],
  components: {ContactRef,SaleaeaRef},
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      actionUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址,
      fileList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 行动表格数据
      behaviorList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bo: null,
        boStage: null,
        boName: null,
        task: null,
        taskCode: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        type: [
          { required: true, message: "行动类型不能为空", trigger: "blur" }
        ],
        time: [
          { required: true, message: "行动日期不能为空", trigger: "blur" }
        ],
        customerName: [
          { required: true, message: "客户不能为空", trigger: "blur" }
        ],
        linkmanName: [
          { required: true, message: "联系人不能为空", trigger: "blur" }
        ],
        purpose: [
          { required: true, message: "拜访目的不能为空", trigger: "blur" }
        ],
        assist: [
          { required: true, message: "是否需要上级协助不能为空", trigger: "blur" }
        ],
        assistContent: [
          { required: true, message: "协助内容不能为空", trigger: "blur" }
        ],
        staffName: [
          { required: true, message: "负责人不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "洽谈内容不能为空", trigger: "blur" }
        ],
        result: [
          { required: true, message: "拜访效果不能为空", trigger: "blur" }
        ],
      },
      //当前操作状态
      operatingState: '',
      //确定按钮是否可点
      submitButtonEditStatus:false,
    };
  },
  created() {
    console.log('this.boAuthority',this.boAuthority);
    if(this.source == 'Behavior'){
      this.queryParams = this.bo;
    }
    if(this.source == 'BoDetails'){
      this.queryParams.bo = this.bo.id;
      this.queryParams.boStage = this.bo.boStage;
      let params = {"post":this.boAuthority.post};
      this.queryParams.params = params;
    }
    if(this.source == 'TaskList'){
      this.queryParams.taskCode = this.bo.code;
      console.log("this.bo", this.bo);
    }
    this.getList();
  },
  methods: {
    uploadPic(file, fileList) {
      this.fileList = fileList
      console.log('this.fileList',this.fileList);
    },
    handleRemove(file) {
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        console.log(this.form.photos.split(','));
      });
    },
    /** 查询行动列表 */
    getList() {
      this.loading = true;
      listBehavior(this.queryParams).then(response => {
        this.behaviorList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        bo: null,
        boName: null,
        task: null,
        taskCode: null,
        type: null,
        time: null,
        customer: null,
        customerName: null,
        linkman: null,
        linkmanName: null,
        purpose: null,
        result: null,
        assist: null,
        assistContent: null,
        marketingArea: null,
        marketingAreaName: null,
        salesOrg: null,
        salesOrgName: null,
        dept: null,
        deptName: null,
        staff: null,
        staffName: null,
        content: null,
        tenantId: null,
        revision: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.fileList = [];
      this.reset();
      this.operatingState = "Insert";
      //新增行动设置默认值
      if(this.source == 'BoDetails'){
        this.queryParams.bo = this.bo.id;
        this.form.bo = this.bo.id;
        this.form.boName = this.bo.boName;
        this.form.boStage = this.bo.boStage;
        this.form.customer = this.bo.customer;
        this.form.customerName = this.bo.customerName;
      }
      if(this.source == 'TaskList'){
        this.form.bo = this.bo.bo;
        this.form.boName = this.bo.boName;
        this.form.boStage = this.bo.boStage;
        this.form.customer = this.bo.customer;
        this.form.customerName = this.bo.customerName;
        this.form.task = this.bo.id;
        this.form.taskCode = this.bo.code;
      }
      this.form.type = '0';
      this.form.staff = this.$store.state.user.id;
      this.form.staffName = this.$store.state.user.nickName;
      this.form.dept = this.$store.state.user.deptId;
      this.form.deptName = this.$store.state.user.deptName;
      this.form.salesOrg = this.$store.state.user.orgId;
      this.form.salesOrgName = this.$store.state.user.orgName;
      this.form.time = new Date();
      this.open = true;
      this.title = "添加行动";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.operatingState = "Update";
      const id = row.id || this.ids
      getBehavior(id).then(response => {
        this.form = response.data;
        
        this.open = true;
        this.title = "修改行动";
      });
    },
    /** 查看按钮操作 */
    handleBrowse(row) {
      this.reset();
      const id = row.id || this.ids
      getBehavior(id).then(response => {
        this.form = response.data;
        this.fileList = this.form.behaviorPs;
        console.log('this.fileList',this.fileList);
        this.open = true;
        this.operatingState = "Browse";
        this.title = "基础信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.submitButtonEditStatus = true;
      this.$refs["form"].validate(valid => {
        if (valid) {
          let formData = new FormData();
          formData.append("behavior", new Blob([JSON.stringify(this.form)], {type: "application/json"}));
          if(this.fileList.length < 1){
            formData.append('files', null);
          }else{
            this.fileList.forEach(el => {
              formData.append('files', el.raw);
            })
          }
          if (this.form.id != null) {
            updateBehavior(formData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.submitButtonEditStatus = false;
            });
          } else {
            addBehavior(formData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.submitButtonEditStatus = false;
            });
          }
        }else{
          this.submitButtonEditStatus = false;
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除行动编号为"' + ids + '"的数据项？').then(function() {
        return delBehavior(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 触发联系人参照列表
    refereContact() {
      this.$refs.contactSelect.init()
    },
    //联系人参照列表选择后
    contactSelectionsToInput (selections) {
      console.log('selections',selections);
      this.form.linkman = selections[0].id;
      this.form.linkmanName = selections[0].name;
    },
    // 触发销售区域参照列表
    refereSaleaea() {
      this.$refs.saleaeaSelect.init()
    },
    //销售区域参照列表选择后
    saleaeaSelectionsToInput (selections) {
      this.form.marketingArea = selections[0].id;
      this.form.marketingAreaName = selections[0].name;
    },
  }
};
</script>



<style scoped>
.md-content >>> .el-form-item {
  margin-bottom: 10px;
}

.md-content >>> .el-tabs--border-card > .el-tabs__content {
  padding-bottom: 8px;
}

.md-content .md-auditInfo >>> .el-form-item {
  margin-bottom: 0px;
}

.md-main >>> .el-form-item,
.md-vice >>> .el-form-item {
  width: 100%;
  box-sizing: border-box;
}

.md-main >>> .el-form-item__label,
.md-vice >>> .el-form-item__label {
  width: 40%;
}

.md-main >>> .el-form-item__content,
.md-md-vice >>> .el-form-item__content {
  width: 60%;
}

.md-content >>> .el-form-item__label {
  font-weight: normal;
  /* text-align: left;
  width: 28%; */
  white-space: nowrap;
  /* IE6 需要定义宽度 */
  overflow: hidden;

  -o-text-overflow: ellipsis;
  /* Opera */
  text-overflow: ellipsis;
  /* IE, Safari (WebKit) */
  /* -moz-binding: url('ellipsis.xml#ellipsis'); */
  /* Firefox */
}

.md-main >>> .material-table {
  height: 100%;
}

.md-vice >>> .material-table {
  height: 140px;
  overflow-y: auto;
  overflow-x: auto;
}
</style>
