<template>
  <div>
    <el-card>
      <div slot="header">单位分组</div>
      <!--分组信息-->
      <div style="display: flex;">
        <div :style="'display: block;width:' + (window.pageWidth - 45 - 110) + 'px;'">
          <div style="display: flex">
            <div>
              <span>体检单位：</span>
              <el-select
                v-model="customerOrgId"
                placeholder="请选择体检单位"
                filterable :filter-method="filterMethod" default-first-option
                clearable @clear="customerOrg = deepCopy(customerOrgAll)"
                style="margin-left: 10px"
                @change="changeCustomerOrg"
                size="small"
              >
                <el-option
                  v-for="item in customerOrg"
                  :key="item.id"
                  :label="item.displayName"
                  :value="item.id"
                >
                {{ item.displayName }}
                </el-option>
              </el-select>
            </div>
            <div style="margin-left: 20px">
              <span>单位体检次数：</span>
              <el-select
                v-model="customerOrgRegister"
                placeholder="次数"
                style="width: 60px; margin-left: 10px"
                size="small"
                @change="changeTimes"
                value-key="id"
              >
                <el-option
                  v-for="item in customerOrgRegisterList"
                  :key="item.id"
                  :label="item.medicalTimes"
                  :value="item"
                />
              </el-select>
            </div>
          </div>
          <div>
            <el-table
              :data="customerOrgGroups" ref="customerOrgGroups"
              style="margin-top: 2px"
              row-key="id"
              border
              height="240px"
              size="small" 
              highlight-current-row :row-class-name="handleRowClassName" 
              @row-click="rowClick"
            >
              <el-table-column
                type="index"
                label="序号"
                min-width="50"
                align="center"
              />
              <el-table-column prop="displayName" label="名称" min-width="150" />
              <el-table-column
                prop="price"
                label="价格"
                min-width="60"
                align="center"
              />
              <el-table-column
                prop="forSexId"
                label="适用性别"
                min-width="60"
                align="center"
              >
                <template slot-scope="scope">
                  {{ dddw(dict.forSex, "id", scope.row.forSexId, "displayName") }}
                </template>
              </el-table-column>
              <el-table-column
                prop="maritalStatusId"
                label="适用婚姻状况"
                min-width="80"
                align="center"
              >
                <template slot-scope="scope">
                  {{
                    dddw(
                      dict.forMaritalStatus,
                      "id",
                      scope.row.maritalStatusId,
                      "displayName"
                    )
                  }}
                </template>
              </el-table-column>
              <el-table-column
                prop="creatorName"
                label="创建者"
                min-width="60"
                align="center"
              />
              <el-table-column label="创建时间" min-width="150" align="center">
                <template slot-scope="scope">
                  {{
                    scope.row.creationTime
                      ? moment(scope.row.creationTime).format("yyyy-MM-DD HH:mm:ss")
                      : ""
                  }}
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template>
                  <el-tag
                    class="move"
                    style="cursor: move; margin-left: 15px"
                    draggable="true"
                  >
                    <i class="el-icon-d-caret" style="width: 1rem; height: 1rem"></i>
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <!--按钮-->
        <div style="display: block;margin-left: 10px;">
          <div style="margin-top: 30px;">      
            <el-button class="btnClass"  @click="btnAdd">新增</el-button>
          </div>
          <div>
            <el-button class="btnClass" @click="btnEdit" >编辑</el-button> 
          </div>
          <div>        
            <el-button class="btnClass" @click="btnDel" >删除</el-button> 
          </div>
          <div>         
            <el-button class="btnClass" @click="btnSetTop" >置顶</el-button> 
          </div>
          <div>         
            <el-button class="btnClass" @click="btnSetBottom" >置低</el-button>
          </div>
          <div>
            <el-button class="btnClass" @click="btnSort" :disabled="!isDrag" >保存排序</el-button>
          </div>
        </div>
      </div>

      <!--分组项目信息 -->
      <div>
        <CustomerOrgGroupAsbitem :customerOrgGroup="form" />
      </div>
     
    </el-card>    

    <!-- 新增或者编辑弹框 -->
    <el-dialog
      :title="form.id ? '编辑' : '新增'"
      :visible.sync="dialogVisible"
      width="800px"
    >
      <el-form :model="form" label-width="80px" :rules="rules" ref="form">
        <el-row>
          <el-col :span="8">
            <el-form-item prop="displayName" label="分组名称">
              <el-input v-model="form.displayName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="价格">
              <el-input v-model="form.price"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="适用性别">
              <el-select v-model="form.forSexId" placeholder="请选择">
                <el-option
                  v-for="item in dict.forSex"
                  :key="item.id"
                  :label="item.displayName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="婚姻状况">
              <el-select
                v-model="form.maritalStatusId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in dict.forMaritalStatus"
                  :key="item.id"
                  :label="item.displayName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="年龄下限">
              <el-input v-model="form.ageLowerLimit"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="年龄上限">
              <el-input v-model="form.ageUpperLimit"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="适用职务">
              <el-input v-model="form.jobPost"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="适用职称">
              <el-input v-model="form.jobTitle"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注">
              <el-input v-model="form.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit('form')">确 定</el-button>
      </span>
    </el-dialog>
    <!--  -->
  </div>
