<template>
  <div class="form-content">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="类  型:" prop="wtlx">
            <el-select
              v-model="ruleForm.wtlx"
              placeholder="请选择"
              class="input-width"
              :disabled="isDisable"
              clearable
              @change="ruleForm.wtlxmc = options[ruleForm.wtlx].label"
            >
              <el-option
                v-for="(item,index) in options"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="场次:" prop="apcc">
            <el-select
              v-model="ruleForm.apcc"
              placeholder="请选择"
              clearable
              class="input-w-220"
              :disabled="isDisable"
              @change="handleCCChange"
            >
              <el-option
                v-for="(item, index) in apccOptions"
                :key="index"
                :label="item.apcc"
                :value="item.apcc"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="退款单位:" prop="jsdw">
            <el-select
              v-model="ruleForm.jsdw"
              placeholder="请选择"
              clearable
              class="input-w-220"
              :disabled="isDisable"
              @change="handledwChange"
            >
              <el-option
                v-for="(item, index) in jsdwOptions"
                :key="index"
                :label="item.cmmc"
                :value="item.cmmc"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同:" prop="ht">
            <el-input
              v-if="$route.query.type == 1"
              v-model="ruleForm.htbh"
              class="input-width"
              clearable
              disabled
            ></el-input>
            <el-select
              v-else
              v-model="ruleForm.ht"
              placeholder="请选择"
              clearable
              class="input-w-220"
              :disabled="isDisable"
              multiple
            >
              <el-option
                v-for="(item, index) in htOpts"
                :key="index"
                :label="item.htbh"
                :value="item.htbm"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="通知标题:" prop="tzbt">
            <el-input
              v-model="ruleForm.tzbt"
              class="input-width"
              clearable
              :disabled="isDisable"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="委托函编号:" prop="wthbh">
            <el-input
              v-model="ruleForm.wthbh"
              class="input-width"
              clearable
              :disabled="isDisable"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="正  文:" prop="jszw">
            <el-input
              v-model="ruleForm.jszw"
              type="textarea"
              rows="10"
              clearable
              maxlength="2000"
              show-word-limit
              :disabled="isDisable"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="编制人员:" prop="bzr">
            <el-input
              v-model="ruleForm.bzr"
              class="input-width"
              clearable
              :disabled="isDisable"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="编制时间:" prop="bzsj">
            <el-date-picker
              class="input-width"
              v-model="ruleForm.bzsj"
              type="datetime"
              clearable
              :disabled="isDisable"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%"
              placeholder="选择日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row style="text-align: center">
        <el-form-item v-if="pageObject.type != 3">
          <el-button
            v-if="!isDisable"
            type="primary"
            @click="btnSave(1)"
            class="iconfont icontijiao"
            >发 送</el-button
          >
          <el-button
            v-if="!isDisable"
            type="primary"
            @click="btnSave(2)"
            class="iconfont iconbaocun"
            >保 存</el-button
          >
          <el-button
            type="primary"
            @click="jumpPage"
            class="iconfont iconfanhui"
            >返 回</el-button
          >
        </el-form-item>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import {
  addRefundDelegation,
  updateRefundDelegation,
  getRefundDelegationDetail,
  getOrgTree,
  getTransactionSignUpAll,
  enumStatus,
  selectContractList,
  selectContractByDwbm,
  selectTkdwList,
  selectTkdwHtList,
} from "@/api/transaction/ensureManage";
import { dateTimeFormat } from "@/utils";
function formatData(list) {
  return list.map((item) => {
    let newItem = {};
    newItem.orgName = item.orgName;
    newItem.orgCode = item.orgCode;

    if (item.hasOwnProperty("children") && item.children.length > 0) {
      newItem.children = formatData(item.children);
    }
    return newItem;
  });
}

