<template>
  <div>
    <el-dialog
      v-model="visible"
      :z-index="99"
      :title="title"
      width="850px"
      align-center
    >
      <div class="barbox" style="margin-top: -10px; margin-bottom: 20px">
        <div class="bar"></div>
        <div class="name">动态信息</div>
      </div>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-row class="row" style="width: 500px">
            <el-select
              :disabled="method === 'edit'"
              v-model="dynamic_type"
              placeholder="请选择白名单维度"
              size="large"
              style="width: 240px"
              @change="changeDynamicType"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-button type="success" @click="add" v-if="method == 'view'"
              >新增</el-button
            >
          </el-row>
          <el-table
            :data="method=='edit'?select:cur_select"
            border
            style="width: 500px; margin-top: 20px"
          >
            <el-table-column prop="item_value" label="动态名称" width="240">
              <template #default="scope">
                <el-select
                  v-if="dynamic_type == 'area'"
                  v-model="scope.row.item_value"
                  placeholder="请选择区域"
                  size="large"
                  style="width: 200px"
                >
                  <el-option
                    v-for="item in provinceData"
                    :key="item"
                    :disabled="formatSelect.includes(item) || formatBeforeSelect.includes(item)"
                    :label="item"
                    :value="item"
                  />
                </el-select>
                <el-select
                  v-if="dynamic_type == 'level'"
                  v-model="scope.row.item_value"
                  placeholder="请选择医院等级"
                  size="large"
                  style="width: 200px"
                >
                  <el-option
                    v-for="item in levelData"
                    :key="item"
                    :disabled="formatSelect.includes(item) || formatBeforeSelect.includes(item)"
                    :label="item"
                    :value="item"
                  />
                </el-select>
                <el-select
                  v-if="dynamic_type == 'title'"
                  v-model="scope.row.item_value"
                  placeholder="请选择职称"
                  size="large"
                  style="width: 200px"
                >
                  <el-option
                    v-for="item in titleData"
                    :key="item"
                    :label="item"
                    :disabled="formatSelect.includes(item) || formatBeforeSelect.includes(item)"
                    :value="item"
                  />
                </el-select>
                <el-select
                  v-if="dynamic_type == 'department'"
                  v-model="scope.row.item_value"
                  placeholder="请选择科室"
                  size="large"
                  style="width: 200px"
                >
                  <el-option
                    v-for="item in departmentData"
                    :key="item.id"
                    :disabled="formatSelect.includes(item) || formatBeforeSelect.includes(item)"
                    :label="item.name"
                    :value="item.name"
                  />
                </el-select>
                <!-- <el-input v-model="scope.row.item_value" style="width: 200px" placeholder="请输入动态名称" /> -->
              </template>
            </el-table-column>
            <!-- <el-table-column prop="status" label="项目状态"  width="100">
                    <template #default="scope">
                       <span>{{scope.row.status==1?'正常':'禁用'}}</span>
                    </template>
                </el-table-column> -->
            <!-- <el-table-column prop="created_at" label="创建时间"  width="165" />-->
            <el-table-column label="操作" fixed="right">
              <template #default="scope">
                <!-- <el-button size="small" type="default" @click="handelEdit(scope.row.white_dynamic_id)">编辑</el-button> -->
                <el-button
                  size="small"
                  type="danger"
                  @click="handelDel(scope.$index)"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="submit"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- <dynamicDetail ref="dynamicDetailRef"></dynamicDetail> -->
  </div>