</template>
<script>
import moment from "moment";
import Sortable from "sortablejs";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { mapState } from "vuex";
import { dddw, deepCopy, objCopy, arrayExistObj } from "../../utlis/proFunc";

import CustomerOrgGroupAsbitem from "../../components/customerOrg/customerOrgGroupAsbitem.vue";

export default {
  components: {
    CustomerOrgGroupAsbitem,
  },
  data() {
    return {
      customerOrg: [], //体检单位
      customerOrgGroups: [], //体检单位分组
      customerOrgId: "", //当前选中的体检单位id
      customerOrgRegisterList: [], //体检次数列表
      customerOrgRegister: {}, //体检次数

      isDrag: false,
      form: {
        //体检单位分组
        customerOrgId:'',   //复制分组时用到
        id: "",
        customerOrgRegisterId: null, //所属体检次数
        displayName: "",
        price: 0,
        forSexId: "A",
        maritalStatusId: "A",
        ageLowerLimit: 0,
        ageUpperLimit: 200,
        jobPost: "",
        jobTitle: "",
        remark: "",
        isMaxMedicalTimes: "N",
      },
      formInit: {},
      rules: {
        displayName: [
          { required: true, message: "请填写分组名称", trigger: "blur" },
        ],
      },

      dialogVisible: false,      
    
    };
  },
  computed: {
    ...mapState(["personnelUnit", "window", "dict"]),
  },
  created() {
    this.rowDrop();
    this.formInit = deepCopy(this.form);
  },
  mounted() {
    //获取初始数据（单位、适用性别）
    this.dictInit();
  },
  methods: {
    moment,
    dddw,deepCopy,
    
    //确定排序
    btnSort() {
      const result = [];
      this.customerOrgGroups.forEach((item, index) => {        
        result.push({ id: item.id, displayOrder: index });       
      });
      putapi("/api/app/customerorggroup/updatesortmany", {
        itemList: result,
      }).then((res) => {
        this.$message.success("操作成功");
        this.isDrag = false;
      });
    },

    //初始化Sortable组件
    rowDrop() {
      // this.$nextTick(() => {
      //   const tbody = document.querySelector(".el-table__body-wrapper tbody");
      //   const _this = this;
      //   Sortable.create(tbody, {
      //     handle: ".move",
      //     animation: 300,
      //     onEnd({ newIndex, oldIndex }) {
      //       _this.isDrag = false;
      //       const currRow = _this.customerOrgGroups.splice(oldIndex, 1)[0];
      //       _this.customerOrgGroups.splice(newIndex, 0, currRow);
      //       _this.customerOrgGroups.map((item, index) => {
      //         if (index == newIndex && index == oldIndex) {
      //         } else if (index == oldIndex) {
      //         } else if (index == newIndex) {
      //         }
      //       });
      //       console.log(_this.customerOrgGroups.map((item) => item.displayOrder));
      //     },
      //   });
      // });
    
      this.$nextTick(() => {
        const el = document.querySelector(".el-table__body-wrapper tbody");
        //console.log('el0',el)
        const that = this;
        Sortable.create(el, {
          handle: ".move",
          animation: 300,
          //拖拽结束
          onEnd({ newIndex, oldIndex }) {            
            that.isDrag = true;
            const currRow = that.customerOrgGroups.splice(oldIndex, 1)[0];
            that.customerOrgGroups.splice(newIndex, 0, currRow);  
            console.log('el',el)         
          },
        });
      });
    },


    //置底
    btnSetBottom() {
      if (!this.form.id) {
        this.$message.warning("请选择操作的数据");
        return
      } 
      let lfind = arrayExistObj(this.customerOrgGroups,'id',this.form.id)
      let currentRow = {}

      putapi(
        `/api/app/customerorggroup/updatemanysort?id=${this.form.id}&SortType=2`
      ).then((res) => {
        this.$message.success("操作成功");
        currentRow = this.customerOrgGroups.splice(lfind,1)[0]  //删除并赋值
        this.customerOrgGroups.unshift(currentRow)
        this.$refs['customerOrgGroups'].setCurrentRow(currentRow); 
      });
      
    },

    //置顶
    btnSetTop() {
      if (!this.form.id) {
        this.$message.warning("请选择操作的数据");
        return
      }

      let lfind = arrayExistObj(this.customerOrgGroups,'id',this.form.id)
      let currentRow = {}
       
      putapi(
        `/api/app/customerorggroup/updatemanysort?id=${this.form.id}&SortType=1`
      ).then((res) => {
        this.$message.success("操作成功");
        currentRow = this.customerOrgGroups.splice(lfind,1)[0]
        this.customerOrgGroups.unshift(currentRow)
        this.$refs['customerOrgGroups'].setCurrentRow(currentRow); 
      });
      
    },

    //选中颜色
    handleRowClassName({ row, rowIndex }) {
      // highLightBg 为 'selected'的高亮 
      //console.log(rowIndex, row)
      //return row.highLightBg == 'selected' ? 'high-light-bg' : '';
      if (row.choosed) {
        return 'current-row';
      } else {
        return '';
      }

    },

    //获取初始数据
    dictInit() {
      //获取单位列表
      getapi("/api/app/customer-org/parent-all").then((res) => {
        if (res.code != -1) {
          this.customerOrgAll = res.data;
          let lfind = arrayExistObj(this.customerOrgAll,"id",this.dict.personOrgId);
          if (lfind > -1) this.customerOrgAll.splice(lfind, 1);
          this.customerOrg = deepCopy(this.customerOrgAll)
        }
      });

      //获取适用性别
      getapi("/api/app/for-sex").then((res) => {
        if (res.code != -1) {
          this.dict.forSex = res.data;
        }
      });
    },

    //获取体检次数下的分组
    getCustomerOrgGroup(customerOrgRegisterId) {
      this.isDrag = false
      objCopy(this.formInit,this.form)
      this.form.customerOrgRegisterId = customerOrgRegisterId
      this.customerOrgGroups = [];
      getapi(
        `/api/app/customerorggroup/getlistinfilter?CustomerOrgRegisterId=${customerOrgRegisterId}`
      ).then((res) => {
        if (res.code != -1) {
          this.customerOrgGroups = res.data.items;
          this.customerOrgGroups.forEach((e) => {
            e.customerOrgRegisterId = customerOrgRegisterId;
          });
        }
      });
    },

    filterMethod(keyWords) {
      if (keyWords) {
        this.customerOrg = [];
        this.customerOrgAll.forEach(item => {
          if (item.displayName.toLowerCase().indexOf(keyWords.toLowerCase()) > - 1
            || item.simpleCode.toLowerCase().indexOf(keyWords.toLowerCase()) > - 1
            // || item.shortName.toLowerCase().indexOf(keyWords.toLowerCase()) > - 1
            ) {
            this.customerOrg.push(item);
          }
        });
      } else {
        this.customerOrg = deepCopy(this.customerOrgAll);
      }
    },

    //选择单位
    changeCustomerOrg(v) {
      getapi(
        `/api/app/customerorgregister/getlistincustomerorgid?CustomerOrgId=${v}`
      ).then((res) => {
        if (res.code != -1) {
          this.customerOrgRegisterList = res.data;
          if (res.data.length > 0) {
            this.customerOrgRegister = res.data[res.data.length - 1];
            this.getCustomerOrgGroup(this.customerOrgRegister.id);
          } else {
            this.customerOrgRegister = {};
            this.customerOrgGroups = [];    
            this.isDrag = false        
          }
          objCopy(this.formInit,this.form)
        }
      });
    },

    //选择体检次数
    changeTimes(v) {
      this.getCustomerOrgGroup(v.id);
    },

    
    //点击分组
    rowClick(row) {     
      objCopy(row, this.form);      
    },

    //新增弹框
    btnAdd() {
      if (!this.customerOrgRegister.id) {
        this.$message.warning("请选择体检次数");
        return;
      }
      if (this.customerOrgRegister.isComplete.toUpperCase() == "Y") {
        this.$message.warning("该单位的该次体检次数已完成，不能再添加分组！");
        return;
      }

      this.form = deepCopy(this.formInit);
      this.form.customerOrgRegisterId = this.customerOrgRegister.id;
      this.form.customerOrgId = this.customerOrgId;
      this.dialogVisible = true;
    },

    //编辑弹框
    btnEdit() {
      this.dialogVisible = true;
    },

    //删除
    btnDel() {
      if (!this.form.id) {
        this.$message.warning("请选择需要操作的数据");
        return;
      }

      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "是",
        cancelButtonText: "  否  ",
        type: "warning",
      })
        .then(() => {
          return deletapi(`/api/app/customer-org-group/${this.form.id}`);
        })
        .then((res) => {
          if (res.code != -1) {
            this.$message.success("删除成功");
            let lfind = arrayExistObj(
              this.customerOrgGroups,
              "id",
              this.form.id
            );
            if (lfind > -1) this.customerOrgGroups.splice(lfind, 1);
            objCopy(this.formInit,this.form)
            this.isDrag = false
          }
        })
        .catch((err) => {
          if (err == "cancel") {
            this.$message.info("已取消删除");
          }
        });
    },

    onSubmit(formName) {
      this.$refs[formName].validate((valid, fields) => {
        if (!valid) {
          this.$message.warning(fields[Object.keys(fields)[0]][0].message);
          return false;
        }

        if (!this.form.customerOrgRegisterId) {
          this.$message.warning("请选择单位体检次数！");
          return false;
        }

        let body = deepCopy(this.form);
        delete body.id;
        delete body.customerOrgId;

        if (this.form.id) {
          //编辑
          putapi(`/api/app/customer-org-group/${this.form.id}`, body).then(
            (res) => {
              if (res.code != -1) {
                this.$message.success("操作成功！");
                let lfind = arrayExistObj(
                  this.customerOrgGroups,
                  "id",
                  this.form.id
                );
                if (lfind > -1)
                  objCopy(this.form, this.customerOrgGroups[lfind]);
                this.dialogVisible = false;
              }
            }
          );
        } else {
          //新增
          postapi(
            "/api/customerorggroup/createcustomerorggroupincustomerorgregister",
            body
          ).then((res) => {
            if (res.code != -1) {
              this.$message.success("操作成功！");
              this.form.id = res.data.id;
              this.customerOrgGroups.push(deepCopy(res.data));
              this.$refs['customerOrgGroups'].setCurrentRow(this.customerOrgGroups[this.customerOrgGroups.length - 1]);              
              this.dialogVisible = false;
            }
          });
        }
      });
    },
  },
};
</script>
<style scoped>
@import "../../assets/css/global_button.css";
@import "../../assets/css/global_dialog.css";
@import "../../assets/css/global_table.css";
@import "../../assets/css/global_form.css";
@import "../../assets/css/global_input.css";
@import "../../assets/css/global.css";

.btnClass {
  width:100px;
  margin-bottom: 5px
}
</style>