<template>
  <div class="kmc">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
      <el-row>
        <el-col :span="6">
          <el-form-item label="是否显示KOL入口" prop="showStatus">
            <el-radio-group v-model="ruleForm.showStatus">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="入口文案" prop="desc">
            <el-input v-model="ruleForm.desc" placeholder="请输入入口文案，最长6个字"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-button type="primary" @click="handleAdd">添加</el-button>
        <span class="des">*说明：添加和移除kol后，需点击页面的保存按钮，方可生效</span>
      </el-row>
    </el-form>
    <el-row class="table-content">
      <kol-table :tableData="tableData" ref="kolTable"></kol-table>
      <el-row class="save-btn">
        <el-button type="primary" @click="handleSave">保存</el-button>
      </el-row>
    </el-row>
    <el-dialog :title="dialogTitle"
               :visible.sync="addFormVisible"
               :close-on-press-escape="false"
               :close-on-click-modal="false">
      <el-form ref="addForm"
               :rules="rules2"
               :model="addForm"
               label-width="150px"
               label-suffix=":"
               size="small">
        <el-form-item label="姓名" prop="name">
          <el-select v-model="addForm.name"
                     filterable
                     remote
                     placeholder="请输入专家姓名或医院名称,多个关键字用空格隔开"
                     clearable
                     style="width: 100%;"
                     :remote-method="remoteMethod"
                     @change="nameChange"
                     @visible-change="noSelectHand">
            <el-option
                v-for="item in expertList"
                :key="item.userId"
                :label="item.option"
                :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button size="small" type="primary" @click="submitForm('addForm')">确 定</el-button>
        <el-button size="small" @click="addFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import kolTable from './kol-component/kolTable'
import { getExpertList, getExperNametList, saveKolConfig } from '@/utils/yqrange/rangeApi'
import { openLoading, closeLoading } from "@/utils/utils";

export default {
  components: {
    kolTable
  },
  props: {
    circleId: {
      type: Number | String,
      default: null
    }
  },
  data() {
    return {
      ruleForm: {
        desc: '',
        showStatus: 0
      },
      dialogTitle: '添加KOL',
      addFormVisible: false,
      addForm: {
        name: '',
      },
      nameList: [],
      expertList: [],
      selectExpertItem: {},
      rules: {
        showStatus: [
          { required: true, message: '请选择是否展示入口', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '请输入入口文案', trigger: 'blur' },
          { max: 6, message: '入口文案长度不能多于6个字符', trigger: 'blur' }
        ]
      },
      rules2: {
        name: [
          { required: true, message: '请输入专家姓名或医院名称,多个关键字用空格隔开', trigger: 'change' },
        ],
      },
      tableData: []
    }
  },
  mounted() {
    this.initData();
  },
  methods: {
    initData() {
      getExpertList(this.circleId).then(res => {
        if (res.code == '000000') {
          // console.log('获取kol配置',res.data);
          const { kolConfig, kolRecordList } = res.data;
          this.ruleForm = kolConfig;
          this.tableData = kolRecordList;
        }
      }).catch(err => {
        console.log('网络出现点儿问题，稍后重试')
      })
    },
    handleAdd() {
      this.addFormVisible = true;
      if (this.$refs['addForm']) {
        this.$refs['addForm'].resetFields();
      }
      this.expertList = [];
      this.selectExpertItem = {};
    },
    handleSave() {
      // 排序和删除后的table数据
      let newTableData = this.$refs.kolTable.getNewData()
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // console.log('form校验通过')
          let param = {
            circleId: this.circleId,
            kolConfig: this.ruleForm,
            kolRecordList: this.tableData
          }
          openLoading(this);
          saveKolConfig(param).then(res => {
            closeLoading(this);
            if (res.code == '000000') {
              console.log('保存成功',res)
              this.$message.success('保存成功');
              this.initData();
            }
          }).catch(err => {
            console.log('网络出现点儿问题，稍后重试')
          })
        }
      });
    },
    deleteItem(index) {
      this.tableData.splice(index, 1);
    },
    remoteMethod(val){
      if (val) {
        getExperNametList(this.circleId, val).then(res => {
          if (res.code == '000000') {
            this.expertList = res.data;
          }else {
            this.expertList = [];
          }
        }).catch(err => {
          console.log('网络出现点儿问题，稍后重试')
        })
      }else {
        this.expertList = [];
      }
    },
    nameChange(val) {
      this.selectExpertItem = {};
      if (val) {
        this.expertList.map((item,index) => {
          if(val == item.userId){
            this.selectExpertItem = item.kolRecord;
          }
        })
      }
    },
    noSelectHand(val) {
      if (!val && !this.addForm.name) {
        this.expertList = [];
        this.selectExpertItem = {};
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let len = this.tableData.length;

          for (let i=0; i< len; i++) {
            if (this.addForm.name == this.tableData[i].doctorId) {
              this.$message.warning('当前选择的专家已经被添加过，请选择其他专家！');
              return
            }
          }

          this.tableData.push({
            ...this.selectExpertItem,
            seq: len + 1,
          });
          this.expertList = [];
          this.addFormVisible = false;

        }
      });
    },
  },
}
</script>

<style lang="scss" scoped>
.des {
  font-size: 12px;
  color: #777;
  margin-left: 40px;
}
.table-content {
  margin-top: 15px;
}
.save-btn {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