</template>
<script setup>
import { onBeforeMount, reactive, ref, nextTick, computed, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import userApi from "../api/user";
import { ElMessage } from "element-plus";
import {
  formatOrderStatus,
  formatRefundStatus,
  formatDate,
} from "../utils/format";
const dynamic_type = ref("");
const dynamicDetailRef = ref(null);
const select = ref([]);
const formatBeforeSelect = ref([]);
const cur_select = ref([]);
const formatSelect=ref([]);
const listData = ref([]);
const project_platform_id = ref("");
const options = ref([
  { value: "area", label: "省份" },
  { value: "level", label: "医院等级" },
  { value: "title", label: "职称" },
  { value: "department", label: "科室" },
]);
const method = ref("");
const visible = ref(false);
const title = ref("");
const dialogVisible = ref(false);
watch(cur_select,(newVal,oldValue)=>{
  if(newVal){
    formatSelect.value=newVal.map(item=>item.item_value);
  }
  
},{
  deep:true
})
watch(select,(newVal,oldValue)=>{
  if(newVal){
    formatBeforeSelect.value=newVal.map(item=>item.item_value);
    console.log(formatBeforeSelect.value)
  }

},{
  deep:true
})
const props = defineProps({
  white_dynamic_id: {
    type: String,
    default: "",
  },
  provinceData: {
    type: Array,
    default: () => [],
  },
  titleData: {
    type: Array,
    default: () => [],
  },
  levelData: {
    type: Array,
    default: () => [],
  },
  departmentData: {
    type: Array,
    default: () => [],
  },
});
const emit = defineEmits(["refreshList"]);
const changeDynamicType = (value) => {
    select.value = [];
    formatSelect.value=[];
    for (let i = 0; i < listData.value.length; i++) {
      if (listData.value[i].dynamic_type == value) {
        select.value = listData.value[i].project_platform_dynamic_item;
        console.log(select.value);
        break;
      }
    }
  
};
const add = () => {
  cur_select.value.push({
    item_value: "",
  });
};
const getList = async () => {
  const { data, code } = await userApi.getDynamicList({
    project_platform_id: project_platform_id.value
  });
  if (code == 200) {
    listData.value = data;
    // if (data.length > 0) {
    //   dynamic_type.value = data[0].dynamic_type;
    //   changeDynamicType(data[0].dynamic_type);
    // }
  }
};

const handelDel = (index) => {
  method.value=='view'?cur_select.value.splice(index, 1):select.value.splice(index, 1);
};
const handleAdd = () => {
  let postData = {
    project_platform_id: project_platform_id.value,
    status: 1,
    dynamic_type: dynamic_type.value,
    project_platform_dynamic_item: cur_select.value,
  };
  for (let i = 0; i < cur_select.value.length; i++) {
    if (!cur_select.value[i].item_value) {
         ElMessage.error("动态名称填写完整才能保存!");
         return false
    }
  }
  userApi.addDynamic(postData).then((res) => {
    let result = res;
    if (result.code == 200) {
      ElMessage.success("添加成功");
      visible.value = false;
      emit("refreshList");
    }
  });
};
const handleEdit = () => {
  //console.log(select.value);
  if( select.value.length==0 ) return ElMessage.error("至少有一个动态")
  let project_platform_dynamic_item=[]
  if(method.value === "view" && formatBeforeSelect.value.length>0){
     project_platform_dynamic_item=cur_select.value.concat(select.value)
   }else{
    project_platform_dynamic_item=select.value
   }
  let postData = {
    project_platform_id: project_platform_id.value,
    status: 1,
    dynamic_type: dynamic_type.value,
    project_platform_dynamic_item: project_platform_dynamic_item,
  };
  for (let i = 0; i < project_platform_dynamic_item.length; i++) {
    if (!project_platform_dynamic_item.item_value) {
         ElMessage.error("动态名称填写完整才能保存!");
         return false
    }
  }

  userApi.updateDynamic(props.white_dynamic_id, postData).then((res) => {
    let result = res;
    if (result.code == 200) {
      ElMessage.success("修改成功");
      visible.value = false;
      emit("refreshList");
    }
  });
};
const submit = async () => {
  if(formatBeforeSelect.value.length>0) {
    handleEdit()
  }else{
    handleAdd()
  }
  //method.value === "edit" ? handleEdit() : handleAdd();
};
const init = (id, type, dynamicType) => {
  select.value = [];
  visible.value = true;
  project_platform_id.value = id;
  method.value = type;
  if (method.value === "edit") {
    title.value = "编辑动态";
  } else if (method.value === "view") {
    title.value = "新建动态";
    cur_select.value = [];
  }

  nextTick(() => {
    if (method.value === "edit") {
      getList().then(() => {
        dynamic_type.value = dynamicType;
        changeDynamicType(dynamicType);
      });
    }else{
      getList().then(() => {
        dynamic_type.value = 'area';
        changeDynamicType(dynamicType);
      });
      
    }
  });
};
defineExpose({
  init,
});
</script>

<style lang="scss" scoped>
.row {
  align-items: center;
  justify-content: space-between;
}
.demo-form-inline {
  ::v-deep .el-radio--large {
    height: 30px;
  }
}
.barbox {
  margin: 10px 0;
  display: flex;
  align-items: center;

  .bar {
    width: 4px;
    height: 25px;
    background: var(--el-color-primary);
  }

  .name {
    margin-left: 8px;
    font-size: 16px;
  }
}
</style>