<template>
  <div class="welfare">
    <!-- form -->
    <a-form-model ref="form" layout="vertical" :model="form" :rules="formRules">
      <a-row :gutter="30">
        <a-col :xl="5" :lg="6" :sm="12">
          <a-form-model-item label="保险公司" prop="payorCode">
            <a-select v-model="form.payorCode" placeholder="请选择保险公司" show-search allow-clear @change="payorChange" :filterOption="filterCode">
              <a-select-option v-for="item in companyCode" :key="item.payorCode" :value="item.payorCode">
                {{ item.longName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="5" :lg="6" :sm="12">
          <a-form-model-item label="客户公司名称" prop="corpCode">
            <a-select v-model="form.corpCode" placeholder="请选择客户公司名称" show-search allow-clear :filterOption="filterCode" @change="corpChange">
              <a-select-option v-for="item in corpCode" :key="item.corpCode" :value="item.corpCode">
                {{ item.longName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="5" :lg="6" :sm="12">
          <a-form-model-item label="保险计划" prop="planCode">
            <a-select v-model="form.planCode" placeholder="请选择保险计划" show-search allow-clear :filterOption="filterCode">
              <a-select-option v-for="item in planCode" :key="item.planCode" :value="item.planCode">
                {{ item.longName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="9" :lg="6" :sm="12" class="none-label">
          <a-form-model-item label="button">
            <a-button type="primary" class="mar-left10" @click="handlerSearch">
                <Icon name="ssisearch_active" :size="14" />查询
            </a-button>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <div>
      <div class="none-label mar-bottom10">
        <a-button type="primary" @click="editPlanData(null)">
          <Icon name="ssiadd" :size="14" />新增计划
        </a-button>
      </div>
      <a-table :scroll="{ x: 1110 }"
        :columns="columns"
        :locale="{ emptyText: 'No Data' }"
        :data-source="planData"
        row-key="coverageCode"
        :pagination="false"
      >
        <template slot="operation" slot-scope="record">
          <!-- <a-button type="link" @click.stop="editPlanData(record, true)">新增</a-button> -->
          <a-button type="link" @click.stop="editPlanData(record)">修改</a-button>
          <!-- <a-popconfirm
            title="你确定要删除吗？"
            ok-text="确定"
            cancel-text="取消"
            @confirm="deleteData"
          >
            <a-button type="link" class="danger">删除</a-button>
          </a-popconfirm> -->
        </template>
        <template slot="expandedRowRender" slot-scope="record">
          <condition class="mar-bottom10" :form-data="{...record, conditionType: '03'}"/>
          <coverages :corpCode="corpCode" :planCode="planCode" :formData="{ ...record }" />
        </template>
      </a-table>
      <BurtPagination :pagination="{ ...pager, total }" @pageChange="pageChange"/>
    </div>
    <a-modal
      title="计划管理"
      v-model="isPlanEditShow"
      :footer="null"
      width="50%"
      @cancel="cancel"
    >
      <a-form-model ref="editForm" layout="vertical" :model="editForm" :rules="editRule">
        <!-- <a-form-model-item label="保险公司" prop="payorCode">
          <a-input disabled v-model="editForm.payorCode"> </a-input>
        </a-form-model-item>
        <a-col :md="12">
        <a-form-model-item label="客户公司名称" prop="corpCode">
          <a-input disabled v-model="editForm.corpCode"> </a-input>
        </a-form-model-item> -->
        <a-row :gutter="20">
          <a-col :md="12">
            <!-- <a-form-model-item label="计划编号" prop="planCode">
              <a-input v-model="editForm.planCode" disabled></a-input>
            </a-form-model-item> -->
            <a-form-model-item label="计划全称" prop="longName">
              <a-input v-model="editForm.longName"></a-input>
            </a-form-model-item>
            <a-form-model-item label="英文名称" prop="englishName">
              <a-input v-model="editForm.englishName"></a-input>
            </a-form-model-item>
            <!-- <a-form-model-item label="生效日期" prop="effectiveDate">
              <a-date-picker v-model="editForm.effectiveDate" placeholder="请选择生效日期" value-format="YYYY-MM-DD 00:00:00"></a-date-picker>
            </a-form-model-item> -->
            <a-form-model-item label="地区限制" prop="regionalRestrictions">
              <a-select v-model="editForm.regionalRestrictions" placeholder="请选择地区限制" show-search allow-clear :filterOption="filterCode">
                <a-select-option v-for="item in areaCode" :key="item.refcd" :value="item.refcd" :label="item.descCh">{{ item.descCh }}</a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item label="医院限制" prop="hospitalRestrictions">
              <a-select v-model="editForm.hospitalRestrictions" placeholder="请选择医院限制" show-search allow-clear :filterOption="filterCode">
                <a-select-option v-for="item in hosCode" :key="item.refcd" :value="item.refcd" :label="item.descCh">{{ item.descCh }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="12">
            <a-form-model-item label="公司名称" prop="corpCode">
              <a-select v-model="editForm.corpCode" disabled>
              <a-select-option v-for="item in corpCode" :key="item.corpCode" :value="item.corpCode">
                {{ item.longName }}
              </a-select-option>
              </a-select>
              <!-- <a-input v-model="editForm.corpCode" disabled></a-input> -->
            </a-form-model-item>
            <a-form-model-item label="计划简称" prop="shortName">
              <a-input v-model="editForm.shortName"></a-input>
            </a-form-model-item>
            <a-form-model-item label="等待期(天)" prop="waitingPeriod">
              <a-input-number v-model="editForm.waitingPeriod"></a-input-number>
            </a-form-model-item>
            <a-form-model-item label="备注" prop="remarks">
              <a-textarea v-model="editForm.remarks" :autoSize="{ minRows: 2, maxRows: 5 }"></a-textarea>
            </a-form-model-item>
            <!-- <a-form-model-item label="失效日期" prop="terminationDate">
              <a-date-picker v-model="editForm.terminationDate" placeholder="请选择失效日期" value-format="YYYY-MM-DD 00:00:00"></a-date-picker>
            </a-form-model-item> -->
          </a-col>
        </a-row>
        <a-form-model-item class="text-r">
          <a-button type="primary" @click="savePlanData">
            <Icon name="ssiadd" :size="14" />保存
          </a-button>
          <a-button class="mar-left10" @click="cancel">取消</a-button>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import BurtPagination from "@/components/CUSTOMER/pagation";
import condition from "./components/condition";
import coverages from "./components/coverages";
// import moment from 'moment'
export default {
  beforeRouteUpdate(to, from, next) {
    this.$refs.form.resetFields();
    this.planData = [];
    next();
  },
  components: {
    BurtPagination,
    condition,
    coverages,
  },
  data() {
    // const dateFormat = (val) => {
    //   return val && moment(val).format('YYYY-MM-DD')
    // }
    const columns = [
      // { title: "计划责任", dataIndex: "planCode", width: 180 },
      { title: "计划全称", dataIndex: "longName", width: 180},
      { title: "简称", dataIndex: "shortName", width: 130, ellipsis: true },
      // { title: "起始日期", dataIndex: "effectiveDate", width: 130, customRender: dateFormat },
      // { title: "终止日期", dataIndex: "terminationDate", width: 130, customRender: dateFormat },
      { title: "医院限制", dataIndex: "hospitalRestrictions", width: 130, customRender: (val) => {
        for(let i = 0; i < this.hosCode.length; i ++) {
          if (val === this.hosCode[i].refcd) {
            return this.hosCode[i].descCh
          }
        }
        return val;
      }},
      // { title: "医院限制", dataIndex: "status", width: 180 },
      // { title: "计划限额", dataIndex: "status", width: 180 },
      // { title: "限额消耗", dataIndex: "waitingPeriod" },
      { title: "等待期", dataIndex: "waitingPeriod", width: 120 },
      { title: "更新日期", dataIndex: "modifierDate",  width: 180},
      { title: "备注", dataIndex: "remarks" },
      {
        title: "操作",
        key: "operation",
        width: "150px",
        fixed: "right",
        align: 'center',
        scopedSlots: { customRender: "operation" },
      },
      //   { title: "保单号码", dataIndex: "policyNo", width: 190 },
      //   { title: "保险有效日期", dataIndex: "startDate", width: 180 },
      //   { title: "保险终止日期", dataIndex: "endDate", width: 180 },
    ];
    return {
      isPlanEditShow: false,
      columns,
      form: {
        payorCode: undefined,
        corpCode: undefined,
        planCode: undefined,
      },
      searchForm: {},
      editForm: {
        isEffective: '',
        hospitalRestrictions: ''
      },
      planData: [],
      companyCode: [],
      corpCode: [],
      planCode: [],
      areaCode: [],
      hosCode: [],
      queryForm: {},
      pager: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      formRules: {
        payorCode: [{ required: true, message: "请选择保险公司" }],
        corpCode: [{ required: true, message: "请选择客户公司名称" }],
        // planCode: [{ required: true, message: "请选择保险计划" }],
      },
      editRule: {
        planCode: [{ required: true, message: "请输入保险计划内容" }],
        longName: [{ required: true, message: "请输入保险计划全称" }],
        // shortName: [{ required: true, message: "请输入保险计划简称" }],
        effectiveDate: [{ required: true, message: "请选择生效日期" }],
        terminationDate: [{ required: true, message: "请选择失效日期" }],
        hospitalRestrictions: [{ required: true, message: "请选择医院限制" }]
      },
    };
  },
  mounted() {
    if (this.$route.query && this.$route.query.planCode) {
      this.form = this.$route.query;
      this._getCorporateCode(this.$route.query.payorCode);
      this._getPlanCode(this.$route.query.corpCode);
      this.$nextTick(this.handlerSearch)
    }
    this._getPayorCode();
    this.initCodeData();
  },
  methods: {
    handlerSearch() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return false;
        }
        this.searchForm = this.$lodash.cloneDeep(this.form);
        this.pager.pageNum = 1;
        this._getPlanList();
      });
    },
    pageChange(page) {
      const { pageNum } = page;
      this.pager.pageNum = pageNum;
      this._getPlanList();
    },
    payorChange(val) {
      this.form.corpCode = undefined;
      this.form.planCode = undefined;
      if (!val) {
        return false;
      }
      this._getCorporateCode(val);
    },
    corpChange(val) {
      this.form.planCode = undefined;
      if (!val) {
        return false;
      }
      this._getPlanCode(val);
    },
    // 选择框筛选
    filterCode(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    cancel() {
      this.$refs.editForm.resetFields();
      this.isPlanEditShow = false;
    },
    deleteData(record) {
      const data = this.$lodash.cloneDeep(record);
      data.status = "2"; // 置为无效状态即删除
      this._editPlanData(data);
    },
    editPlanData(data) {
      if(!data){  //新增
        this.editForm = {
          planCode: '',
          longName: '',
          englishName: '',
          shortName: '',
          corpCode: this.form.corpCode,
        }
      }else{
        this.editForm = this.$lodash.cloneDeep(data);
      }
      this.isPlanEditShow = true;
      // else {
      //   this.$refs.form.validateField(["payorCode", "corpCode"], (error) => {
      //     if (error) {
      //       return false;
      //     }
      //     data = {
      //       payorCode: this.form.payorCode,
      //       corpCode: this.form.corpCode,
      //     };
      //     this.editForm = this.$lodash.cloneDeep(data);
      //     this.isPlanEditShow = true;
      //   });
      // }
      //   data = data || {};
    },
    savePlanData() {
      this.$refs.editForm.validate((valid) => {
        if (!valid) {
          return false;
        }
        this._editPlanData(this.editForm);
      });
    },
    initCodeData() {
      const params = {
        areaCode: {
          modid: "CI",
          refgrp: "POLICY_DIRECT_AREA"
        },
        hosCode: {
          modid: "CI",
          refgrp: "HOSPITAL_RESTRICTIONS"
        },
      }
      for (let i in params) {
        this._getRefcdByRefgrp(params[i], i)
      }
    },
    _editPlanData(data) {
      const fn = data.id ? 'EDITPLANDATA' : 'ADDTPLANDATA' 
      this.$apis[fn](data).then((res) => {
        if (res.returnCode === "0000") {
          this._getPlanList();
          this.$message.success(res.returnMsg || "操作成功");
          this.isPlanEditShow = false;
        } else {
          this.$message.error(res.returnMsg || "操作失败");
        }
      });
    },
    _getPayorCode() {
      this.$apis.GETPAYORCODE({}).then((res) => {
        this.companyCode = res.content || [];
      });
    },
    _getCorporateCode(val) {
      this.$apis.GETCORPORATECODEBYPAYOR({
          longName: "",
          payorCode: val,
        }).then((res) => {
          this.corpCode = res.content || [];
        });
    },
    _getPlanCode(val) {
      this.$apis.GETPLANCODEBYCORP({
          longName: "",
          corpCode: val,
        }).then((res) => {
          this.planCode = res.content || [];
        });
    },
    _getPlanList() {
      const data = {
        ...this.searchForm,
        ...this.pager,
      };
      this.$apis.GETPLANLIST(data).then((res) => {
        this.planData = (res.content && res.content.list) || [];
        this.total = (res.content && res.content.total) || 0;
      });
    },
    _getRefcdByRefgrp(data, prop) {
      if (this[prop] && this[prop].length) {
        return true
      }
      this.$apis.GETREFCDBYREFGRP(data).then((res) => {
        this[prop] = res.content || [];
      });
    },
  },
};
</script>

<style lang="less" scoped>
.welfare {
  .pa(30, 36, 50, 39);
  background-color: #fff;
  .none-label {
    text-align: right;
  }
  .classify {
    .pa(10, 20, 10, 20);
    .mg-t(10);
    .mg-b(10);
    background-color: #f8fafb;
    .ant-btn:not(:first-child) {
      .mg-l(30);
    }
    .save-btn {
      float: right;
    }
  }
  .icon-class {
    .mg-r(10);
  }
}
</style>