export default {
  name: "refundDelegationComponet",
  props: {
    pageObject: Object,
  },
  data() {
    let self = this;
    return {
      //type 1.查看 2.编辑 3.预览
      type: self.pageObject.type,
      isDisable:
        self.pageObject.type == 1 || self.pageObject.type == 3 ? true : false,
      options: [
        { label: "退还", value: 0 },
        { label: "抵扣粮款", value: 1 },
        { label: "部分扣除", value: 2 },
        { label: "全部扣除", value: 3 },
      ],
      apccOptions: [],
      jsdwOptions: [],
      htOpts: [],
      jsdwProps: {
        value: "orgName", //orgCode
        label: "orgName",
        children: "children",
      },
      ruleForm: {
        tzbt: "",
        wthbh: "",
        wtlx: "",
        jsdw: "",
        jszw: "",
        bzr: "",
        bzsj: "",
        zt: "",
        ztmc: "",
        wthbm: self.pageObject.wthbm,
        apcc: self.pageObject.apcc,
        ht: [],
      },
      rules: {
        tzbt: [{ required: true, message: "请输入通知标题", trigger: "blur" }],
        wthbh: [
          { required: true, message: "请输入委托函编号", trigger: "blur" },
        ],
        wtlx: [{ required: true, message: "请选择类型", trigger: "change" }],
        jszw: [{ required: true, message: "请输入接收正文", trigger: "blur" }],
        bzr: [{ required: true, message: "请输入编制人", trigger: "blur" }],
        bzsj: [
          { required: true, message: "请选择编制时间", trigger: "change" },
        ],
        apcc: [{ required: true, message: "请选择场次", trigger: "change" }],
        ht: [
          {
            required: true,
            message: "请选择合同",
            trigger: "change",
            type: "array",
          },
        ],
        jsdw: [
          {
            required: true,
            message: "请选择退款单位",
            trigger: "change",
          },
        ],
      },
      statusType: "",
      statusMsg: "",
    };
  },
  created() {
    // alert("1111");
    // this.getOrgList();
    this.getSessionList();
    if (this.ruleForm.wthbm) this.getDetailInfo();
    this.ruleForm.bzsj = dateTimeFormat(new Date());
  },
  methods: {
    // async handleCCChange(val) {
    //   let cur = this.apccOptions.find((d) => d.apcc == val);
    //   let id = cur.ccbm;
    //   this.ruleForm.ccbm = id;
    //   let res = await selectContractList(id);
    //   if (res.infoCode != 200) {
    //     this.jsdwOptions = [];
    //     return;
    //   }
    //   this.jsdwOptions = res.data.data.length ? res.data.data : [];
    //   if (this.jsdwOptions.length) {
    //     this.jsdwOptions.map((item) => {
    //       if (!item.cmmc) {
    //         item.cmmc = item.sgmc;
    //         item.cmdw = item.sgdw;
    //       }
    //     });
    //   }
    // },
    async handledwChange(val) {
      let cur = this.jsdwOptions.find((d) => d.cmmc == val);
      let id = cur.cmdw;
      this.ruleForm.jsdwbm = id;
      let res = await selectTkdwHtList(id);
      if (res.infoCode != 200) {
        this.htOpts = [];
        return;
      }
      this.htOpts = res.data.length ? res.data : [];
    },
    btnSave(type) {
      let status = type === 1 ? enumStatus[1] : enumStatus[0];
      this.ruleForm.zt = status.value;
      this.ruleForm.ztmc = status.label;
      this.statusType = type;
      this.statusMsg = (type === 2 ? "保存" : "发送") + "成功!";
      console.log(this.ruleForm);
      if (type === 2) {
        if (this.statusType == 2) {
          if (this.ruleForm.wthbm) this.updateInfo();
          else this.addInfo();
        } else {
          if (this.ruleForm.wthbm) this.updateInfo();
          else this.addInfo();
        }
      } else {
        this.submitForm("ruleForm");
      }
    },
    submitForm(formName) {
      let self = this;
      self.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.statusType == 2) {
            if (self.ruleForm.wthbm) self.updateInfo();
            else self.addInfo();
          } else {
            if (self.ruleForm.wthbm) self.updateInfo();
            else self.addInfo();
          }
        } else {
          this.$message.warning("请先完成必填项!");
        }
      });
    },
    jumpPage() {
      // this.$router.push({
      // 	name: 'refundDelegationList',
      // })
      this.$router.go(-1);
    },
    getDetailInfo() {
      console.log("852");
      let self = this,
        params = {
          wthbm: this.ruleForm.wthbm,
          apcc: this.ruleForm.apcc,
        };

      getRefundDelegationDetail(params).then((response) => {
        if (response && response.infoCode == 200) {
          self.ruleForm = response.data;
          this.$set(self.ruleForm, "ht", response.data.htbm.split(","));
          self.ruleForm.wtlx = response.data.wtlx;
          if (self.ruleForm.ccbm) {
            // this.getdwList(self.ruleForm.ccbm);
          }
          if (self.ruleForm.jsdw) {
            this.gethtList();
          }
          self.$refs.ruleForm.clearValidate();
        }
      });
    },
    // async getdwList(ccbm) {
    //   console.log("1111");
    //   let res = await selectContractList(ccbm);
    //   if (res.infoCode != 200) {
    //     this.jsdwOptions = [];
    //     return;
    //   }
    //   this.jsdwOptions = res.data.data.length ? res.data.data : [];
    //   if (this.jsdwOptions.length) {
    //     this.jsdwOptions.map((item) => {
    //       if (!item.cmmc) {
    //         item.cmmc = item.sgmc;
    //         item.cmdw = item.sgdw;
    //       }
    //     });
    //   }
    // },
    async gethtList() {
      let res = await selectTkdwHtList(this.ruleForm.jsdwbm);
      if (res.infoCode != 200) {
        this.htOpts = [];
        return;
      }
      this.htOpts = res.data.length ? res.data : [];
    },
    addInfo() {
      // console.log(this.ruleForm);
      let arr = [];
      this.ruleForm.ht.map((item) => {
        this.htOpts.map((item1) => {
          if (item == item1.htbm) {
            arr.push(item1.htbh);
          }
        });
      });
      // console.log(arr, "arr");
      let self = this,
        params = {
          tzbt: self.ruleForm.tzbt,
          wthbh: self.ruleForm.wthbh,
          wtlx: self.ruleForm.wtlx,
          jsdw: self.ruleForm.jsdw,
          jsdwbm: self.ruleForm.jsdwbm,
          jszw: self.ruleForm.jszw,
          bzr: self.ruleForm.bzr,
          bzsj: self.ruleForm.bzsj,
          zt: self.ruleForm.zt,
          ztmc: self.ruleForm.ztmc,
          wthbm: self.pageObject.wthbm,
          apcc: self.ruleForm.apcc,
          htbh: arr.join(","),
          htbm: self.ruleForm.ht.join(","),
          ccbm: self.ruleForm.ccbm,
          url: `/transaction/ensureManage/transactionHandling/detail`,
          itemQuery: JSON.stringify({
            type: "2",
            idKey: "tkbm",
          }),
        };
      addRefundDelegation(params).then(actionMethod).catch(actionMethod);

      function actionMethod(response) {
        if (response && response.infoCode === 200) {
          self.$message.success(self.statusMsg);
          self.jumpPage();
        } else {
          self.$message.error(response.msg);
        }
      }
    },
    updateInfo() {
      console.log(this.ruleForm);
      let arr = [];
      this.ruleForm.ht.map((item) => {
        this.htOpts.map((item1) => {
          if (item == item1.htbm) {
            arr.push(item1.htbh);
          }
        });
      });
      console.log(arr, "arr");
      let self = this,
        params = self.ruleForm;
      let jsdw = self.ruleForm.jsdw;

      params.jsdw = jsdw;
      params.htbm = self.ruleForm.ht.join(",");
      (params.htbh = arr.join(",")),
        (params.url = `/transaction/ensureManage/marginRefundDetail`),
        (params.itemQuery = JSON.stringify({
          type: "2",
          idKey: "tkbm",
          dwmc: "undefined",
        })),
        (params.itemQueryHaveDone = JSON.stringify({
          type: "1",
          idKey: "tkbm",
          dwmc: "undefined",
        }));
      updateRefundDelegation(params).then(actionMethod).catch(actionMethod);

      function actionMethod(response) {
        if (response && response.infoCode === 200) {
          self.$message.success(self.statusMsg);
          self.jumpPage();
        } else {
          self.$message.error(response.msg);
        }
      }
    },
    // getOrgList() {
    //   let self = this;
    //   getOrgTree()
    //     .then(actionMethod)
    //     .catch(actionMethod);

    //   function actionMethod(response) {
    //     if (response && response.infoCode === 200) {
    //       self.jsdwOptions = formatData([response.data]);
    //     }
    //   }
    // },
    getSessionList() {
      selectTkdwList().then((res) => {
        if (res.infoCode == 200) {
          this.jsdwOptions = res.data;
        }
      });
      // let self = this;
      // getTransactionSignUpAll({ pageType: 4 })
      //   .then(actionMethod)
      //   .catch(actionMethod);

      // function actionMethod(response) {
      //   if (response && response.infoCode === 200) {
      //     console.log("apccOptions", response.data);
      //     self.apccOptions = response.data;
      //   }
      // }
    },
  },
};
</script>

<style scoped></style>
